dsh-completion-guard 0.7.0 → 0.8.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.
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
- import { $ as currentV6Feedback, $i as requestedIdentityKey, $n as decideTurnStopping, $r as npmEscapedPackageName, $t as RC015_RC2_HOST_PACKAGES, A as firstStepGuidanceV6, Ai as opensWithDirective, An as CLEANUP_CONDITION_RULE, Ar as capabilityRemedyPhrase, At as BASE_HOST_PACKAGES, B as SessionApiError, Bi as ACTION_MANIFEST, Bn as renderRecoveryPacket, Br as partialFailureOf, Bt as evaluateHostCapability, C as gitCommandMatchesTarget, Ci as itemHoldsExecutionAuthority, Cn as proofV2Rejection, Cr as proposeRebindV042, Ct as parsePwshCommand, D as FIRST_STEP_GUIDANCE, Di as maskQuotedSpans, Dn as sessionQueryV2, Dr as CONFIRM_LINE_PATTERN, Dt as ACTIVE_HOST_LAUNCHER_VERSION, E as verifiedLinearCommitReadback, Ei as maskCodeSpans, En as sessionQuery, Er as replayRebindResult, Et as ACTIVE_HOST_COHORT_IDS, F as HOST_WORKDIR_PREFIX, Fi as restatedContentOf, Fn as carriesCleanupCondition, Fr as DEPENDENCY_FREE_ONLY_CONDITION, Ft as HOST_COHORTS, G as PROTOCOL_V3_NOTICE, Gi as SEMANTIC_ACTIONS, Gn as CONTROL_RECORD_PREFIX, Gr as classifyClause, Gt as LATEST_SUPPORTED_HOST_VERSION, H as projectCoreV2, Hi as BOUNDED_ARTIFACT_TYPES, Hn as evidenceCoverage, Hr as removalIsPartiallyKnown, Ht as evaluateToolSurfaceCapability, I as captureHostWorkdir, Ii as semanticActionOfScope, In as cleanupConditionFor, Ir as actionHasCertificationPath, It as LEGACY_HOST_COHORTS, J as PROTOCOL_V6_NOTICE, Ji as STOP_PROTOCOL_VERSION_V2, Jn as assessmentAction, Jr as extractMethod, Jt as SUPPORTED_HOST_VERSIONS, K as PROTOCOL_V4_NOTICE, Ki as STATEFUL_ACTIONS, Kn as NO_PROGRESS_RECORD_PREFIX, Kr as environmentDefaultRepositoryTarget, Kt as MIN_SUPPORTED_HOST_VERSION, L as sourcedNamedTestRoot, Li as splitTextFragments, Ln as closingHint, Lr as admissibleForRemoval, Lt as bindExecutableIdentity, M as previewFirstStepInjection, Mi as qualificationOfClause, Mn as CLEANUP_CONDITION_RULE_SHORT, Mr as evidenceAvailabilityReason, Mt as EXPECTED_HOST_PACKAGES, N as projectSessionCoreV2, Ni as questionHeadsClause, Nn as DEFAULT_RECOVERY_CHAR_BUDGET, Nr as itemDiagnosis, Nt as GOAL_HOST_PACKAGES, O as claimedBatchHasRealRootInput, Oi as namedActions, On as validateProofManifest, Or as isFrozenV042RebindResponse, Ot as ALPHA2_DSHMARKET_139_HOST_PACKAGES, P as sessionCoreSnapshot, Pi as reportingHeadGoverns, Pn as MIN_RECOVERY_CHAR_BUDGET, Pr as relevantEvidence, Pt as HOST_CAPABILITY_PACKAGE_GROUPS, Q as rootLocatorFlavor, Qi as isStatefulAction, Qn as decideTurnBoundary, Qr as canonicalRegistryBase, Qt as satisfiesSupportedHostRange, R as SESSION_API_UNSUPPORTED, Ri as statefulActionsOfScope, Rn as openItems, Rr as capabilityConsequence, Rt as bindLiveGoalCapability, S as executeRevalidatedGitEffect, Si as isRestatement, Sn as proofOperationMatches, Sr as proposeRebindOutcome, St as isRunExecutable, T as revalidateGitPrestate, Ti as legacyQuestionReadingIsInformational, Tn as scopeCoverageDigest, Tr as rebindResponse, Tt as ACTIVE_HOST_COHORT_ID, U as CAPTURE_V042_NOTICE, Ui as CERTIFICATE_VERSION, Un as evidenceMatchesItem, Ur as captureClause, Ut as hostVersionFromPackages, V as snapshotSessionEvents, Vi as ACTION_MANIFEST_VERSION, Vn as bindingSatisfies, Vr as removalIsComplete, Vt as evaluateHostLock, W as DEFAULT_DELEGATION_TOOL_NAMES, Wi as CERTIFICATE_VERSION_V2, Wn as isVerifyingCapability, Wr as captureItem, Wt as selectHostCohort, X as deriveProjection, Xi as actionCompatible, Xn as classifyCompletionClaim, Xr as isInformationalMessage, Xt as evaluateMinimumHostVersion, Y as applyUpgradeEligibility, Yi as SUPPORTED_EVIDENCE_ADAPTERS, Yn as assessmentOutcomePredicate, Yr as extractOperation, Yt as compareHostVersions, Z as legacyRecordsNeedingReview, Zi as boundedArtifactChoiceMatches, Zn as currentActionBases, Zr as segmentClauses, Zt as parseHostVersion, _ as GIT_COMMAND_MANIFEST_IDS, _i as isExecutableItem, _n as proofCapabilityReport, _r as qualifyBoundary, _t as extractToolSubject, a as auditedForegroundRenderers, aa as validateActionTarget, ai as clarifiedSpanOf, an as certifyCheckpoint, ar as observeAssistantOutcome, at as inFlightReservation, b as commitTreeSnapshotDigest, bi as isOpenObligation, bn as proofEvidenceConstraints, br as confirmRebind, bt as withDurability, c as hostLockRowsFromComposedDump, ca as canonicalizePath, ci as clauseIsProtected, cn as PROOF_KINDS_V2, cr as v6TestPredicate, ct as normalizeSettlement, d as packageRowsFromActiveGraph, da as sanitizeClauseText, di as hasOrderedCoordination, dn as PROOF_PROTOCOL_VERSION_V2, dr as certifiableOpenItems, dt as releaseCoverage, ea as requestedTargetAuthorizesMutation, ei as classifyTaskIntent, en as RC015_HOST_PACKAGES, er as decisionBoundaryKey, et as sourceItemForCoreRequirement, f as packageRowsFromPnpmLock, fa as sanitizeUrl, fi as hasQuestionScope, fn as bindProofToProjection, fr as certificateClosure, ft as releasePreEffectDecision, g as verifyComposedHostLockDump, gi as introducesActionClause, gn as createProofManifestV2, gr as isCurrentAcceptedBoundary, gt as extractTextContent, h as resolveInstalledHostLock, hi as interpretMessage, hn as createProofManifest, hr as effectuateBoundary, ht as evidenceFromPersistedToolResult, i as auditedDefaultWorkdirProvider, ia as validateActionManifest, ii as actionVerbMatches, in as segmentAuthorityBlocks, ir as latestRootInstruction, it as contractById, j as lifecyclePhase, ji as presentExplanationHead, jn as CLEANUP_CONDITION_RULE_COMPACT, jr as deriveItemDiagnosis, jt as DEFAULT_HOST_LOCK, k as firstStepGuidance, ki as opensConditionLead, kn as validateProofManifestV2, kr as parseConfirmationMessage, kt as ALPHA2_HOST_PACKAGES, l as injectActiveProfileHostLock, la as digestStrings, li as explanationHasActionResidue, ln as PROOF_MANIFEST_DOMAIN_V2, lr as goalCompletionDenial, lt as readbackSettlesContract, m as resolveActiveProfileHostLock, mi as interpretClause, mn as canonicalProjection, mr as availableBoundaryQualifications, mt as supersedeItem, n as activeRendererModule, na as semanticActionFromCommand, ni as GRANTED_QUALIFICATION, nn as ALPHA3_HOST_PACKAGES, nr as isWholeTaskCompletionClaim, nt as RELEASE_OPERATIONS, o as combineHostPolicy, oa as COMMAND_SURFACE_MANIFEST, oi as clauseAsksOwnQuestion, on as PROOF_CAPABILITY_MATRIX, or as progressFingerprint, ot as normalizeReleaseContract, p as readActiveHostGraph, pa as sha256, pi as hasWorkPredicate, pn as bindProofV2ToProjection, pr as unitDescendantIds, pt as reservationFor, q as PROTOCOL_V5_NOTICE, qi as STOP_PROTOCOL_VERSION, qn as NO_PROGRESS_TURNS_BEFORE_STOP, qr as extractArtifactPaths, qt as SUPPORTED_HOST_RANGE, r as auditedDefaultWorkdirHost, ra as semanticActionFromText, ri as LEGACY_QUALIFICATION, rn as authorityCaptureCounts, rr as latestAssistantText, rt as RELEASE_OPERATION_SURFACES, s as hostLockContextFromComposedDump, sa as validateManifest, si as clauseIsGoverned, sn as PROOF_KINDS, sr as testOutcomePredicate, st as normalizeReservation, t as HostProfileError, ta as requestedTargetMatchesResolved, ti as classifyUserInteraction, tn as RC1_HOST_PACKAGES, tr as isRootPauseRequest, tt as OUTCOME_STRENGTH, u as inspectTargetHostGraph, ua as normalizeClause, ui as governedClauseRestrictsExecution, un as PROOF_PROTOCOL_VERSION, ur as hasCurrentCertificate, ut as releaseContractFor, v as GIT_COMMAND_TEMPLATES, vi as isExplanationScope, vn as proofDigest, vr as currentContractDigest, vt as isDeterministicCheck, w as parseGitCommandManifest, wi as kindOfScope, wn as requiredSubjectsOf, wr as rebindAttemptKey, wt as parseShellCommand, x as createGitPrestateEnvelope, xi as isQuestionScopeNeedingReview, xn as proofHostSurfacesOf, xr as proposeRebind, xt as canonicalArgvFromCommand, y as commitIndexSnapshotDigest, yi as isInformationalFragment, yn as proofDigestV2, yr as createProjection, yt as persistedToolResultStatus, z as SESSION_EVENT_ENVELOPE_INVALID, zi as verbIsNegated, zn as recoveryDigest, zr as capabilityFactOf, zt as evaluateExternalWaitCapability } from "./domain-B3EuAllT.js";
2
- import { defineTool } from "@deepseek-ai/dsh-tools";
3
- import { createHash } from "node:crypto";
1
+ import { $ as PROOF_KINDS, $i as BOUNDED_ARTIFACT_TYPES, $n as capabilityConsequence, $r as statefulActionsOfScope, $t as reservationFor, A as PROTOCOL_V4_NOTICE, Ai as DEFAULT_HOST_LOCK, An as isCurrentAcceptedBoundary, Ar as interpretMessage, At as carriesCleanupCondition, B as extractToolSubject, Bi as evaluateToolSurfaceCapability, Bn as replayRebindResult, Br as legacyQuestionReadingIsInformational, Bt as sourceItemForCoreRequirement, C as SESSION_EVENT_ENVELOPE_INVALID, Ci as resolveActiveProfileHostLock, Cn as hasCurrentCertificate, Cr as clauseIsProtected, Ct as CLEANUP_CONDITION_RULE_COMPACT, D as CAPTURE_V042_NOTICE, Di as ACTIVE_HOST_COHORT_IDS, Dn as BOUNDARY_RECORD_PREFIX, Dr as hasQuestionScope, Dt as V6_ORDINARY_COMPLETION_RULE, E as projectCoreV2, Ei as ACTIVE_HOST_COHORT_ID, En as unitDescendantIds, Er as hasOrderedCoordination, Et as MIN_RECOVERY_CHAR_BUDGET, F as legacyRecordsNeedingReview, Fi as bindExecutableIdentity, Fn as proposeRebind, Fr as isOpenObligation, Ft as recoveryTitle, G as isRunExecutable, Gi as SUPPORTED_HOST_RANGE, Gn as deriveItemDiagnosis, Gr as opensWithDirective, Gt as inFlightReservation, H as persistedToolResultStatus, Hi as selectHostCohort, Hn as isFrozenV042RebindResponse, Hr as maskQuotedSpans, Ht as RELEASE_OPERATIONS, I as rootLocatorFlavor, Ii as bindLiveGoalCapability, In as proposeRebindOutcome, Ir as isQuestionScopeNeedingReview, It as renderRecoveryPacket, J as authorityCaptureCounts, Ji as evaluateMinimumHostVersion, Jn as nativeFileTwoRole, Jr as questionHeadsClause, Jt as normalizeSettlement, K as parsePwshCommand, Ki as SUPPORTED_HOST_VERSIONS, Kn as evidenceAvailabilityReason, Kr as presentExplanationHead, Kt as normalizeReleaseContract, L as supersedeItem, Li as evaluateExternalWaitCapability, Ln as proposeRebindV042, Lr as isRestatement, Lt as v6CurrentRootBoundaries, M as PROTOCOL_V6_NOTICE, Mi as GOAL_HOST_PACKAGES, Mn as currentContractDigest, Mr as isExecutableItem, Mt as closingHint, N as applyUpgradeEligibility, Ni as HOST_CAPABILITY_PACKAGE_GROUPS, Nn as createProjection, Nr as isExplanationScope, Nt as openItems, O as DEFAULT_DELEGATION_TOOL_NAMES, Oi as ACTIVE_HOST_LAUNCHER_VERSION, On as availableBoundaryQualifications, Or as hasWorkPredicate, Ot as V6_ORDINARY_COMPLETION_RULE_COMPACT, P as deriveProjection, Pi as HOST_COHORTS, Pn as confirmRebind, Pr as isInformationalFragment, Pt as recoveryDigest, Q as PROOF_CAPABILITY_MATRIX, Qi as ACTION_MANIFEST_VERSION, Qn as admissibleForRemoval, Qr as splitTextFragments, Qt as releasePreEffectDecision, R as evidenceFromPersistedToolResult, Ri as evaluateHostCapability, Rn as rebindAttemptKey, Rr as itemHoldsExecutionAuthority, Rt as currentV6Feedback, S as SESSION_API_UNSUPPORTED, Si as readActiveHostGraph, Sn as goalCompletionDenial, Sr as clauseIsGoverned, St as CLEANUP_CONDITION_RULE, T as snapshotSessionEvents, Ti as verifyComposedHostLockDump, Tn as certificateClosure, Tr as governedClauseRestrictsExecution, Tt as DEFAULT_RECOVERY_CHAR_BUDGET, U as withDurability, Ui as LATEST_SUPPORTED_HOST_VERSION, Un as parseConfirmationMessage, Ur as namedActions, Ut as RELEASE_OPERATION_SURFACES, V as isDeterministicCheck, Vi as hostVersionFromPackages, Vn as CONFIRM_LINE_PATTERN, Vr as maskCodeSpans, Vt as OUTCOME_STRENGTH, W as canonicalArgvFromCommand, Wi as MIN_SUPPORTED_HOST_VERSION, Wn as capabilityRemedyPhrase, Wr as opensConditionLead, Wt as contractById, X as bindingIndividuallyAccepted, Xi as satisfiesSupportedHostRange, Xn as DEPENDENCY_FREE_ONLY_CONDITION, Xr as restatedContentOf, Xt as releaseContractFor, Y as segmentAuthorityBlocks, Yi as parseHostVersion, Yn as relevantEvidence, Yr as reportingHeadGoverns, Yt as readbackSettlesContract, Z as certifyCheckpoint, Zi as ACTION_MANIFEST, Zn as actionHasCertificationPath, Zr as semanticActionOfScope, Zt as releaseCoverage, _ as projectSessionCoreV2, _a as RC017_RC2_HOST_PACKAGES, _i as hostLockRowsFromComposedDump, _n as latestRootInstruction, _r as GRANTED_QUALIFICATION, _t as scopeCoverageDigest, a as createGitPrestateEnvelope, aa as STOP_PROTOCOL_VERSION_V2, ai as normalizeClause, an as NO_PROGRESS_RECORD_PREFIX, ar as captureItem, at as bindProofV2ToProjection, b as captureHostWorkdir, bi as packageRowsFromActiveGraph, bn as testOutcomePredicate, br as clarifiedSpanOf, bt as validateProofManifest, c as parseGitCommandManifest, ca as boundedArtifactChoiceMatches, ci as sha256, cn as assessmentOutcomePredicate, cr as extractArtifactPaths, ct as createProofManifestV2, d as FIRST_STEP_GUIDANCE, da as requestedTargetAuthorizesMutation, di as auditedDefaultWorkdirHost, dn as decideTurnBoundary, dr as isInformationalMessage, dt as proofDigestV2, ea as CERTIFICATE_VERSION, ei as verbIsNegated, en as bindingSatisfies, er as capabilityFactOf, et as PROOF_KINDS_V2, f as claimedBatchHasRealRootInput, fa as requestedTargetMatchesResolved, fi as auditedDefaultWorkdirProvider, fn as decideTurnStopping, fr as segmentClauses, ft as proofEvidenceConstraints, g as previewFirstStepInjection, ga as validateActionTarget, gi as hostLockContextFromComposedDump, gn as latestAssistantText, gr as classifyUserInteraction, gt as requiredSubjectsOf, h as lifecyclePhase, ha as validateActionManifest, hi as combineHostPolicy, hn as isWholeTaskCompletionClaim, hr as classifyTaskIntent, ht as proofV2Rejection, i as commitTreeSnapshotDigest, ia as STOP_PROTOCOL_VERSION, ii as digestStrings, in as CONTROL_RECORD_PREFIX, ir as captureClause, it as bindProofToProjection, j as PROTOCOL_V5_NOTICE, ji as EXPECTED_HOST_PACKAGES, jn as qualifyBoundary, jr as introducesActionClause, jt as cleanupConditionFor, k as PROTOCOL_V3_NOTICE, ki as BASE_HOST_PACKAGES, kn as effectuateBoundary, kr as interpretClause, kt as V6_ORDINARY_COMPLETION_RULE_SHORT, l as revalidateGitPrestate, la as isStatefulAction, li as HostProfileError, ln as classifyCompletionClaim, lr as extractMethod, lt as proofCapabilityReport, m as firstStepGuidanceV6, ma as semanticActionFromText, mi as auditedHostImplementation, mn as isRootPauseRequest, mr as npmEscapedPackageName, mt as proofOperationMatches, n as GIT_COMMAND_TEMPLATES, na as SEMANTIC_ACTIONS, ni as validateManifest, nn as evidenceMatchesItem, nr as removalIsComplete, nt as PROOF_PROTOCOL_VERSION, o as executeRevalidatedGitEffect, oa as SUPPORTED_EVIDENCE_ADAPTERS, oi as sanitizeClauseText, on as NO_PROGRESS_TURNS_BEFORE_STOP, or as classifyClause, ot as canonicalProjection, p as firstStepGuidance, pa as semanticActionFromCommand, pi as auditedForegroundRenderers, pn as decisionBoundaryKey, pr as canonicalRegistryBase, pt as proofHostSurfacesOf, q as parseShellCommand, qi as compareHostVersions, qn as itemDiagnosis, qr as qualificationOfClause, qt as normalizeReservation, r as commitIndexSnapshotDigest, ra as STATEFUL_ACTIONS, ri as canonicalizePath, rn as isVerifyingCapability, rr as removalIsPartiallyKnown, rt as PROOF_PROTOCOL_VERSION_V2, s as gitCommandMatchesTarget, sa as actionCompatible, si as sanitizeUrl, sn as assessmentAction, sr as environmentDefaultRepositoryTarget, st as createProofManifest, t as GIT_COMMAND_MANIFEST_IDS, ta as CERTIFICATE_VERSION_V2, ti as COMMAND_SURFACE_MANIFEST, tn as evidenceCoverage, tr as partialFailureOf, tt as PROOF_MANIFEST_DOMAIN_V2, u as verifiedLinearCommitReadback, ua as requestedIdentityKey, ui as activeRendererModule, un as currentActionBases, ur as extractOperation, ut as proofDigest, v as sessionCoreSnapshot, vi as injectActiveProfileHostLock, vn as observeAssistantOutcome, vr as LEGACY_QUALIFICATION, vt as sessionQuery, w as SessionApiError, wi as resolveInstalledHostLock, wn as certifiableOpenItems, wr as explanationHasActionResidue, wt as CLEANUP_CONDITION_RULE_SHORT, x as sourcedNamedTestRoot, xi as packageRowsFromPnpmLock, xn as v6TestPredicate, xr as clauseAsksOwnQuestion, xt as validateProofManifestV2, y as HOST_WORKDIR_PREFIX, yi as inspectTargetHostGraph, yn as progressFingerprint, yr as actionVerbMatches, yt as sessionQueryV2, z as extractTextContent, zi as evaluateHostLock, zn as rebindResponse, zr as kindOfScope, zt as isV6PendingRootWait } from "./domain-D0zTh3O_.js";
2
+ import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
3
+ import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync } from "node:fs";
4
4
  import { basename, delimiter, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+ import { JobId } from "@deepseek-ai/dsh-jobs";
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
5
9
  import { homedir, tmpdir } from "node:os";
6
- import { boundContextSummary, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
7
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync } from "node:fs";
8
10
  import { promisify } from "node:util";
9
11
  import { execFile } from "node:child_process";
10
12
  import { access, readFile, realpath } from "node:fs/promises";
11
- import { fileURLToPath } from "node:url";
12
13
  import { gunzip } from "node:zlib";
13
14
  import { SESSION_FORMAT_VERSION, Session, SessionId } from "@deepseek-ai/dsh-session";
14
15
 
@@ -62,6 +63,18 @@ function createRebindTool(getProjection, prepare) {
62
63
  });
63
64
  }
64
65
 
66
+ //#endregion
67
+ //#region src/tools/cursor-identity.ts
68
+ /** The Session observation watermark advances when a read-only Guard tool
69
+ * records its own result. It is not a change to the current business state.
70
+ * Keep every other core field in cursor identity so changed predicates,
71
+ * actions, coverage, and release state still invalidate a page. */
72
+ function semanticCoreCursorState(core) {
73
+ if (!core) return null;
74
+ const { as_of: _observationWatermark,...semantic } = core;
75
+ return semantic;
76
+ }
77
+
65
78
  //#endregion
66
79
  //#region src/tools/checkpoint-page.ts
67
80
  const LANES = [
@@ -86,7 +99,7 @@ function checkpointPage(p, query, full) {
86
99
  revision: p.contractRevision,
87
100
  evidence: [...p.evidence.values()],
88
101
  items: [...p.items.values()],
89
- ...full.current_feedback === true ? { current_core: p.coreV2 } : {},
102
+ ...full.current_feedback === true ? { current_core: semanticCoreCursorState(p.coreV2) } : {},
90
103
  item_ids,
91
104
  evidence_ids,
92
105
  evidence_scope,
@@ -292,38 +305,70 @@ function bindingTemplate(projection, item) {
292
305
  const action = item.semanticAction;
293
306
  if (!action || action === "generic_run") return void 0;
294
307
  const evidence = evidenceForAction(projection, item);
295
- const effect = evidence.find((entry) => (entry.evidenceRole ?? "effect") === "effect");
296
- if (!effect?.resolvedTarget) return void 0;
297
- const resolved = effect.resolvedTarget;
298
- const resolution = isStatefulAction(action) ? evidence.find((entry) => entry.evidenceRole === "resolution" && sameTuple(entry.resolvedTarget, resolved)) : void 0;
299
- const states = isStatefulAction(action) ? evidence.filter((entry) => entry.evidenceRole === "state" && sameTuple(entry.resolvedTarget, resolved)) : [];
300
- if (isStatefulAction(action) && (!resolution || states.length === 0)) return void 0;
301
- if (isStatefulAction(action) && (!resolution?.expectedTransition?.parameters || !resolution.expectedTransitionDigest)) return void 0;
302
- const observed = isStatefulAction(action) ? Object.assign({}, ...states.map((entry) => entry.observedState ?? {})) : effect.observedState ?? {};
303
- const expectedTransition = isStatefulAction(action) ? resolution.expectedTransition : {
304
- predicateId: ACTION_MANIFEST.actions[action].predicateId,
305
- version: 1,
306
- predParamsKind: "inline",
307
- parameters: expectedParameters(action, resolved, observed)
308
- };
309
- return {
310
- item_id: item.id,
311
- evidence_ids: isStatefulAction(action) ? [
312
- resolution.id,
313
- effect.id,
314
- ...states.map((entry) => entry.id)
315
- ] : [effect.id],
316
- semantic_action: action,
317
- requested_target: targetForTool(item.requestedTarget),
318
- resolved_target: targetForTool(resolved),
319
- observed_state: targetForTool(observed),
320
- expected_transition: expectedTransitionForTool(expectedTransition),
321
- ...isStatefulAction(action) ? {
322
- resolution_evidence_id: resolution.id,
323
- effect_evidence_id: effect.id,
324
- state_evidence_ids: states.map((entry) => entry.id)
325
- } : { effect_evidence_id: effect.id }
326
- };
308
+ const effects = evidence.filter((entry) => (entry.evidenceRole ?? "effect") === "effect");
309
+ for (const effect of effects.reverse()) {
310
+ if (!effect.resolvedTarget) continue;
311
+ const resolved = effect.resolvedTarget;
312
+ const nativeFile = projection.boundaryProtocol === 6 && action === "modify" && !item.legacyFlags?.length && ["edit", "edit_file"].includes(effect.toolName);
313
+ const states = nativeFile ? evidence.filter((entry) => entry.evidenceRole === "state" && entry.causedByCallId === effect.callId) : isStatefulAction(action) ? evidence.filter((entry) => entry.evidenceRole === "state" && sameTuple(entry.resolvedTarget, resolved)) : [];
314
+ const resolution = !nativeFile && isStatefulAction(action) ? evidence.find((entry) => entry.evidenceRole === "resolution" && sameTuple(entry.resolvedTarget, resolved)) : void 0;
315
+ if (isStatefulAction(action) && !nativeFile && (!resolution || states.length === 0 || !resolution.expectedTransition?.parameters || !resolution.expectedTransitionDigest)) continue;
316
+ const candidates = nativeFile ? states.map((state) => [state]) : [states];
317
+ for (const chosen of candidates) {
318
+ if (nativeFile && chosen.length !== 1) continue;
319
+ const observed = nativeFile ? { post_digest: chosen[0]?.observedState?.post_digest ?? "" } : isStatefulAction(action) ? Object.assign({}, ...chosen.map((entry) => entry.observedState ?? {})) : effect.observedState ?? {};
320
+ const expectedTransition = nativeFile ? {
321
+ predicateId: ACTION_MANIFEST.actions[action].predicateId,
322
+ version: 1,
323
+ predParamsKind: "inline",
324
+ parameters: observed
325
+ } : isStatefulAction(action) ? resolution.expectedTransition : {
326
+ predicateId: ACTION_MANIFEST.actions[action].predicateId,
327
+ version: 1,
328
+ predParamsKind: "inline",
329
+ parameters: expectedParameters(action, resolved, observed)
330
+ };
331
+ const binding = {
332
+ itemId: item.id,
333
+ evidenceIds: nativeFile ? [effect.id, chosen[0].id] : isStatefulAction(action) ? [
334
+ resolution.id,
335
+ effect.id,
336
+ ...chosen.map((entry) => entry.id)
337
+ ] : [effect.id],
338
+ semanticAction: action,
339
+ requestedTarget: item.requestedTarget,
340
+ resolvedTarget: resolved,
341
+ observedState: observed,
342
+ expectedTransition,
343
+ ...nativeFile ? {
344
+ effectEvidenceId: effect.id,
345
+ stateEvidenceIds: [chosen[0].id]
346
+ } : isStatefulAction(action) ? {
347
+ resolutionEvidenceId: resolution.id,
348
+ effectEvidenceId: effect.id,
349
+ stateEvidenceIds: chosen.map((entry) => entry.id)
350
+ } : { effectEvidenceId: effect.id }
351
+ };
352
+ if (!bindingIndividuallyAccepted(projection, item, binding)) continue;
353
+ return {
354
+ item_id: item.id,
355
+ evidence_ids: binding.evidenceIds,
356
+ semantic_action: action,
357
+ requested_target: targetForTool(item.requestedTarget),
358
+ resolved_target: targetForTool(resolved),
359
+ observed_state: targetForTool(observed),
360
+ expected_transition: expectedTransitionForTool(expectedTransition),
361
+ ...nativeFile ? {
362
+ effect_evidence_id: effect.id,
363
+ state_evidence_ids: [chosen[0].id]
364
+ } : isStatefulAction(action) ? {
365
+ resolution_evidence_id: resolution.id,
366
+ effect_evidence_id: effect.id,
367
+ state_evidence_ids: chosen.map((entry) => entry.id)
368
+ } : { effect_evidence_id: effect.id }
369
+ };
370
+ }
371
+ }
327
372
  }
328
373
  function openItemForTool(projection, item) {
329
374
  const action = item.semanticAction ?? "generic_run";
@@ -357,7 +402,7 @@ function openItemForTool(projection, item) {
357
402
  predicate: {
358
403
  predicate_id: spec.predicateId,
359
404
  version: 1,
360
- parameters_source: isStatefulAction(action) ? "resolution_evidence_expected_transition" : "versioned_action_manifest",
405
+ parameters_source: nativeFileTwoRole(projection, item) ? "native_state_readback" : isStatefulAction(action) ? "resolution_evidence_expected_transition" : "versioned_action_manifest",
361
406
  resolved_target_keys: spec.resolvedTargetKeys,
362
407
  observed_state_keys: spec.observedStateKeys,
363
408
  pred_params_kind: "inline"
@@ -723,6 +768,7 @@ function createCheckpointTool(getProjection, onRejected, prepare = async () => t
723
768
  if (currentFeedback) {
724
769
  const openRows = currentFeedback.openIds.map((id) => {
725
770
  const sourced = sourceItemForCoreRequirement(projection, id);
771
+ const isProhibition = sourced?.item.kind === "prohibition";
726
772
  return {
727
773
  id,
728
774
  reason_code: currentFeedback.predicates[id],
@@ -738,13 +784,20 @@ function createCheckpointTool(getProjection, onRejected, prepare = async () => t
738
784
  semantic_action: sourced.origin.action,
739
785
  target: sourced.origin.target
740
786
  } : sourced?.item.semanticAction ? { semantic_action: sourced.item.semanticAction } : {},
741
- next_step: "Answer this sourced requirement using the current Host observation or final delivery; ordinary Guard bindings are not required."
787
+ next_step: isProhibition ? "This recorded prohibition stays in force; do not perform the action." : "Answer this sourced requirement using the current Host observation or final delivery; ordinary Guard bindings are not required."
788
+ };
789
+ });
790
+ const constraints = Object.entries(currentFeedback.predicates).filter(([, state]) => state === "constraint_active" || state === "constraint_unresolved" || state === "constraint_violated").map(([id, state]) => {
791
+ const sourced = sourceItemForCoreRequirement(projection, id);
792
+ return {
793
+ id,
794
+ reason_code: state,
795
+ ...sourced ? {
796
+ revision: sourced.item.revision,
797
+ text: sourced.item.normalizedText
798
+ } : {}
742
799
  };
743
800
  });
744
- const constraints = Object.entries(currentFeedback.predicates).filter(([, state]) => state === "constraint_active" || state === "constraint_unresolved" || state === "constraint_violated").map(([id, state]) => ({
745
- id,
746
- reason_code: state
747
- }));
748
801
  return checkpointPage(projection, args, {
749
802
  status: currentFeedback.status,
750
803
  reason_code: currentFeedback.reasonCode,
@@ -1326,7 +1379,10 @@ const encodeCursor = (cursor) => Buffer.from(JSON.stringify(cursor), "utf8").toS
1326
1379
  */
1327
1380
  function discoveryItemIds(p) {
1328
1381
  const current = currentV6Feedback(p);
1329
- if (current && current.status !== "unknown") return current.openIds;
1382
+ if (current && current.status !== "unknown") {
1383
+ const standing = Object.entries(current.predicates).filter(([, state]) => state === "constraint_active").map(([id]) => id).sort().filter((id) => !current.openIds.includes(id));
1384
+ return [...current.openIds, ...standing];
1385
+ }
1330
1386
  const pending = [...p.items.values()].filter((item) => item.status === "pending").sort((a, b) => a.revision - b.revision || a.id.localeCompare(b.id));
1331
1387
  if (p.boundaryProtocol === void 0 || p.boundaryProtocol < 5) return pending.map((item) => item.id);
1332
1388
  const closureUnits = new Set([...p.currentUnitId !== void 0 ? [p.currentUnitId, ...unitDescendantIds(p, p.currentUnitId)] : []]);
@@ -1386,10 +1442,40 @@ function createPrepareTool(options) {
1386
1442
  reason_code: "guard_unavailable"
1387
1443
  };
1388
1444
  const currentFeedback = currentV6Feedback(p);
1389
- if (currentFeedback?.status === "unknown") return {
1390
- status: "unknown",
1391
- reason_code: currentFeedback.reasonCode
1392
- };
1445
+ if (currentFeedback?.status === "unknown") {
1446
+ if (args.item_id !== void 0) {
1447
+ const item$1 = sourceItemForCoreRequirement(p, args.item_id)?.item ?? p.items.get(args.item_id);
1448
+ if (item$1) {
1449
+ if (args.item_revision !== void 0 && args.item_revision !== item$1.revision) return {
1450
+ status: "rejected",
1451
+ reason_code: "item_revision_mismatch",
1452
+ item_revision: item$1.revision
1453
+ };
1454
+ return {
1455
+ status: "unknown",
1456
+ reason_code: currentFeedback.reasonCode,
1457
+ item: {
1458
+ id: item$1.id,
1459
+ revision: item$1.revision,
1460
+ kind: item$1.kind,
1461
+ text: item$1.normalizedText,
1462
+ ...item$1.waitAuthorization !== void 0 || item$1.authorityDisposition === "conditional_wait" ? {
1463
+ recorded_wait: {
1464
+ resume_event: item$1.resumeEvent ?? null,
1465
+ condition: item$1.condition ?? null
1466
+ },
1467
+ ...isV6PendingRootWait(p, item$1) ? { wait: "root_condition_pending" } : {}
1468
+ } : {}
1469
+ },
1470
+ next_step: "The recorded text above is a durable read-only fact only; the closure, release, and authorization state stays unknown until the named condition is restored."
1471
+ };
1472
+ }
1473
+ }
1474
+ return {
1475
+ status: "unknown",
1476
+ reason_code: currentFeedback.reasonCode
1477
+ };
1478
+ }
1393
1479
  if (p.boundaryProtocol === 6 && args.item_id !== void 0) {
1394
1480
  const sourced = currentFeedback ? sourceItemForCoreRequirement(p, args.item_id) : void 0;
1395
1481
  const current = sourced?.item ?? p.items.get(args.item_id);
@@ -1403,15 +1489,17 @@ function createPrepareTool(options) {
1403
1489
  };
1404
1490
  if (current.kind === "prohibition" && currentFeedback) {
1405
1491
  const state = currentFeedback.predicates[args.item_id];
1406
- if (state === "constraint_active" || state === "constraint_unresolved" || state === "constraint_violated") return {
1407
- status: state === "constraint_active" ? "active" : state === "constraint_unresolved" ? "unknown" : "incomplete",
1492
+ if (state === "constraint_active" || state === "constraint_unresolved" || state === "constraint_violated" || state === "legacy_review") return {
1493
+ status: state === "constraint_active" ? "active" : state === "constraint_violated" ? "incomplete" : "unknown",
1408
1494
  reason_code: state,
1409
1495
  item: {
1410
1496
  id: current.id,
1411
1497
  revision: current.revision,
1412
- status: state
1498
+ kind: current.kind,
1499
+ status: state,
1500
+ text: current.normalizedText
1413
1501
  },
1414
- next_step: state === "constraint_active" ? "This sourced prohibition remains active." : state === "constraint_unresolved" ? "The current Host facts cannot establish whether this prohibition was respected." : "A sourced Host mutation violated this prohibition."
1502
+ next_step: state === "constraint_active" ? "This sourced prohibition remains active." : state === "constraint_unresolved" ? "The current Host facts cannot establish whether this prohibition was respected." : state === "constraint_violated" ? "A sourced host mutation violated this prohibition." : "This recorded prohibition stays in force as recorded history; current confirmed facts cannot establish its compliance state. Do not perform the action."
1415
1503
  };
1416
1504
  }
1417
1505
  if (current.semanticAction !== "publish" && currentFeedback) {
@@ -1426,7 +1514,15 @@ function createPrepareTool(options) {
1426
1514
  source_item_id: current.id,
1427
1515
  revision: current.revision,
1428
1516
  status: state ?? "historical",
1429
- related_requirement_ids: related.map(([id]) => id)
1517
+ related_requirement_ids: related.map(([id]) => id),
1518
+ text: current.normalizedText,
1519
+ ...current.waitAuthorization !== void 0 || current.authorityDisposition === "conditional_wait" ? {
1520
+ recorded_wait: {
1521
+ resume_event: current.resumeEvent ?? null,
1522
+ condition: current.condition ?? null
1523
+ },
1524
+ ...isV6PendingRootWait(p, current) ? { wait: "root_condition_pending" } : {}
1525
+ } : {}
1430
1526
  },
1431
1527
  next_step: state === void 0 ? "This item is historical and is not current ordinary work." : state === "satisfied" ? "This ordinary predicate is already observed. Continue with the remaining sourced requirements; no Guard execution qualification is needed." : "Use the current sourced action and host facts; no Guard execution qualification is needed."
1432
1528
  };
@@ -1444,7 +1540,6 @@ function createPrepareTool(options) {
1444
1540
  }
1445
1541
  if (args.item_id === void 0) {
1446
1542
  const filter = args.semantic_action ?? null;
1447
- const coreIdentity = currentFeedback ? sha256(JSON.stringify(p.coreV2 ?? null)) : void 0;
1448
1543
  const invalidCursor = (reason_code, note) => ({
1449
1544
  status: "rejected",
1450
1545
  reason_code,
@@ -1452,6 +1547,15 @@ function createPrepareTool(options) {
1452
1547
  contract_revision: p.contractRevision,
1453
1548
  ...note !== void 0 ? { note } : { note: "Re-run discovery without page_cursor to list from the first page." }
1454
1549
  });
1550
+ const eligible = discoveryItemIds(p).map((id) => ({
1551
+ id,
1552
+ sourced: currentFeedback ? sourceItemForCoreRequirement(p, id) : void 0,
1553
+ item: currentFeedback ? sourceItemForCoreRequirement(p, id)?.item : p.items.get(id)
1554
+ })).filter((entry) => entry.item !== void 0).filter(({ item: item$1, sourced }) => filter === null || (sourced?.origin?.action ?? item$1.semanticAction ?? "generic_run") === filter);
1555
+ const coreIdentity = currentFeedback ? sha256(JSON.stringify({
1556
+ core: semanticCoreCursorState(p.coreV2),
1557
+ listing: eligible.map(({ id, item: item$1 }) => [id, item$1.revision])
1558
+ })) : void 0;
1455
1559
  let startAfter;
1456
1560
  if (args.page_cursor !== void 0) {
1457
1561
  let parsed;
@@ -1469,11 +1573,6 @@ function createPrepareTool(options) {
1469
1573
  if ((parsed.f ?? null) !== (filter ?? null)) return invalidCursor("discovery_cursor_filter_mismatch");
1470
1574
  startAfter = parsed.k;
1471
1575
  }
1472
- const eligible = discoveryItemIds(p).map((id) => ({
1473
- id,
1474
- sourced: currentFeedback ? sourceItemForCoreRequirement(p, id) : void 0,
1475
- item: currentFeedback ? sourceItemForCoreRequirement(p, id)?.item : p.items.get(id)
1476
- })).filter((entry) => entry.item !== void 0).filter(({ item: item$1, sourced }) => filter === null || (sourced?.origin?.action ?? item$1.semanticAction ?? "generic_run") === filter);
1477
1576
  const startIndex = startAfter === void 0 ? 0 : eligible.findIndex(({ id, item: item$1 }) => item$1.revision === startAfter[0] && id === startAfter[1]) + 1;
1478
1577
  if (startAfter !== void 0 && startIndex <= 0) return invalidCursor("discovery_cursor_stale", "The cursor names an item no longer in the current listing. Re-run discovery without page_cursor.");
1479
1578
  const page = eligible.slice(startIndex, startIndex + DISCOVERY_ITEM_LIMIT);
@@ -1603,7 +1702,7 @@ function createPrepareTool(options) {
1603
1702
  resolved_target: evidence.resolvedTarget,
1604
1703
  tool_result_seq: evidence.toolResultSeq
1605
1704
  }));
1606
- const requiredOrder = plannedAction && isStatefulAction(plannedAction) ? [
1705
+ const requiredOrder = nativeFileTwoRole(p, item) ? ["effect (the persisted native edit result)", "state (independent context_guard_observe_file readback)"] : plannedAction && isStatefulAction(plannedAction) ? [
1607
1706
  "resolution (prestate facts from a trusted read)",
1608
1707
  "effect (the exact planned change)",
1609
1708
  "state (independent post-state readback)"
@@ -1816,7 +1915,7 @@ function restartIntent(events, resolutionCallId, target) {
1816
1915
  if (!event || event.type !== "user/message") continue;
1817
1916
  const data = record$1(event.data);
1818
1917
  const source = record$1(data?.source);
1819
- if (source?.kind !== "plugin" || source.plugin !== "context-guard" || source.form !== "notice") continue;
1918
+ if (source?.kind !== "plugin" && source?.kind !== "context-guard" || source.plugin !== "context-guard" || source.form !== "notice") continue;
1820
1919
  const content = Array.isArray(data?.content) ? data.content : [];
1821
1920
  const block = content.length === 1 ? record$1(content[0]) : void 0;
1822
1921
  const text = typeof block?.text === "string" ? block.text : "";
@@ -4194,12 +4293,12 @@ function createExternalOperationTool(read, capability) {
4194
4293
  reason_code: "host_jobs_capability_unavailable",
4195
4294
  adapter_id: "dsh.jobs.v1"
4196
4295
  });
4197
- const snapshot = read(args.operation_id, exec.agent);
4198
- return Promise.resolve(snapshot ? {
4199
- status: snapshot.status,
4200
- operation_id: snapshot.id,
4296
+ const snapshot$1 = read(args.operation_id, exec.agent);
4297
+ return Promise.resolve(snapshot$1 ? {
4298
+ status: snapshot$1.status,
4299
+ operation_id: snapshot$1.id,
4201
4300
  reason_code: "external_operation_readback",
4202
- adapter_id: snapshot.adapterId
4301
+ adapter_id: snapshot$1.adapterId
4203
4302
  } : {
4204
4303
  status: "unknown",
4205
4304
  operation_id: args.operation_id,
@@ -4485,7 +4584,7 @@ function createContextGuardCommand(projectionFor, setEnabled, clearContract, lif
4485
4584
  }
4486
4585
 
4487
4586
  //#endregion
4488
- //#region node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.3/node_modules/@deepseek-ai/cosmokit/lib/index.js
4587
+ //#region node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.5/node_modules/@deepseek-ai/cosmokit/lib/index.js
4489
4588
  /** Return true when a value is `null` or `undefined`. */
4490
4589
  function isNullable(value) {
4491
4590
  return value === null || value === void 0;
@@ -4509,6 +4608,43 @@ function pick(source, keys, forced) {
4509
4608
  for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
4510
4609
  return result;
4511
4610
  }
4611
+ /** Shared config references used by schema validators and plugin runtimes. */
4612
+ const write = Symbol.for("cosmokit.volatile.write");
4613
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
4614
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
4615
+ if (value === null || typeof value !== "object") return value;
4616
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
4617
+ ancestors.add(value);
4618
+ try {
4619
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
4620
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
4621
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
4622
+ } finally {
4623
+ ancestors.delete(value);
4624
+ }
4625
+ }
4626
+ /**
4627
+ * Create a detached reference containing an immutable copy of the supplied data.
4628
+ * @param value - validated config data; class instances and functions are unsupported.
4629
+ * @returns a reference whose value is updated only by its owning runtime.
4630
+ */
4631
+ function createVolatile(value) {
4632
+ let current = snapshot(value);
4633
+ return Object.freeze({
4634
+ get: () => current,
4635
+ [write]: (value$1) => {
4636
+ current = value$1;
4637
+ }
4638
+ });
4639
+ }
4640
+ /**
4641
+ * Identify references across ESM/CJS copies of the shared library.
4642
+ * @param value - a parsed config value.
4643
+ * @returns whether the value implements the shared reference protocol.
4644
+ */
4645
+ function isVolatile(value) {
4646
+ return typeof value === "object" && value !== null && write in value;
4647
+ }
4512
4648
  /** Test values using `instanceof` with a `toStringTag` fallback. */
4513
4649
  function is(type, value) {
4514
4650
  if (arguments.length === 1) return (value$1) => is(type, value$1);
@@ -4593,26 +4729,47 @@ function clone(source, refs = /* @__PURE__ */ new Map()) {
4593
4729
  }
4594
4730
  return result;
4595
4731
  }
4596
- /** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
4732
+ /**
4733
+ * Compare values recursively, treating two volatile references as equal regardless of value.
4734
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
4735
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
4736
+ * @param a - first value.
4737
+ * @param b - second value.
4738
+ * @param strict - whether to require strict data equality outside volatile references.
4739
+ * @returns whether the values compare equal.
4740
+ */
4597
4741
  function deepEqual(a, b, strict) {
4598
- if (a === b) return true;
4599
- if (!strict && isNullable(a) && isNullable(b)) return true;
4600
- if (typeof a !== typeof b) return false;
4601
- if (typeof a !== "object") return false;
4602
- if (!a || !b) return false;
4603
- function check(test, then) {
4604
- return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
4742
+ const ancestors = /* @__PURE__ */ new Set();
4743
+ function compare(a$1, b$1) {
4744
+ if (a$1 === b$1) return true;
4745
+ if (isVolatile(a$1) || isVolatile(b$1)) return isVolatile(a$1) && isVolatile(b$1);
4746
+ if (!strict && isNullable(a$1) && isNullable(b$1)) return true;
4747
+ if (typeof a$1 !== typeof b$1 || typeof a$1 !== "object" || !a$1 || !b$1) return false;
4748
+ if (ancestors.has(a$1)) return false;
4749
+ function check(test, then) {
4750
+ return test(a$1) ? test(b$1) ? then(a$1, b$1) : false : test(b$1) ? false : void 0;
4751
+ }
4752
+ ancestors.add(a$1);
4753
+ try {
4754
+ return check(Array.isArray, (a$2, b$2) => {
4755
+ if (a$2.length !== b$2.length) return false;
4756
+ for (let index = 0; index < a$2.length; index++) if (!compare(a$2[index], b$2[index])) return false;
4757
+ return true;
4758
+ }) ?? check(is("Date"), (a$2, b$2) => a$2.valueOf() === b$2.valueOf()) ?? check(is("URL"), (a$2, b$2) => a$2.href === b$2.href) ?? check(is("RegExp"), (a$2, b$2) => a$2.source === b$2.source && a$2.flags === b$2.flags) ?? check(isArrayBufferLike, (a$2, b$2) => {
4759
+ if (a$2.byteLength !== b$2.byteLength) return false;
4760
+ const viewA = new Uint8Array(a$2);
4761
+ const viewB = new Uint8Array(b$2);
4762
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
4763
+ return true;
4764
+ }) ?? ((!strict || [a$1, b$1].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
4765
+ ...a$1,
4766
+ ...b$1
4767
+ }).every((key) => compare(a$1[key], b$1[key])));
4768
+ } finally {
4769
+ ancestors.delete(a$1);
4770
+ }
4605
4771
  }
4606
- return check(Array.isArray, (a$1, b$1) => a$1.length === b$1.length && a$1.every((item, index) => deepEqual(item, b$1[index]))) ?? check(is("Date"), (a$1, b$1) => a$1.valueOf() === b$1.valueOf()) ?? check(is("RegExp"), (a$1, b$1) => a$1.source === b$1.source && a$1.flags === b$1.flags) ?? check(isArrayBufferLike, (a$1, b$1) => {
4607
- if (a$1.byteLength !== b$1.byteLength) return false;
4608
- const viewA = new Uint8Array(a$1);
4609
- const viewB = new Uint8Array(b$1);
4610
- for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
4611
- return true;
4612
- }) ?? Object.keys({
4613
- ...a,
4614
- ...b
4615
- }).every((key) => deepEqual(a[key], b[key], strict));
4772
+ return compare(a, b);
4616
4773
  }
4617
4774
  /** Time constants plus parsing and formatting helpers. */
4618
4775
  var Time;
@@ -4686,7 +4843,7 @@ var Time;
4686
4843
  })(Time || (Time = {}));
4687
4844
 
4688
4845
  //#endregion
4689
- //#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.2/node_modules/@deepseek-ai/schemastery/lib/index.mjs
4846
+ //#region node_modules/.pnpm/@deepseek-ai+schemastery@3.18.4/node_modules/@deepseek-ai/schemastery/lib/index.mjs
4690
4847
  const kSchema = Symbol.for("schemastery");
4691
4848
  const kValidationError = Symbol.for("ValidationError");
4692
4849
  globalThis.__schemastery_index__ ??= 0;
@@ -4862,6 +5019,7 @@ Schema.prototype.pattern = function pattern(regexp) {
4862
5019
  return schema;
4863
5020
  };
4864
5021
  Schema.prototype.simplify = function simplify(value) {
5022
+ if (isVolatile(value)) value = value.get();
4865
5023
  if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
4866
5024
  if (isNullable(value)) return value;
4867
5025
  if (this.type === "object" || this.type === "dict") {
@@ -4918,12 +5076,49 @@ for (const key of [
4918
5076
  };
4919
5077
  return schema;
4920
5078
  } });
5079
+ Schema.prototype.volatile = function volatile() {
5080
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
5081
+ return this.extra("volatile", true);
5082
+ };
4921
5083
  const resolvers = {};
5084
+ const checkedVolatile = Symbol("checked-volatile-schema");
5085
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
5086
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
5087
+ if (states.has(blocked)) return;
5088
+ states.add(blocked);
5089
+ seen.set(schema, states);
5090
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
5091
+ const nested = blocked || !!schema.meta?.volatile;
5092
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
5093
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
5094
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
5095
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
5096
+ }
4922
5097
  Schema.extend = function extend(type, resolve$1) {
4923
5098
  resolvers[type] = resolve$1;
4924
5099
  };
4925
5100
  Schema.resolve = function resolve$1(data, schema, options = {}, strict = false) {
4926
5101
  if (!schema) return [data];
5102
+ if (!options[checkedVolatile]) {
5103
+ validateVolatileSchema(schema, options.path);
5104
+ options = {
5105
+ ...options,
5106
+ [checkedVolatile]: true
5107
+ };
5108
+ }
5109
+ if (schema.meta?.volatile) {
5110
+ const inner = Schema(schema);
5111
+ inner.meta = {
5112
+ ...schema.meta,
5113
+ volatile: false
5114
+ };
5115
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
5116
+ try {
5117
+ return [createVolatile(value), adapted];
5118
+ } catch (error) {
5119
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
5120
+ }
5121
+ }
4927
5122
  if (options.ignore?.(data, schema)) return [data];
4928
5123
  if (isNullable(data) && schema.type !== "lazy") {
4929
5124
  if (schema.meta.required) throw new ValidationError(`missing required value`, options);
@@ -5026,6 +5221,7 @@ Schema.extend("lazy", (data, schema, options, strict) => {
5026
5221
  ...schema.meta,
5027
5222
  ...schema.inner.meta
5028
5223
  };
5224
+ validateVolatileSchema(schema.inner, options.path, true);
5029
5225
  }
5030
5226
  return Schema.resolve(data, schema.inner, options, strict);
5031
5227
  });
@@ -5125,7 +5321,7 @@ function property(data, key, schema, options) {
5125
5321
  } catch (e) {
5126
5322
  if (!options?.autofix) throw e;
5127
5323
  delete data[key];
5128
- return schema.meta.default;
5324
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
5129
5325
  }
5130
5326
  }
5131
5327
  Schema.extend("array", (data, { inner, meta }, options) => {
@@ -5582,11 +5778,11 @@ function appendPrivateLedger(root, input, kind, payload) {
5582
5778
  const expectedContext = contextDigest(context, root);
5583
5779
  const anchored = readAnchors(root).get(session);
5584
5780
  if (anchored !== void 0 && anchored !== expectedContext) return false;
5585
- const snapshot = anchored === void 0 ? {
5781
+ const snapshot$1 = anchored === void 0 ? {
5586
5782
  records: [],
5587
5783
  damaged: false
5588
5784
  } : readPrivateLedger(root, context);
5589
- if (snapshot.damaged) return false;
5785
+ if (snapshot$1.damaged) return false;
5590
5786
  if (anchored === void 0) {
5591
5787
  const unsignedAnchor = {
5592
5788
  version: 1,
@@ -5607,7 +5803,7 @@ function appendPrivateLedger(root, input, kind, payload) {
5607
5803
  }
5608
5804
  if (kind === "release_settlement") {
5609
5805
  const settlement = normalizeSettlement(payload);
5610
- const reservation = settlement && [...snapshot.records].reverse().find((record$3) => record$3.kind === "release_reservation" && record$3.payload.contractId === settlement.contractId && record$3.payload.operation === settlement.operation && record$3.payload.callId === settlement.callId);
5806
+ const reservation = settlement && [...snapshot$1.records].reverse().find((record$3) => record$3.kind === "release_reservation" && record$3.payload.contractId === settlement.contractId && record$3.payload.operation === settlement.operation && record$3.payload.callId === settlement.callId);
5611
5807
  if (!reservation) return false;
5612
5808
  payload = {
5613
5809
  ...payload,
@@ -5620,8 +5816,8 @@ function appendPrivateLedger(root, input, kind, payload) {
5620
5816
  version: 1,
5621
5817
  session_sha256: session,
5622
5818
  context_sha256: expectedContext,
5623
- position: snapshot.records.length + 1,
5624
- prior_sha256: snapshot.records.at(-1)?.record_sha256 ?? null,
5819
+ position: snapshot$1.records.length + 1,
5820
+ prior_sha256: snapshot$1.records.at(-1)?.record_sha256 ?? null,
5625
5821
  kind,
5626
5822
  payload
5627
5823
  };
@@ -5651,8 +5847,8 @@ function appendPrivateLedger(root, input, kind, payload) {
5651
5847
  }
5652
5848
  }
5653
5849
  }
5654
- function applyPrivateLedger(projection, snapshot) {
5655
- if (snapshot.damaged || projection.releaseContracts.length > 0 && snapshot.anchored === false) {
5850
+ function applyPrivateLedger(projection, snapshot$1) {
5851
+ if (snapshot$1.damaged || projection.releaseContracts.length > 0 && snapshot$1.anchored === false) {
5656
5852
  projection.releaseStateDamaged = true;
5657
5853
  if (!projection.releaseDiagnostics.some((row) => row.reasonCode === "private_ledger_damaged")) projection.releaseDiagnostics.push({
5658
5854
  seq: 0,
@@ -5661,7 +5857,7 @@ function applyPrivateLedger(projection, snapshot) {
5661
5857
  return;
5662
5858
  }
5663
5859
  const reservations = /* @__PURE__ */ new Map();
5664
- for (const record$2 of snapshot.records) if (record$2.kind === "release_reservation") {
5860
+ for (const record$2 of snapshot$1.records) if (record$2.kind === "release_reservation") {
5665
5861
  const normalized = normalizeReservation(record$2.payload);
5666
5862
  const contract = normalized && projection.releaseContracts.find((entry) => entry.contractId === normalized.contractId);
5667
5863
  if (!normalized || !contract || record$2.payload.contract_sha256 !== privateLedgerContractDigest(contract) || typeof record$2.payload.target_sha256 !== "string") {
@@ -5705,8 +5901,8 @@ function applyPrivateLedger(projection, snapshot) {
5705
5901
  else if (OUTCOME_STRENGTH[pinned.outcome] >= OUTCOME_STRENGTH[projection.releaseSettlements[index].outcome]) projection.releaseSettlements[index] = pinned;
5706
5902
  }
5707
5903
  }
5708
- function hasPrivateRestartIntent(snapshot, resolutionCallId, serviceId, preGeneration) {
5709
- return !snapshot.damaged && snapshot.records.some((record$2) => record$2.kind === "restart_intent" && record$2.payload.resolution_call_id === resolutionCallId && record$2.payload.service_id === serviceId && record$2.payload.pre_generation === preGeneration);
5904
+ function hasPrivateRestartIntent(snapshot$1, resolutionCallId, serviceId, preGeneration) {
5905
+ return !snapshot$1.damaged && snapshot$1.records.some((record$2) => record$2.kind === "restart_intent" && record$2.payload.resolution_call_id === resolutionCallId && record$2.payload.service_id === serviceId && record$2.payload.pre_generation === preGeneration);
5710
5906
  }
5711
5907
 
5712
5908
  //#endregion
@@ -5842,13 +6038,9 @@ function authorizeMutationFromProjection(projection, request) {
5842
6038
  }
5843
6039
  const PROTOCOL_CORRECTION_NOTICE = "Context Guard protocol correction: root-authorized work remains pending; continue with tools or obtain a typed boundary.";
5844
6040
  /**
5845
- * Establish a boundary Guard itself owns, through the same durable record the
5846
- * boundary tool writes.
5847
- *
5848
- * Replay reads boundaries from the `context_guard_boundary` call/result pair, so
5849
- * a Guard-created boundary is written in exactly that wire shape rather than in
5850
- * a private side channel — otherwise it would not survive a reload, and a
5851
- * boundary that only exists in memory is not a persisted wait or stop.
6041
+ * Establish a Guard-owned boundary as a durable producer notice. V4 Stop hooks
6042
+ * run outside tool steps, so replay requalifies the notice request and verifies
6043
+ * its candidate digest instead of inventing a tool call/result envelope.
5852
6044
  *
5853
6045
  * Returns the boundary only after the durable flush succeeded. A failed flush
5854
6046
  * reports the failure instead of a boundary, because an unflushed record must
@@ -5858,35 +6050,10 @@ async function establishBoundary(agent, runtime, flush, request) {
5858
6050
  const projection = runtime.projection;
5859
6051
  const candidate = qualifyBoundary(projection, request);
5860
6052
  if (candidate.persistedResult !== "accepted") return { reasonCode: candidate.reasonCode };
5861
- const session = agent.session;
5862
- const callId = `guard-boundary-${candidate.id}`;
5863
- session.append("tool/call", {
5864
- turn: 0,
5865
- step: session.seq,
5866
- callId,
5867
- name: "context_guard_boundary",
5868
- arguments: JSON.stringify({
5869
- disposition: request.disposition,
5870
- qualification_kind: request.qualificationKind,
5871
- qualification_ids: request.qualificationIds
5872
- })
5873
- });
5874
- session.append("tool/result", {
5875
- turn: 0,
5876
- step: session.seq,
5877
- message: createToolResultMessage({
5878
- callId,
5879
- content: [{
5880
- type: "text",
5881
- text: JSON.stringify({
5882
- status: candidate.persistedResult,
5883
- reason_code: candidate.reasonCode,
5884
- boundary: { candidate_sha256: candidate.candidateSha256 }
5885
- })
5886
- }],
5887
- isError: false
5888
- })
5889
- }, { surfaceOp: "append" });
6053
+ agent.session.append("user/message", pluginNoticeMessage(`${BOUNDARY_RECORD_PREFIX}${JSON.stringify({
6054
+ request,
6055
+ candidate_sha256: candidate.candidateSha256
6056
+ })}`, "recording a qualified stop boundary"), { surfaceOp: "append" });
5890
6057
  let durable = false;
5891
6058
  try {
5892
6059
  durable = await flush();
@@ -5953,7 +6120,7 @@ async function handleGuardTurnStopping(agent, runtime, access$1) {
5953
6120
  })}`
5954
6121
  }],
5955
6122
  source: {
5956
- kind: "plugin",
6123
+ kind: "context-guard",
5957
6124
  plugin: "context-guard",
5958
6125
  form: "notice",
5959
6126
  summary: boundContextSummary("carrying the root pause request to the host")
@@ -5978,7 +6145,7 @@ async function handleGuardTurnStopping(agent, runtime, access$1) {
5978
6145
  text: record$2
5979
6146
  }],
5980
6147
  source: {
5981
- kind: "plugin",
6148
+ kind: "context-guard",
5982
6149
  plugin: "context-guard",
5983
6150
  form: "notice",
5984
6151
  summary: boundContextSummary("recording a turn boundary without relevant progress")
@@ -6001,7 +6168,7 @@ async function handleGuardTurnStopping(agent, runtime, access$1) {
6001
6168
  text: PROTOCOL_CORRECTION_NOTICE
6002
6169
  }],
6003
6170
  source: {
6004
- kind: "plugin",
6171
+ kind: "context-guard",
6005
6172
  plugin: "context-guard",
6006
6173
  form: "notice",
6007
6174
  summary: boundContextSummary("requesting the one allowed protocol correction step")
@@ -6102,6 +6269,7 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6102
6269
  const projection = createProjection();
6103
6270
  const session = agent.session;
6104
6271
  let pendingRecovery = false;
6272
+ let pendingRecoveryCauses = /* @__PURE__ */ new Set();
6105
6273
  let durabilityConfirmed = false;
6106
6274
  let durabilityWatermark = "unknown";
6107
6275
  let observedEpoch = -1;
@@ -6188,13 +6356,18 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6188
6356
  });
6189
6357
  if (observedEpoch >= 0 && derived.projection.epoch > observedEpoch) {
6190
6358
  pendingRecovery = true;
6359
+ pendingRecoveryCauses.add("guard_reenabled");
6191
6360
  projection.lastRecoveryDigest = void 0;
6192
6361
  }
6193
6362
  observedEpoch = derived.projection.epoch;
6194
- if (observedContractRevision >= 0 && projection.contractRevision !== observedContractRevision) pendingRecovery = true;
6363
+ if (observedContractRevision >= 0 && projection.contractRevision !== observedContractRevision) {
6364
+ pendingRecovery = true;
6365
+ pendingRecoveryCauses.add("contract_updated");
6366
+ }
6195
6367
  observedContractRevision = projection.contractRevision;
6196
6368
  if (derived.lastCompactionSeq > observedCompactionSeq) {
6197
6369
  pendingRecovery = true;
6370
+ pendingRecoveryCauses.add("compaction");
6198
6371
  projection.lastRecoveryDigest = void 0;
6199
6372
  observedCompactionSeq = derived.lastCompactionSeq;
6200
6373
  }
@@ -6210,12 +6383,14 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6210
6383
  durabilityWatermark = confirmed ? "confirmed" : "failed";
6211
6384
  projection.durabilityWatermark = durabilityWatermark;
6212
6385
  };
6213
- const markRecoveryNeeded = () => {
6386
+ const markRecoveryNeeded = (cause) => {
6214
6387
  pendingRecovery = true;
6388
+ pendingRecoveryCauses.add(cause ?? "explicit");
6215
6389
  };
6216
6390
  const consumeRecovery = () => {
6217
6391
  const was = pendingRecovery;
6218
6392
  pendingRecovery = false;
6393
+ pendingRecoveryCauses = /* @__PURE__ */ new Set();
6219
6394
  return was;
6220
6395
  };
6221
6396
  rebuild();
@@ -6234,6 +6409,9 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6234
6409
  get protocolV6Present() {
6235
6410
  return protocolV6Present;
6236
6411
  },
6412
+ get recoveryCauses() {
6413
+ return [...pendingRecoveryCauses];
6414
+ },
6237
6415
  sync,
6238
6416
  setEnabled,
6239
6417
  setDurability,
@@ -6275,6 +6453,12 @@ function revalidateCoreLock(config, expected) {
6275
6453
  goalAvailable: false,
6276
6454
  reasonCode: "host_lock_installed_graph_drift"
6277
6455
  };
6456
+ if (!auditedHostImplementation(config.hostLockRuntimeRoot, config.hostLockProfileRoot)) return {
6457
+ ...actual,
6458
+ status: "unsupported",
6459
+ goalAvailable: false,
6460
+ reasonCode: "host_lock_installed_graph_drift"
6461
+ };
6278
6462
  const audited = auditedForegroundRenderers(config.hostLockRuntimeRoot, config.hostLockProfileRoot);
6279
6463
  return audited.length ? {
6280
6464
  ...actual,
@@ -6292,17 +6476,17 @@ function revalidateCoreLock(config, expected) {
6292
6476
  }
6293
6477
  /** Observe one actual Host dispatch through Cordis without joining its gate. */
6294
6478
  function registerPassiveHostWorkdirObserver(agent, hostLockAtCall, attestedRouteAtCall, sourcedRootAtCall) {
6295
- if (typeof agent.ctx.on !== "function") return;
6479
+ if (typeof agent.ctx.on !== "function") return () => {};
6296
6480
  const pending = /* @__PURE__ */ new WeakMap();
6297
- agent.ctx.on("tools/pre-execute", async (exec, next) => {
6481
+ const pre = agent.ctx.on("tools/pre-execute", async (exec, next) => {
6298
6482
  if (exec.agent === agent && (exec.name === "bash" || exec.name === "pwsh")) try {
6299
6483
  const policy = agent.ctx.get("sandboxPolicy");
6300
- const receipt = captureHostWorkdir(agent.session, exec, hostLockAtCall(), policy, await attestedRouteAtCall(exec.name, agent.ctx.get("shell"), policy), sourcedRootAtCall?.(exec) ?? null);
6484
+ const receipt = captureHostWorkdir(agent.session, exec, hostLockAtCall(), policy, await attestedRouteAtCall(exec.name, agent.ctx.get("shell"), policy), sourcedRootAtCall?.(exec) ?? null, SESSION_FORMAT_VERSION);
6301
6485
  if (receipt) pending.set(exec, receipt);
6302
6486
  } catch {}
6303
6487
  return next();
6304
6488
  });
6305
- agent.ctx.on("tools/post-execute", async (exec, _result, next) => {
6489
+ const post = agent.ctx.on("tools/post-execute", async (exec, _result, next) => {
6306
6490
  const decision = await next();
6307
6491
  const receipt = pending.get(exec);
6308
6492
  pending.delete(exec);
@@ -6313,7 +6497,7 @@ function registerPassiveHostWorkdirObserver(agent, hostLockAtCall, attestedRoute
6313
6497
  text: `${HOST_WORKDIR_PREFIX}${JSON.stringify(receipt)}`
6314
6498
  }],
6315
6499
  source: {
6316
- kind: "plugin",
6500
+ kind: "context-guard",
6317
6501
  plugin: "context-guard",
6318
6502
  form: "notice",
6319
6503
  summary: "read-only Host workdir observation"
@@ -6324,6 +6508,10 @@ function registerPassiveHostWorkdirObserver(agent, hostLockAtCall, attestedRoute
6324
6508
  additionalContexts: [...decision.additionalContexts ?? [], context]
6325
6509
  };
6326
6510
  });
6511
+ return () => {
6512
+ pre();
6513
+ post();
6514
+ };
6327
6515
  }
6328
6516
  function apply(ctx, rawConfig = {}, seams = {}) {
6329
6517
  const config = resolveConfig(rawConfig);
@@ -6340,7 +6528,20 @@ function apply(ctx, rawConfig = {}, seams = {}) {
6340
6528
  cwd: sessionCwd(agent.session) ?? "",
6341
6529
  hostLockDigest: (hostLocks.get(agent) ?? fallback).digest
6342
6530
  });
6343
- const registeredAgents = /* @__PURE__ */ new WeakSet();
6531
+ const registrations = /* @__PURE__ */ new Map();
6532
+ const detach = (agent) => {
6533
+ const disposers = registrations.get(agent);
6534
+ registrations.delete(agent);
6535
+ for (const dispose of disposers?.slice().reverse() ?? []) dispose();
6536
+ runtimes.delete(agent);
6537
+ hostLocks.delete(agent);
6538
+ };
6539
+ ctx.effect?.(() => () => {
6540
+ for (const agent of registrations.keys()) detach(agent);
6541
+ });
6542
+ ctx.on("agent/disposed", ({ agent }) => {
6543
+ detach(agent);
6544
+ });
6344
6545
  const ensure = (agent) => {
6345
6546
  let runtime = runtimes.get(agent);
6346
6547
  if (!runtime) {
@@ -6358,197 +6559,223 @@ function apply(ctx, rawConfig = {}, seams = {}) {
6358
6559
  return runtime;
6359
6560
  };
6360
6561
  ctx.commands.register(createContextGuardCommand((agent) => ensure(agent).projection, (agent, enabled) => ensure(agent).setEnabled(enabled), (agent) => ensure(agent).sync(), (agent) => ensure(agent).lifecycle));
6361
- ctx.on("agent/session-start", ({ agent, source }) => {
6362
- const runtime = ensure(agent);
6363
- runtime.sync();
6364
- if (source === "resume" || source === "compact") {
6365
- runtime.projection.lastRecoveryDigest = void 0;
6366
- runtime.markRecoveryNeeded();
6562
+ const attach = (agent, source) => {
6563
+ if (registrations.has(agent)) {
6564
+ if (source === "resume" || source === "compact") {
6565
+ const runtime = ensure(agent);
6566
+ runtime.sync();
6567
+ runtime.projection.lastRecoveryDigest = void 0;
6568
+ runtime.markRecoveryNeeded(source === "resume" ? "resume" : "compaction");
6569
+ }
6570
+ return;
6367
6571
  }
6368
- if (registeredAgents.has(agent)) return;
6369
- registeredAgents.add(agent);
6370
- registerPassiveHostWorkdirObserver(agent, () => seams.hostLock ?? revalidateCoreLock(config, installedHostLock), (tool, provider, policy) => config.hostLockRuntimeRoot && config.hostLockProfileRoot ? auditedDefaultWorkdirProvider(config.hostLockRuntimeRoot, config.hostLockProfileRoot, tool, provider, policy) : false, (exec) => {
6371
- runtime.sync();
6372
- return sourcedNamedTestRoot(runtime.projection, agent.session, exec.arguments);
6373
- });
6374
- agent.ctx.tools.register(createRebindTool(() => runtime.projection, async () => {
6375
- const durable = await ctx.sessions.flush(agent.session);
6376
- runtime.setDurability(durable);
6377
- runtime.sync();
6378
- return durable;
6379
- }));
6380
- agent.ctx.tools.register(createCheckpointTool(() => runtime.projection, () => runtime.markRecoveryNeeded(), async () => {
6381
- const durable = await ctx.sessions.flush(agent.session);
6382
- runtime.setDurability(durable);
6383
- runtime.sync();
6384
- return durable;
6385
- }));
6386
- agent.ctx.tools.register(createBoundaryTool(() => runtime.projection, async () => {
6387
- const durable = await ctx.sessions.flush(agent.session);
6388
- runtime.setDurability(durable);
6389
- runtime.sync();
6390
- return durable;
6391
- }, () => runtime.markRecoveryNeeded()));
6392
- /** Persist release state outside provider-visible Session history. */
6393
- const persistReleaseRecord = async (toolAgent, kind, payload) => {
6394
- if (toolAgent.session !== agent.session) return false;
6395
- if (!sessionCwd(agent.session)) return false;
6396
- const durable = appendPrivateLedger(privateLedgerRoot, ledgerContext(agent), kind, payload);
6397
- runtime.sync();
6398
- return durable;
6572
+ const disposers = [];
6573
+ registrations.set(agent, disposers);
6574
+ const own = (dispose) => {
6575
+ if (dispose) disposers.push(dispose);
6399
6576
  };
6400
- const evidenceOptions = {
6401
- hostCapability: createHostCapabilityEvaluator(hostLocks.get(agent) ?? installedHostLock),
6402
- ...seams.commandRunner ? { commandRunner: seams.commandRunner } : {},
6403
- ...seams.fetcher ? { fetcher: seams.fetcher } : {},
6404
- ...seams.allowLoopbackHttpRegistry ? { allowLoopbackHttpRegistry: true } : {},
6405
- prepareMutation: async (toolAgent) => {
6406
- if (toolAgent.session !== agent.session) return false;
6577
+ const ownedTools = {
6578
+ register: (...args) => own(agent.ctx.tools.register(...args)),
6579
+ guard: (...args) => own(agent.ctx.tools.guard(...args))
6580
+ };
6581
+ try {
6582
+ const runtime = ensure(agent);
6583
+ runtime.sync();
6584
+ if (source === "resume" || source === "compact") {
6585
+ runtime.projection.lastRecoveryDigest = void 0;
6586
+ runtime.markRecoveryNeeded(source === "resume" ? "resume" : "compaction");
6587
+ }
6588
+ own(registerPassiveHostWorkdirObserver(agent, () => seams.hostLock ?? revalidateCoreLock(config, installedHostLock), (tool, provider, policy) => config.hostLockRuntimeRoot && config.hostLockProfileRoot ? auditedDefaultWorkdirProvider(config.hostLockRuntimeRoot, config.hostLockProfileRoot, tool, provider, policy) : false, (exec) => {
6589
+ runtime.sync();
6590
+ return sourcedNamedTestRoot(runtime.projection, agent.session, exec.arguments);
6591
+ }));
6592
+ ownedTools.register(createRebindTool(() => runtime.projection, async () => {
6407
6593
  const durable = await ctx.sessions.flush(agent.session);
6408
6594
  runtime.setDurability(durable);
6409
6595
  runtime.sync();
6410
6596
  return durable;
6411
- },
6412
- authorizeMutation: (request) => {
6413
- runtime.sync();
6414
- return authorizeMutationFromProjection(runtime.projection, request);
6415
- },
6416
- marketOrigin: optionalMarketOrigin(ctx, agent),
6417
- hasRestartIntent: (resolutionCallId, serviceId, preGeneration) => hasPrivateRestartIntent(readPrivateLedger(privateLedgerRoot, ledgerContext(agent)), resolutionCallId, serviceId, preGeneration),
6418
- releaseGate: async (request) => {
6419
- runtime.sync();
6420
- const projection = runtime.projection;
6421
- if (!(projection.policy === "release" || projection.releaseContracts.length > 0)) return {
6422
- status: "denied",
6423
- reasonCode: "release_contract_not_adopted"
6424
- };
6425
- const observed = { ...request.observed };
6426
- const declaredRef = releaseContractFor(projection, request.operation)?.candidate.ref;
6427
- if (declaredRef !== void 0 && observed.ref === void 0) {
6428
- const refSha = await resolveAuditedRef(sessionCwd(runtime.session), declaredRef, evidenceOptions, requestSignal());
6429
- if (refSha !== void 0) {
6430
- observed.ref = declaredRef;
6431
- observed.refSha = refSha;
6432
- }
6433
- }
6434
- const decision = releasePreEffectDecision(projection, {
6435
- operation: request.operation,
6436
- observed,
6437
- resolvedTarget: request.resolvedTarget,
6438
- nowEpochMs: Date.now()
6439
- });
6440
- if (decision.status !== "granted" || decision.contractId === void 0) return {
6441
- status: "denied",
6442
- reasonCode: decision.reasonCode
6443
- };
6444
- const grantedContract = projection.releaseContracts.find((entry) => entry.contractId === decision.contractId);
6445
- if (!grantedContract) return {
6446
- status: "denied",
6447
- reasonCode: "release_state_damaged"
6448
- };
6449
- return await persistReleaseRecord(agent, "release_reservation", {
6450
- contractId: decision.contractId,
6451
- operation: request.operation,
6452
- callId: request.callId,
6453
- startedAtSeq: 0,
6454
- status: "in_flight",
6455
- contract_sha256: privateLedgerContractDigest(grantedContract),
6456
- target_sha256: privateLedgerTargetDigest(request.resolvedTarget),
6457
- ...observed.artifactSri !== void 0 ? { observedArtifactSri: observed.artifactSri } : {}
6458
- }) ? {
6459
- status: "granted",
6460
- reasonCode: decision.reasonCode,
6461
- contractId: decision.contractId
6462
- } : {
6463
- status: "denied",
6464
- reasonCode: "release_reservation_not_durable"
6465
- };
6466
- },
6467
- releaseSettle: async (request) => {
6468
- const contractId = request.contractId ?? releaseContractFor(runtime.projection, request.operation)?.contractId ?? "unknown";
6469
- const contract = runtime.projection.releaseContracts.find((entry) => entry.contractId === contractId);
6470
- const reservation = reservationFor(runtime.projection, contractId, request.callId);
6471
- let outcome = request.effect === "not_effected" ? "not_effected" : "unknown";
6472
- if (request.effect === "completed" && contract) outcome = readbackSettlesContract(contract, request.readback, reservation?.observedArtifactSri) === "settled" ? "settled" : "unknown";
6473
- await persistReleaseRecord(agent, "release_settlement", {
6474
- contractId,
6475
- operation: request.operation,
6476
- callId: request.callId,
6477
- settledAtSeq: 0,
6478
- readback: request.readback,
6479
- outcome,
6480
- settlement_source: "effect"
6481
- });
6482
- },
6483
- persistRestartIntent: async (toolAgent, intent) => {
6484
- if (toolAgent.session !== agent.session) return false;
6485
- if (!sessionCwd(agent.session)) return false;
6486
- const snapshot = readPrivateLedger(privateLedgerRoot, ledgerContext(agent));
6487
- if (snapshot.damaged || !snapshot.anchored) return false;
6488
- const durable = appendPrivateLedger(privateLedgerRoot, ledgerContext(agent), "restart_intent", {
6489
- resolution_call_id: intent.resolutionCallId,
6490
- service_id: intent.serviceId,
6491
- pre_generation: intent.preGeneration
6492
- });
6493
- runtime.sync();
6494
- return durable;
6495
- }
6496
- };
6497
- agent.ctx.tools.register(createEvidenceTool(evidenceOptions));
6498
- agent.ctx.tools.register(createNativeFileObserver({
6499
- fs: ctx.fs,
6500
- flush: (session) => ctx.sessions.flush(session)
6501
- }));
6502
- agent.ctx.tools.register(createNativeGitObserver({ flush: (session) => ctx.sessions.flush(session) }));
6503
- agent.ctx.tools.register(createTestReadinessObserver({
6504
- getProjection: () => runtime.projection,
6505
- fs: ctx.fs,
6506
- flush: (session) => ctx.sessions.flush(session)
6507
- }));
6508
- agent.ctx.tools.register(createActionTool(evidenceOptions));
6509
- agent.ctx.tools.register(createPrepareTool({
6510
- getProjection: () => runtime.projection,
6511
- hostCapability: (action) => {
6512
- const evaluation = createHostCapabilityEvaluator(hostLocks.get(agent) ?? installedHostLock)(action);
6513
- return {
6514
- status: evaluation.status,
6515
- reasonCode: evaluation.reasonCode
6516
- };
6517
- },
6518
- commandTemplate: (action) => GIT_COMMAND_TEMPLATES[action],
6519
- refreshProjection: async () => {
6597
+ }));
6598
+ ownedTools.register(createCheckpointTool(() => runtime.projection, () => runtime.markRecoveryNeeded("checkpoint_followup"), async () => {
6520
6599
  const durable = await ctx.sessions.flush(agent.session);
6521
6600
  runtime.setDurability(durable);
6522
6601
  runtime.sync();
6523
6602
  return durable;
6524
- }
6525
- }));
6526
- agent.ctx.tools.register(createInterpretTool({
6527
- getProjection: () => runtime.projection,
6528
- refreshProjection: async () => {
6603
+ }));
6604
+ ownedTools.register(createBoundaryTool(() => runtime.projection, async () => {
6529
6605
  const durable = await ctx.sessions.flush(agent.session);
6530
6606
  runtime.setDurability(durable);
6531
6607
  runtime.sync();
6532
6608
  return durable;
6533
- }
6534
- }));
6535
- agent.ctx.tools.register(createReleaseTool({
6536
- getProjection: () => runtime.projection,
6537
- fetcher: evidenceOptions.fetcher,
6538
- ...evidenceOptions.allowLoopbackHttpRegistry ? { allowLoopbackHttpRegistry: true } : {},
6539
- persistSettlement: async (request) => persistReleaseRecord(request.agent, "release_settlement", {
6540
- contractId: request.contractId,
6541
- operation: request.operation,
6542
- callId: request.callId,
6543
- settledAtSeq: 0,
6544
- readback: request.readback,
6545
- outcome: request.outcome,
6546
- settlement_source: "reconcile"
6547
- })
6548
- }));
6549
- agent.ctx.tools.register(createExternalOperationTool((id, toolAgent) => readExternalOperation(ctx, toolAgent, id), () => evaluateExternalWaitCapability(hostLocks.get(agent) ?? installedHostLock)));
6550
- agent.ctx.tools.guard((exec) => goalCompletionDenial(runtime.projection, exec.name, exec.arguments));
6609
+ }, () => runtime.markRecoveryNeeded("boundary_update")));
6610
+ /** Persist release state outside provider-visible Session history. */
6611
+ const persistReleaseRecord = async (toolAgent, kind, payload) => {
6612
+ if (toolAgent.session !== agent.session) return false;
6613
+ if (!sessionCwd(agent.session)) return false;
6614
+ const durable = appendPrivateLedger(privateLedgerRoot, ledgerContext(agent), kind, payload);
6615
+ runtime.sync();
6616
+ return durable;
6617
+ };
6618
+ const evidenceOptions = {
6619
+ hostCapability: createHostCapabilityEvaluator(hostLocks.get(agent) ?? installedHostLock),
6620
+ ...seams.commandRunner ? { commandRunner: seams.commandRunner } : {},
6621
+ ...seams.fetcher ? { fetcher: seams.fetcher } : {},
6622
+ ...seams.allowLoopbackHttpRegistry ? { allowLoopbackHttpRegistry: true } : {},
6623
+ prepareMutation: async (toolAgent) => {
6624
+ if (toolAgent.session !== agent.session) return false;
6625
+ const durable = await ctx.sessions.flush(agent.session);
6626
+ runtime.setDurability(durable);
6627
+ runtime.sync();
6628
+ return durable;
6629
+ },
6630
+ authorizeMutation: (request) => {
6631
+ runtime.sync();
6632
+ return authorizeMutationFromProjection(runtime.projection, request);
6633
+ },
6634
+ marketOrigin: optionalMarketOrigin(ctx, agent),
6635
+ hasRestartIntent: (resolutionCallId, serviceId, preGeneration) => hasPrivateRestartIntent(readPrivateLedger(privateLedgerRoot, ledgerContext(agent)), resolutionCallId, serviceId, preGeneration),
6636
+ releaseGate: async (request) => {
6637
+ runtime.sync();
6638
+ const projection = runtime.projection;
6639
+ if (!(projection.policy === "release" || projection.releaseContracts.length > 0)) return {
6640
+ status: "denied",
6641
+ reasonCode: "release_contract_not_adopted"
6642
+ };
6643
+ const observed = { ...request.observed };
6644
+ const declaredRef = releaseContractFor(projection, request.operation)?.candidate.ref;
6645
+ if (declaredRef !== void 0 && observed.ref === void 0) {
6646
+ const refSha = await resolveAuditedRef(sessionCwd(runtime.session), declaredRef, evidenceOptions, requestSignal());
6647
+ if (refSha !== void 0) {
6648
+ observed.ref = declaredRef;
6649
+ observed.refSha = refSha;
6650
+ }
6651
+ }
6652
+ const decision = releasePreEffectDecision(projection, {
6653
+ operation: request.operation,
6654
+ observed,
6655
+ resolvedTarget: request.resolvedTarget,
6656
+ nowEpochMs: Date.now()
6657
+ });
6658
+ if (decision.status !== "granted" || decision.contractId === void 0) return {
6659
+ status: "denied",
6660
+ reasonCode: decision.reasonCode
6661
+ };
6662
+ const grantedContract = projection.releaseContracts.find((entry) => entry.contractId === decision.contractId);
6663
+ if (!grantedContract) return {
6664
+ status: "denied",
6665
+ reasonCode: "release_state_damaged"
6666
+ };
6667
+ return await persistReleaseRecord(agent, "release_reservation", {
6668
+ contractId: decision.contractId,
6669
+ operation: request.operation,
6670
+ callId: request.callId,
6671
+ startedAtSeq: 0,
6672
+ status: "in_flight",
6673
+ contract_sha256: privateLedgerContractDigest(grantedContract),
6674
+ target_sha256: privateLedgerTargetDigest(request.resolvedTarget),
6675
+ ...observed.artifactSri !== void 0 ? { observedArtifactSri: observed.artifactSri } : {}
6676
+ }) ? {
6677
+ status: "granted",
6678
+ reasonCode: decision.reasonCode,
6679
+ contractId: decision.contractId
6680
+ } : {
6681
+ status: "denied",
6682
+ reasonCode: "release_reservation_not_durable"
6683
+ };
6684
+ },
6685
+ releaseSettle: async (request) => {
6686
+ const contractId = request.contractId ?? releaseContractFor(runtime.projection, request.operation)?.contractId ?? "unknown";
6687
+ const contract = runtime.projection.releaseContracts.find((entry) => entry.contractId === contractId);
6688
+ const reservation = reservationFor(runtime.projection, contractId, request.callId);
6689
+ let outcome = request.effect === "not_effected" ? "not_effected" : "unknown";
6690
+ if (request.effect === "completed" && contract) outcome = readbackSettlesContract(contract, request.readback, reservation?.observedArtifactSri) === "settled" ? "settled" : "unknown";
6691
+ await persistReleaseRecord(agent, "release_settlement", {
6692
+ contractId,
6693
+ operation: request.operation,
6694
+ callId: request.callId,
6695
+ settledAtSeq: 0,
6696
+ readback: request.readback,
6697
+ outcome,
6698
+ settlement_source: "effect"
6699
+ });
6700
+ },
6701
+ persistRestartIntent: async (toolAgent, intent) => {
6702
+ if (toolAgent.session !== agent.session) return false;
6703
+ if (!sessionCwd(agent.session)) return false;
6704
+ const snapshot$1 = readPrivateLedger(privateLedgerRoot, ledgerContext(agent));
6705
+ if (snapshot$1.damaged || !snapshot$1.anchored) return false;
6706
+ const durable = appendPrivateLedger(privateLedgerRoot, ledgerContext(agent), "restart_intent", {
6707
+ resolution_call_id: intent.resolutionCallId,
6708
+ service_id: intent.serviceId,
6709
+ pre_generation: intent.preGeneration
6710
+ });
6711
+ runtime.sync();
6712
+ return durable;
6713
+ }
6714
+ };
6715
+ ownedTools.register(createEvidenceTool(evidenceOptions));
6716
+ ownedTools.register(createNativeFileObserver({
6717
+ fs: ctx.fs,
6718
+ flush: (session) => ctx.sessions.flush(session)
6719
+ }));
6720
+ ownedTools.register(createNativeGitObserver({ flush: (session) => ctx.sessions.flush(session) }));
6721
+ ownedTools.register(createTestReadinessObserver({
6722
+ getProjection: () => runtime.projection,
6723
+ fs: ctx.fs,
6724
+ flush: (session) => ctx.sessions.flush(session)
6725
+ }));
6726
+ ownedTools.register(createActionTool(evidenceOptions));
6727
+ ownedTools.register(createPrepareTool({
6728
+ getProjection: () => runtime.projection,
6729
+ hostCapability: (action) => {
6730
+ const evaluation = createHostCapabilityEvaluator(hostLocks.get(agent) ?? installedHostLock)(action);
6731
+ return {
6732
+ status: evaluation.status,
6733
+ reasonCode: evaluation.reasonCode
6734
+ };
6735
+ },
6736
+ commandTemplate: (action) => GIT_COMMAND_TEMPLATES[action],
6737
+ refreshProjection: async () => {
6738
+ const durable = await ctx.sessions.flush(agent.session);
6739
+ runtime.setDurability(durable);
6740
+ runtime.sync();
6741
+ return durable;
6742
+ }
6743
+ }));
6744
+ ownedTools.register(createInterpretTool({
6745
+ getProjection: () => runtime.projection,
6746
+ refreshProjection: async () => {
6747
+ const durable = await ctx.sessions.flush(agent.session);
6748
+ runtime.setDurability(durable);
6749
+ runtime.sync();
6750
+ return durable;
6751
+ }
6752
+ }));
6753
+ ownedTools.register(createReleaseTool({
6754
+ getProjection: () => runtime.projection,
6755
+ fetcher: evidenceOptions.fetcher,
6756
+ ...evidenceOptions.allowLoopbackHttpRegistry ? { allowLoopbackHttpRegistry: true } : {},
6757
+ persistSettlement: async (request) => persistReleaseRecord(request.agent, "release_settlement", {
6758
+ contractId: request.contractId,
6759
+ operation: request.operation,
6760
+ callId: request.callId,
6761
+ settledAtSeq: 0,
6762
+ readback: request.readback,
6763
+ outcome: request.outcome,
6764
+ settlement_source: "reconcile"
6765
+ })
6766
+ }));
6767
+ ownedTools.register(createExternalOperationTool((id, toolAgent) => readExternalOperation(ctx, toolAgent, id), () => evaluateExternalWaitCapability(hostLocks.get(agent) ?? installedHostLock)));
6768
+ ownedTools.guard((exec) => goalCompletionDenial(runtime.projection, exec.name, exec.arguments));
6769
+ } catch (error) {
6770
+ detach(agent);
6771
+ throw error;
6772
+ }
6773
+ };
6774
+ ctx.on("agent/created", ({ agent, source, signal }) => {
6775
+ signal?.throwIfAborted();
6776
+ return attach(agent, source);
6551
6777
  });
6778
+ for (const agent of ctx.get?.("agents")?.list() ?? []) attach(agent);
6552
6779
  ctx.on("agent/pre-step", async ({ agent }, next) => {
6553
6780
  const durability = await ctx.sessions.flush(agent.session);
6554
6781
  const runtime = ensure(agent);
@@ -6574,9 +6801,12 @@ function apply(ctx, rawConfig = {}, seams = {}) {
6574
6801
  if (runtime.lifecycle === "armed") injected.push(pluginNoticeMessage(firstStep.guidance, "Context Guard first-step protection guidance"));
6575
6802
  boundaryPending = false;
6576
6803
  }
6804
+ const armedRecoveryCauses = runtime.recoveryCauses ?? [];
6577
6805
  if (runtime.projection.enabled && runtime.consumeRecovery()) {
6578
- const hasOpenWork = [...runtime.projection.items.values()].some((item) => item.status === "pending");
6579
- const hasRejections = (runtime.projection.lastCheckpointRejections?.length ?? 0) > 0;
6806
+ const current = currentV6Feedback(runtime.projection);
6807
+ const standingConstraints = current ? Object.values(current.predicates).filter((state) => state === "constraint_active").length : 0;
6808
+ const hasOpenWork = current ? current.status !== "observed" || standingConstraints > 0 : [...runtime.projection.items.values()].some((item) => item.status === "pending");
6809
+ const hasRejections = current === void 0 && (runtime.projection.lastCheckpointRejections?.length ?? 0) > 0;
6580
6810
  const recovery = hasOpenWork || hasRejections ? renderRecoveryPacket(runtime.projection, { charBudget: 4e3 }) : void 0;
6581
6811
  const digest$2 = recovery ? recoveryDigest(recovery, runtime.projection) : void 0;
6582
6812
  if (recovery && digest$2 !== runtime.projection.lastRecoveryDigest) {
@@ -6585,13 +6815,14 @@ function apply(ctx, rawConfig = {}, seams = {}) {
6585
6815
  injected.push(pluginNoticeMessage(PROTOCOL_V6_NOTICE, "Context Guard recorded a replay version boundary"));
6586
6816
  boundaryPending = false;
6587
6817
  }
6818
+ const title = recoveryTitle(armedRecoveryCauses);
6588
6819
  injected.push(createUserMessage({
6589
6820
  content: [{
6590
6821
  type: "text",
6591
- text: `Open task requirements (recovered after compaction or resume):\n${recovery}`
6822
+ text: `${title}\n${recovery}`
6592
6823
  }],
6593
6824
  source: {
6594
- kind: "plugin",
6825
+ kind: "context-guard",
6595
6826
  plugin: "context-guard",
6596
6827
  form: "notice",
6597
6828
  summary: boundContextSummary("recovering open task requirements")
@@ -6619,15 +6850,15 @@ function apply(ctx, rawConfig = {}, seams = {}) {
6619
6850
  }
6620
6851
  function readExternalOperation(ctx, agent, id) {
6621
6852
  if (!agent || !id) return void 0;
6622
- for (const owner of [agent.ctx, ctx]) try {
6623
- const service = owner.get?.("jobs") ?? owner.jobs;
6624
- if (!service || typeof service !== "object") continue;
6625
- const row = typeof service.get === "function" ? service.get(id, agent) : void 0;
6626
- if (!row) return void 0;
6627
- const raw = String(row.status ?? "unknown");
6853
+ if (!agent.session || agent.id !== agent.session.id) return void 0;
6854
+ try {
6855
+ const service = agent.ctx.get("jobs") ?? ctx.get("jobs");
6856
+ if (!service) return void 0;
6857
+ const row = service.get(JobId(id), agent.id);
6858
+ if (!row || row.id !== id) return void 0;
6628
6859
  return {
6629
6860
  id,
6630
- status: raw === "running" ? "running" : raw === "stopping" ? "pending" : raw === "completed" ? "completed" : raw === "killed" || raw === "failed" ? "failed" : "unknown",
6861
+ status: row.status === "running" ? "running" : row.status === "stopping" ? "pending" : row.status === "completed" ? "completed" : row.status === "killed" || row.status === "failed" ? "failed" : "unknown",
6631
6862
  adapterId: "dsh.jobs.v1"
6632
6863
  };
6633
6864
  } catch {
@@ -6649,7 +6880,7 @@ function pluginNoticeMessage(text, summaryLabel) {
6649
6880
  text
6650
6881
  }],
6651
6882
  source: {
6652
- kind: "plugin",
6883
+ kind: "context-guard",
6653
6884
  plugin: "context-guard",
6654
6885
  form: "notice",
6655
6886
  summary: boundContextSummary(summaryLabel)
@@ -6745,7 +6976,7 @@ async function replayRawV2(input) {
6745
6976
  text: PROTOCOL_V6_NOTICE
6746
6977
  }],
6747
6978
  source: {
6748
- kind: "plugin",
6979
+ kind: "context-guard",
6749
6980
  plugin: "context-guard",
6750
6981
  form: "notice",
6751
6982
  summary: "v6 replay boundary"
@@ -6789,7 +7020,7 @@ async function replayRawV2(input) {
6789
7020
  const runtime = createRuntime(agent, { activation: "always" }, lock, () => void 0);
6790
7021
  runtime.setDurability(true);
6791
7022
  runtime.sync();
6792
- const snapshot = sessionCoreSnapshot(session.snapshotEvents(), runtime.projection);
7023
+ const snapshot$1 = sessionCoreSnapshot(session.snapshotEvents(), runtime.projection);
6793
7024
  const stopCore = runtime.projection.coreV2 ?? null;
6794
7025
  const stop = await handleGuardTurnStopping(agent, runtime, {
6795
7026
  flush: async () => true,
@@ -6804,7 +7035,7 @@ async function replayRawV2(input) {
6804
7035
  const projection = runtime.projection;
6805
7036
  const postSnapshot = sessionCoreSnapshot(session.snapshotEvents(), projection);
6806
7037
  return {
6807
- stop_core_snapshot: snapshot ?? null,
7038
+ stop_core_snapshot: snapshot$1 ?? null,
6808
7039
  stop_core_projection: stopCore,
6809
7040
  stop,
6810
7041
  post_turn_core_snapshot: postSnapshot ?? null,
@@ -6834,4 +7065,4 @@ async function replayRawV2(input) {
6834
7065
  }
6835
7066
 
6836
7067
  //#endregion
6837
- export { ACTION_MANIFEST, ACTION_MANIFEST_VERSION, ACTIVE_HOST_COHORT_ID, ACTIVE_HOST_COHORT_IDS, ACTIVE_HOST_LAUNCHER_VERSION, ALPHA2_DSHMARKET_139_HOST_PACKAGES, ALPHA2_HOST_PACKAGES, ALPHA3_HOST_PACKAGES, BASE_HOST_PACKAGES, BOUNDED_ARTIFACT_TYPES, CAPTURE_V042_NOTICE, CERTIFICATE_VERSION, CERTIFICATE_VERSION_V2, CLEANUP_CONDITION_RULE, CLEANUP_CONDITION_RULE_COMPACT, CLEANUP_CONDITION_RULE_SHORT, COMMAND_SURFACE_MANIFEST, CONFIRM_LINE_PATTERN, CONTROL_RECORD_PREFIX, Config, DEFAULT_DELEGATION_TOOL_NAMES, DEFAULT_HOST_LOCK, DEFAULT_RECOVERY_CHAR_BUDGET, DEPENDENCY_FREE_ONLY_CONDITION, EXPECTED_HOST_PACKAGES, FIRST_STEP_GUIDANCE, GIT_COMMAND_MANIFEST_IDS, GIT_COMMAND_TEMPLATES, GOAL_HOST_PACKAGES, GRANTED_QUALIFICATION, HOST_CAPABILITY_PACKAGE_GROUPS, HOST_COHORTS, HostProfileError, LATEST_SUPPORTED_HOST_VERSION, LEGACY_HOST_COHORTS, LEGACY_QUALIFICATION, MIN_RECOVERY_CHAR_BUDGET, MIN_SUPPORTED_HOST_VERSION, NO_PROGRESS_RECORD_PREFIX, NO_PROGRESS_TURNS_BEFORE_STOP, PROOF_CAPABILITY_MATRIX, PROOF_KINDS, PROOF_KINDS_V2, PROOF_MANIFEST_DOMAIN_V2, PROOF_PROTOCOL_VERSION, PROOF_PROTOCOL_VERSION_V2, PROTOCOL_V3_NOTICE, PROTOCOL_V4_NOTICE, PROTOCOL_V5_NOTICE, PROTOCOL_V6_NOTICE, RC015_HOST_PACKAGES, RC015_RC2_HOST_PACKAGES, RC1_HOST_PACKAGES, SEMANTIC_ACTIONS, SESSION_API_UNSUPPORTED, SESSION_EVENT_ENVELOPE_INVALID, STATEFUL_ACTIONS, STOP_PROTOCOL_VERSION, STOP_PROTOCOL_VERSION_V2, SUPPORTED_EVIDENCE_ADAPTERS, SUPPORTED_HOST_RANGE, SUPPORTED_HOST_VERSIONS, SessionApiError, actionCompatible, actionHasCertificationPath, actionVerbMatches, activeRendererModule, admissibleForRemoval, apply, applyUpgradeEligibility, assessmentAction, assessmentOutcomePredicate, auditedDefaultWorkdirHost, auditedDefaultWorkdirProvider, auditedForegroundRenderers, authorityCaptureCounts, availableBoundaryQualifications, bindExecutableIdentity, bindLiveGoalCapability, bindProofToProjection, bindProofV2ToProjection, bindingSatisfies, boundedArtifactChoiceMatches, canonicalArgvFromCommand, canonicalProjection, canonicalizePath, capabilityConsequence, capabilityFactOf, capabilityRemedyPhrase, captureClause, captureItem, carriesCleanupCondition, certifyCheckpoint, claimedBatchHasRealRootInput, clarifiedSpanOf, classifyClause, classifyCompletionClaim, classifyTaskIntent, classifyUserInteraction, clauseAsksOwnQuestion, clauseIsGoverned, clauseIsProtected, cleanupConditionFor, closingHint, combineHostPolicy, commitIndexSnapshotDigest, commitTreeSnapshotDigest, compareHostVersions, confirmRebind, createGitPrestateEnvelope, createProjection, createProofManifest, createProofManifestV2, currentActionBases, currentContractDigest, decideTurnBoundary, decideTurnStopping, decisionBoundaryKey, deriveItemDiagnosis, deriveProjection, digestStrings, effectuateBoundary, environmentDefaultRepositoryTarget, evaluateExternalWaitCapability, evaluateHostCapability, evaluateHostLock, evaluateMinimumHostVersion, evaluateToolSurfaceCapability, evidenceAvailabilityReason, evidenceCoverage, evidenceFromPersistedToolResult, evidenceMatchesItem, executeRevalidatedGitEffect, explanationHasActionResidue, extractArtifactPaths, extractMethod, extractOperation, extractTextContent, extractToolSubject, firstStepGuidance, firstStepGuidanceV6, gitCommandMatchesTarget, goalCompletionDenial, governedClauseRestrictsExecution, hasCurrentCertificate, hasOrderedCoordination, hasQuestionScope, hasWorkPredicate, hostLockContextFromComposedDump, hostLockRowsFromComposedDump, hostVersionFromPackages, inject, injectActiveProfileHostLock, inspectTargetHostGraph, interpretClause, interpretMessage, introducesActionClause, isCurrentAcceptedBoundary, isDeterministicCheck, isExecutableItem, isExplanationScope, isFrozenV042RebindResponse, isInformationalFragment, isInformationalMessage, isOpenObligation, isQuestionScopeNeedingReview, isRestatement, isRootPauseRequest, isRunExecutable, isStatefulAction, isVerifyingCapability, isWholeTaskCompletionClaim, itemDiagnosis, itemHoldsExecutionAuthority, kindOfScope, latestAssistantText, latestRootInstruction, legacyQuestionReadingIsInformational, legacyRecordsNeedingReview, lifecyclePhase, maskCodeSpans, maskQuotedSpans, name, namedActions, normalizeClause, observeAssistantOutcome, openItems, opensConditionLead, opensWithDirective, packageRowsFromActiveGraph, packageRowsFromPnpmLock, parseConfirmationMessage, parseGitCommandManifest, parseHostVersion, parsePwshCommand, parseShellCommand, partialFailureOf, persistedToolResultStatus, presentExplanationHead, previewFirstStepInjection, progressFingerprint, projectCoreV2, projectSessionCoreV2, proofCapabilityReport, proofDigest, proofDigestV2, proofEvidenceConstraints, proofHostSurfacesOf, proofOperationMatches, proofV2Rejection, proposeRebind, proposeRebindOutcome, proposeRebindV042, qualificationOfClause, qualifyBoundary, questionHeadsClause, readActiveHostGraph, rebindAttemptKey, rebindResponse, recoveryDigest, relevantEvidence, removalIsComplete, removalIsPartiallyKnown, renderRecoveryPacket, replayRawV2, replayRebindResult, reportingHeadGoverns, requestedIdentityKey, requestedTargetAuthorizesMutation, requestedTargetMatchesResolved, requiredSubjectsOf, resolveActiveProfileHostLock, resolveInstalledHostLock, restatedContentOf, revalidateGitPrestate, rootLocatorFlavor, sanitizeClauseText, sanitizeUrl, satisfiesSupportedHostRange, scopeCoverageDigest, segmentAuthorityBlocks, segmentClauses, selectHostCohort, semanticActionFromCommand, semanticActionFromText, semanticActionOfScope, sessionQuery, sessionQueryV2, sha256, snapshotSessionEvents, splitTextFragments, statefulActionsOfScope, supersedeItem, testOutcomePredicate, v6TestPredicate, validateActionManifest, validateActionTarget, validateManifest, validateProofManifest, validateProofManifestV2, verbIsNegated, verifiedLinearCommitReadback, verifyComposedHostLockDump, withDurability };
7068
+ export { ACTION_MANIFEST, ACTION_MANIFEST_VERSION, ACTIVE_HOST_COHORT_ID, ACTIVE_HOST_COHORT_IDS, ACTIVE_HOST_LAUNCHER_VERSION, BASE_HOST_PACKAGES, BOUNDARY_RECORD_PREFIX, BOUNDED_ARTIFACT_TYPES, CAPTURE_V042_NOTICE, CERTIFICATE_VERSION, CERTIFICATE_VERSION_V2, CLEANUP_CONDITION_RULE, CLEANUP_CONDITION_RULE_COMPACT, CLEANUP_CONDITION_RULE_SHORT, COMMAND_SURFACE_MANIFEST, CONFIRM_LINE_PATTERN, CONTROL_RECORD_PREFIX, Config, DEFAULT_DELEGATION_TOOL_NAMES, DEFAULT_HOST_LOCK, DEFAULT_RECOVERY_CHAR_BUDGET, DEPENDENCY_FREE_ONLY_CONDITION, EXPECTED_HOST_PACKAGES, FIRST_STEP_GUIDANCE, GIT_COMMAND_MANIFEST_IDS, GIT_COMMAND_TEMPLATES, GOAL_HOST_PACKAGES, GRANTED_QUALIFICATION, HOST_CAPABILITY_PACKAGE_GROUPS, HOST_COHORTS, HostProfileError, LATEST_SUPPORTED_HOST_VERSION, LEGACY_QUALIFICATION, MIN_RECOVERY_CHAR_BUDGET, MIN_SUPPORTED_HOST_VERSION, NO_PROGRESS_RECORD_PREFIX, NO_PROGRESS_TURNS_BEFORE_STOP, PROOF_CAPABILITY_MATRIX, PROOF_KINDS, PROOF_KINDS_V2, PROOF_MANIFEST_DOMAIN_V2, PROOF_PROTOCOL_VERSION, PROOF_PROTOCOL_VERSION_V2, PROTOCOL_V3_NOTICE, PROTOCOL_V4_NOTICE, PROTOCOL_V5_NOTICE, PROTOCOL_V6_NOTICE, RC017_RC2_HOST_PACKAGES, SEMANTIC_ACTIONS, SESSION_API_UNSUPPORTED, SESSION_EVENT_ENVELOPE_INVALID, STATEFUL_ACTIONS, STOP_PROTOCOL_VERSION, STOP_PROTOCOL_VERSION_V2, SUPPORTED_EVIDENCE_ADAPTERS, SUPPORTED_HOST_RANGE, SUPPORTED_HOST_VERSIONS, SessionApiError, V6_ORDINARY_COMPLETION_RULE, V6_ORDINARY_COMPLETION_RULE_COMPACT, V6_ORDINARY_COMPLETION_RULE_SHORT, actionCompatible, actionHasCertificationPath, actionVerbMatches, activeRendererModule, admissibleForRemoval, apply, applyUpgradeEligibility, assessmentAction, assessmentOutcomePredicate, auditedDefaultWorkdirHost, auditedDefaultWorkdirProvider, auditedForegroundRenderers, auditedHostImplementation, authorityCaptureCounts, availableBoundaryQualifications, bindExecutableIdentity, bindLiveGoalCapability, bindProofToProjection, bindProofV2ToProjection, bindingIndividuallyAccepted, bindingSatisfies, boundedArtifactChoiceMatches, canonicalArgvFromCommand, canonicalProjection, canonicalizePath, capabilityConsequence, capabilityFactOf, capabilityRemedyPhrase, captureClause, captureItem, carriesCleanupCondition, certifyCheckpoint, claimedBatchHasRealRootInput, clarifiedSpanOf, classifyClause, classifyCompletionClaim, classifyTaskIntent, classifyUserInteraction, clauseAsksOwnQuestion, clauseIsGoverned, clauseIsProtected, cleanupConditionFor, closingHint, combineHostPolicy, commitIndexSnapshotDigest, commitTreeSnapshotDigest, compareHostVersions, confirmRebind, createGitPrestateEnvelope, createProjection, createProofManifest, createProofManifestV2, currentActionBases, currentContractDigest, decideTurnBoundary, decideTurnStopping, decisionBoundaryKey, deriveItemDiagnosis, deriveProjection, digestStrings, effectuateBoundary, environmentDefaultRepositoryTarget, evaluateExternalWaitCapability, evaluateHostCapability, evaluateHostLock, evaluateMinimumHostVersion, evaluateToolSurfaceCapability, evidenceAvailabilityReason, evidenceCoverage, evidenceFromPersistedToolResult, evidenceMatchesItem, executeRevalidatedGitEffect, explanationHasActionResidue, extractArtifactPaths, extractMethod, extractOperation, extractTextContent, extractToolSubject, firstStepGuidance, firstStepGuidanceV6, gitCommandMatchesTarget, goalCompletionDenial, governedClauseRestrictsExecution, hasCurrentCertificate, hasOrderedCoordination, hasQuestionScope, hasWorkPredicate, hostLockContextFromComposedDump, hostLockRowsFromComposedDump, hostVersionFromPackages, inject, injectActiveProfileHostLock, inspectTargetHostGraph, interpretClause, interpretMessage, introducesActionClause, isCurrentAcceptedBoundary, isDeterministicCheck, isExecutableItem, isExplanationScope, isFrozenV042RebindResponse, isInformationalFragment, isInformationalMessage, isOpenObligation, isQuestionScopeNeedingReview, isRestatement, isRootPauseRequest, isRunExecutable, isStatefulAction, isVerifyingCapability, isWholeTaskCompletionClaim, itemDiagnosis, itemHoldsExecutionAuthority, kindOfScope, latestAssistantText, latestRootInstruction, legacyQuestionReadingIsInformational, legacyRecordsNeedingReview, lifecyclePhase, maskCodeSpans, maskQuotedSpans, name, namedActions, nativeFileTwoRole, normalizeClause, observeAssistantOutcome, openItems, opensConditionLead, opensWithDirective, packageRowsFromActiveGraph, packageRowsFromPnpmLock, parseConfirmationMessage, parseGitCommandManifest, parseHostVersion, parsePwshCommand, parseShellCommand, partialFailureOf, persistedToolResultStatus, presentExplanationHead, previewFirstStepInjection, progressFingerprint, projectCoreV2, projectSessionCoreV2, proofCapabilityReport, proofDigest, proofDigestV2, proofEvidenceConstraints, proofHostSurfacesOf, proofOperationMatches, proofV2Rejection, proposeRebind, proposeRebindOutcome, proposeRebindV042, qualificationOfClause, qualifyBoundary, questionHeadsClause, readActiveHostGraph, rebindAttemptKey, rebindResponse, recoveryDigest, recoveryTitle, relevantEvidence, removalIsComplete, removalIsPartiallyKnown, renderRecoveryPacket, replayRawV2, replayRebindResult, reportingHeadGoverns, requestedIdentityKey, requestedTargetAuthorizesMutation, requestedTargetMatchesResolved, requiredSubjectsOf, resolveActiveProfileHostLock, resolveInstalledHostLock, restatedContentOf, revalidateGitPrestate, rootLocatorFlavor, sanitizeClauseText, sanitizeUrl, satisfiesSupportedHostRange, scopeCoverageDigest, segmentAuthorityBlocks, segmentClauses, selectHostCohort, semanticActionFromCommand, semanticActionFromText, semanticActionOfScope, sessionQuery, sessionQueryV2, sha256, snapshotSessionEvents, splitTextFragments, statefulActionsOfScope, supersedeItem, testOutcomePredicate, v6CurrentRootBoundaries, v6TestPredicate, validateActionManifest, validateActionTarget, validateManifest, validateProofManifest, validateProofManifestV2, verbIsNegated, verifiedLinearCommitReadback, verifyComposedHostLockDump, withDurability };