dsh-completion-guard 0.8.3 → 0.9.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,12 +1,12 @@
1
- import { $ as segmentAuthorityBlocks, $a as createHostAuditSession, $i as acquireHostTrust, $n as evidenceAvailabilityReason, $r as presentExplanationHead, $t as normalizeSettlement, A as PROTOCOL_V3_NOTICE, Aa as parseHostVersion, Ai as packageRowsFromActiveGraph, An as certifiableOpenItems, Ar as clauseIsProtected, At as MIN_RECOVERY_CHAR_BUDGET, B as evidenceFromPersistedToolResult, Ba as STOP_PROTOCOL_VERSION_V2, Bi as verifyComposedHostLockDump, Bn as createProjection, Br as isExplanationScope, Bt as renderRecoveryPacket, C as SESSION_API_UNSUPPORTED, Ca as HOST_VALIDATED_VERSIONS, Ci as evaluateActiveHostLock, Cn as observeAssistantOutcome, Cr as classifyUserInteraction, Ct as sessionQueryV2, D as projectCoreV2, Da as SUPPORTED_HOST_VERSIONS, Di as injectActiveProfileHostLock, Dn as goalCompletionDenial, Dr as clarifiedSpanOf, Dt as CLEANUP_CONDITION_RULE_COMPACT, E as snapshotSessionEvents, Ea as SUPPORTED_HOST_RANGE, Ei as hostLockRowsFromComposedDump, En as v6TestPredicate, Er as actionVerbMatches, Et as CLEANUP_CONDITION_RULE, F as deriveProjection, Fa as CERTIFICATE_VERSION, Fi as readActiveHostGraph, Fn as availableBoundaryQualifications, Fr as hasWorkPredicate, Ft as cleanupConditionFor, G as persistedToolResultStatus, Ga as requestedIdentityKey, Gi as hasDesktopImporterState, Gn as rebindAttemptKey, Gr as itemHoldsExecutionAuthority, Gt as sourceItemForCoreRequirement, H as extractToolSubject, Ha as actionCompatible, Hi as DESKTOP_PROFILE_PACKAGE_NAME, Hn as proposeRebind, Hr as isOpenObligation, Ht as confirmedV6CoreDiagnostic, I as legacyRecordsNeedingReview, Ia as CERTIFICATE_VERSION_V2, Ii as resolveActiveProfileHostLock, In as effectuateBoundary, Ir as interpretClause, It as closingHint, J as canonicalArgvFromCommand, Ja as semanticActionFromCommand, Ji as readDesktopAppRuntime, Jn as CONFIRM_LINE_PATTERN, Jr as maskCodeSpans, Jt as RELEASE_OPERATION_SURFACES, K as shellReadbackOutcome, Ka as requestedTargetAuthorizesMutation, Ki as readAsarFile, Kn as rebindResponse, Kr as kindOfScope, Kt as OUTCOME_STRENGTH, L as rootLocatorFlavor, La as SEMANTIC_ACTIONS, Li as resolveDesktopProfileHostLock, Ln as isCurrentAcceptedBoundary, Lr as interpretMessage, Lt as openItems, M as PROTOCOL_V5_NOTICE, Ma as ACTION_MANIFEST, Mi as prepareActiveHostTrust, Mn as needsReviewObligations, Mr as governedClauseRestrictsExecution, Mt as V6_ORDINARY_COMPLETION_RULE_COMPACT, N as PROTOCOL_V6_NOTICE, Na as ACTION_MANIFEST_VERSION, Ni as prepareDesktopHostTrust, Nn as unitDescendantIds, Nr as hasOrderedCoordination, Nt as V6_ORDINARY_COMPLETION_RULE_SHORT, O as CAPTURE_V042_NOTICE, Oa as compareHostVersions, Oi as inspectDesktopTargetGraph, On as hasCurrentCertificate, Or as clauseAsksOwnQuestion, Ot as CLEANUP_CONDITION_RULE_SHORT, P as applyUpgradeEligibility, Pa as BOUNDED_ARTIFACT_TYPES, Pi as prepareTargetHostTrust, Pn as BOUNDARY_RECORD_PREFIX, Pr as hasQuestionScope, Pt as carriesCleanupCondition, Q as authorityCaptureCounts, Qa as RC020_RC2_HOST_PACKAGES, Qi as HostTrustError, Qn as deriveItemDiagnosis, Qr as opensWithDirective, Qt as normalizeReservation, R as supersedeItem, Ra as STATEFUL_ACTIONS, Ri as resolveInstalledHostLock, Rn as qualifyBoundary, Rr as introducesActionClause, Rt as recoveryDigest, S as sourcedNamedTestRoot, Sa as selectHostCohort, Si as combineHostPolicy, Sn as latestRootInstruction, Sr as classifyTaskIntent, St as sessionQuery, T as SessionApiError, Ta as MIN_SUPPORTED_HOST_VERSION, Ti as hostLockContextFromComposedDump, Tn as testOutcomePredicate, Tr as LEGACY_QUALIFICATION, Tt as validateProofManifestV2, U as isDeterministicCheck, Ua as boundedArtifactChoiceMatches, Ui as DESKTOP_RUNTIME_PACKAGE_NAME, Un as proposeRebindOutcome, Ur as isQuestionScopeNeedingReview, Ut as currentV6Feedback, V as extractTextContent, Va as SUPPORTED_EVIDENCE_ADAPTERS, Vi as DESKTOP_IDENTITY_FACTS, Vn as confirmRebind, Vr as isInformationalFragment, Vt as v6CurrentRootBoundaries, W as nativeGitParentOidVerified, Wa as isStatefulAction, Wi as auditDesktopInstalledImplementation, Wn as proposeRebindV042, Wr as isRestatement, Wt as isV6PendingRootWait, X as parsePwshCommand, Xa as validateActionManifest, Xi as readDesktopTargetGraph, Xn as parseConfirmationMessage, Xr as namedActions, Xt as inFlightReservation, Y as isRunExecutable, Ya as semanticActionFromText, Yi as readDesktopDependency, Yn as isFrozenV042RebindResponse, Yr as maskQuotedSpans, Yt as contractById, Z as parseShellCommand, Za as validateActionTarget, Zi as writeDesktopRuntimeReceipt, Zn as capabilityRemedyPhrase, Zr as opensConditionLead, Zt as normalizeReleaseContract, _ as previewFirstStepInjection, _a as evaluateGraphDerivedHostLock, _i as activeRendererModule, _n as decideTurnStopping, _r as extractOperation, _t as proofHostSurfacesOf, a as commitTreeSnapshotDigest, aa as ACTIVE_HOST_COHORT_ID, ai as splitTextFragments, an as bindingSatisfies, ar as admissibleForRemoval, at as PROOF_MANIFEST_DOMAIN_V2, b as HOST_WORKDIR_PREFIX, ba as evaluateToolSurfaceCapability, bi as auditedForegroundRenderers, bn as isWholeTaskCompletionClaim, br as canonicalRegistryBase, bt as requiredSubjectsOf, c as gitCommandMatchesTarget, ca as BASE_HOST_PACKAGES, ci as COMMAND_SURFACE_MANIFEST, cn as isVerifyingCapability, cr as partialFailureOf, ct as bindProofToProjection, d as verifiedLinearCommitReadback, da as GOAL_HOST_PACKAGES, di as digestStrings, dn as NO_PROGRESS_TURNS_BEFORE_STOP, dr as captureClause, dt as createProofManifest, ea as hostTrustDigest, ei as qualificationOfClause, en as readbackSettlesContract, er as itemDiagnosis, et as bindingIndividuallyAccepted, f as FIRST_STEP_GUIDANCE, fa as HOST_CAPABILITY_PACKAGE_GROUPS, fi as normalizeClause, fn as assessmentAction, fr as captureItem, ft as createProofManifestV2, g as lifecyclePhase, ga as evaluateExternalWaitCapability, gi as HostProfileError, gn as decideTurnBoundary, gr as extractMethod, gt as proofEvidenceConstraints, h as firstStepGuidanceV6, ha as bindLiveGoalCapability, hi as sha256, hn as currentActionBases, hr as extractArtifactPaths, ht as proofDigestV2, i as commitIndexSnapshotDigest, ia as registryArchiveModules, ii as semanticActionOfScope, in as reservationFor, ir as actionHasCertificationPath, it as PROOF_KINDS_V2, j as PROTOCOL_V4_NOTICE, ja as satisfiesSupportedHostRange, ji as packageRowsFromPnpmLock, jn as certificateClosure, jr as explanationHasActionResidue, jt as V6_ORDINARY_COMPLETION_RULE, k as DEFAULT_DELEGATION_TOOL_NAMES, ka as evaluateMinimumHostVersion, ki as inspectTargetHostGraph, kn as ancestorConstraintForBinding, kr as clauseIsGoverned, kt as DEFAULT_RECOVERY_CHAR_BUDGET, l as parseGitCommandManifest, la as DEFAULT_HOST_LOCK, li as validateManifest, ln as CONTROL_RECORD_PREFIX, lr as removalIsComplete, lt as bindProofV2ToProjection, m as firstStepGuidance, ma as bindExecutableIdentity, mi as sanitizeUrl, mn as classifyCompletionClaim, mr as environmentDefaultRepositoryTarget, mt as proofDigest, n as GIT_COMMAND_MANIFEST_IDS, na as qualifyHostTrust, ni as reportingHeadGoverns, nn as releaseCoverage, nr as relevantEvidence, nt as PROOF_CAPABILITY_MATRIX, o as createGitPrestateEnvelope, oa as ACTIVE_HOST_COHORT_IDS, oi as statefulActionsOfScope, on as evidenceCoverage, or as capabilityConsequence, ot as PROOF_PROTOCOL_VERSION, p as claimedBatchHasRealRootInput, pa as HOST_COHORTS, pi as sanitizeClauseText, pn as assessmentOutcomePredicate, pr as classifyClause, pt as proofCapabilityReport, q as withDurability, qa as requestedTargetMatchesResolved, qi as readAsarIndex, qn as replayRebindResult, qr as legacyQuestionReadingIsInformational, qt as RELEASE_OPERATIONS, r as GIT_COMMAND_TEMPLATES, ra as registryArchiveFiles, ri as restatedContentOf, rn as releasePreEffectDecision, rr as DEPENDENCY_FREE_ONLY_CONDITION, rt as PROOF_KINDS, s as executeRevalidatedGitEffect, sa as ACTIVE_HOST_LAUNCHER_VERSION, si as verbIsNegated, sn as evidenceMatchesItem, sr as capabilityFactOf, st as PROOF_PROTOCOL_VERSION_V2, t as RC020_RC1_HOST_PACKAGES, ta as parseHostTrust, ti as questionHeadsClause, tn as releaseContractFor, tr as nativeFileTwoRole, tt as certifyCheckpoint, u as revalidateGitPrestate, ua as EXPECTED_HOST_PACKAGES, ui as canonicalizePath, un as NO_PROGRESS_RECORD_PREFIX, ur as removalIsPartiallyKnown, ut as canonicalProjection, v as projectSessionCoreV2, va as evaluateHostCapability, vi as auditedDefaultWorkdirHost, vn as decisionBoundaryKey, vr as isInformationalMessage, vt as proofOperationMatches, w as SESSION_EVENT_ENVELOPE_INVALID, wa as LATEST_TESTED_HOST_VERSION, wi as evaluateConfiguredHostLock, wn as progressFingerprint, wr as GRANTED_QUALIFICATION, wt as validateProofManifest, x as captureHostWorkdir, xa as hostVersionFromPackages, xi as auditedHostImplementation, xn as latestAssistantText, xr as npmEscapedPackageName, xt as scopeCoverageDigest, y as sessionCoreSnapshot, ya as evaluateHostLock, yi as auditedDefaultWorkdirProvider, yn as isRootPauseRequest, yr as segmentClauses, yt as proofV2Rejection, z as NATIVE_GIT_ROOT_PARENT_OID, za as STOP_PROTOCOL_VERSION, zi as revalidateDesktopCoreLock, zn as currentContractDigest, zr as isExecutableItem, zt as recoveryTitle } from "./domain-DKqyOtgY.js";
1
+ import { $ as extractTextContent, $a as readActivationBinding, $i as registryArchiveModules, $n as itemDiagnosis, $r as qualificationOfClause, $t as v6CurrentRootBoundaries, A as projectSessionCoreV2, Aa as CERTIFICATE_VERSION, Ai as resolveDesktopProfileHostLock, An as certificateClosure, Ao as normalizeClause, Ar as explanationHasActionResidue, At as proofOperationMatches, B as CAPTURE_V042_NOTICE, Ba as requestedIdentityKey, Bi as memoizedAsarIndex, Bn as confirmRebind, Br as isInformationalFragment, Bt as CLEANUP_CONDITION_RULE_SHORT, C as verifiedLinearCommitReadback, Ca as compareHostVersions, Ci as packageRowsFromActiveGraph, Cn as progressFingerprint, Co as readbackSettlesContract, Cr as GRANTED_QUALIFICATION, Ct as createProofManifest, D as firstStepGuidanceV6, Da as ACTION_MANIFEST, Di as prepareTargetHostTrust, Dn as hasCurrentCertificate, Do as reservationFor, Dr as clauseAsksOwnQuestion, Dt as proofDigestV2, E as firstStepGuidance, Ea as satisfiesSupportedHostRange, Ei as prepareDesktopHostTrust, En as goalCompletionDenial, Eo as releasePreEffectDecision, Er as clarifiedSpanOf, Et as proofDigest, F as SESSION_API_UNSUPPORTED, Fa as STOP_PROTOCOL_VERSION_V2, Fi as DESKTOP_PROFILE_PACKAGE_NAME, Fn as effectuateBoundary, Fr as interpretClause, Ft as sessionQueryV2, G as PROTOCOL_V6_NOTICE, Ga as validateActionManifest, Gi as readDesktopTargetGraph, Gn as rebindResponse, Gr as kindOfScope, Gt as V6_ORDINARY_COMPLETION_RULE_SHORT, H as PROTOCOL_V3_NOTICE, Ha as requestedTargetMatchesResolved, Hi as readAsarIndex, Hn as proposeRebindOutcome, Hr as isQuestionScopeNeedingReview, Ht as MIN_RECOVERY_CHAR_BUDGET, I as SESSION_EVENT_ENVELOPE_INVALID, Ia as SUPPORTED_EVIDENCE_ADAPTERS, Ii as DESKTOP_RUNTIME_PACKAGE_NAME, In as isCurrentAcceptedBoundary, Ir as interpretMessage, It as validateProofManifest, J as legacyRecordsNeedingReview, Ja as createHostAuditSession, Ji as acquireHostTrust, Jn as isFrozenV042RebindResponse, Jr as maskQuotedSpans, Jt as closingHint, K as applyUpgradeEligibility, Ka as validateActionTarget, Ki as writeDesktopRuntimeReceipt, Kn as replayRebindResult, Kr as legacyQuestionReadingIsInformational, Kt as carriesCleanupCondition, L as SessionApiError, La as actionCompatible, Li as auditDesktopInstalledImplementation, Ln as qualifyBoundary, Lr as introducesActionClause, Lt as validateProofManifestV2, M as HOST_WORKDIR_PREFIX, Ma as SEMANTIC_ACTIONS, Mi as revalidateDesktopCoreLock, Mn as unitDescendantIds, Mo as sanitizeUrl, Mr as hasOrderedCoordination, Mt as requiredSubjectsOf, N as captureHostWorkdir, Na as STATEFUL_ACTIONS, Ni as verifyComposedHostLockDump, Nn as BOUNDARY_RECORD_PREFIX, No as sha256, Nr as hasQuestionScope, Nt as scopeCoverageDigest, O as lifecyclePhase, Oa as ACTION_MANIFEST_VERSION, Oi as readActiveHostGraph, On as ancestorConstraintForBinding, Oo as canonicalizePath, Or as clauseIsGoverned, Ot as proofEvidenceConstraints, P as sourcedNamedTestRoot, Pa as STOP_PROTOCOL_VERSION, Pi as DESKTOP_IDENTITY_FACTS, Pn as availableBoundaryQualifications, Po as privateStorageToolDenial, Pr as hasWorkPredicate, Pt as sessionQuery, Q as evidenceFromPersistedToolResult, Qa as createActivationMigrationReceipt, Qi as registryArchiveFiles, Qn as evidenceAvailabilityReason, Qr as presentExplanationHead, Qt as renderRecoveryPacket, R as snapshotSessionEvents, Ra as boundedArtifactChoiceMatches, Ri as hasDesktopImporterState, Rn as currentContractDigest, Rr as isExecutableItem, Rt as CLEANUP_CONDITION_RULE, S as revalidateGitPrestate, Sa as SUPPORTED_HOST_VERSIONS, Si as inspectTargetHostGraph, Sn as observeAssistantOutcome, So as normalizeReleaseContract, Sr as classifyUserInteraction, St as canonicalProjection, T as claimedBatchHasRealRootInput, Ta as parseHostVersion, Ti as prepareActiveHostTrust, Tn as v6TestPredicate, To as releaseCoverage, Tr as actionVerbMatches, Tt as proofCapabilityReport, U as PROTOCOL_V4_NOTICE, Ua as semanticActionFromCommand, Ui as readDesktopAppRuntime, Un as proposeRebindV042, Ur as isRestatement, Ut as V6_ORDINARY_COMPLETION_RULE, V as DEFAULT_DELEGATION_TOOL_NAMES, Va as requestedTargetAuthorizesMutation, Vi as readAsarFile, Vn as proposeRebind, Vr as isOpenObligation, Vt as DEFAULT_RECOVERY_CHAR_BUDGET, W as PROTOCOL_V5_NOTICE, Wa as semanticActionFromText, Wi as readDesktopDependency, Wn as rebindAttemptKey, Wr as itemHoldsExecutionAuthority, Wt as V6_ORDINARY_COMPLETION_RULE_COMPACT, X as supersedeItem, Xa as activationBindingPath, Xi as parseHostTrust, Xn as capabilityRemedyPhrase, Xr as opensConditionLead, Xt as recoveryDigest, Y as rootLocatorFlavor, Ya as __activationBindingInternals, Yi as hostTrustDigest, Yn as parseConfirmationMessage, Yr as namedActions, Yt as openItems, Z as NATIVE_GIT_ROOT_PARENT_OID, Za as adoptActivationReceipt, Zi as qualifyHostTrust, Zn as deriveItemDiagnosis, Zr as opensWithDirective, Zt as recoveryTitle, _ as commitTreeSnapshotDigest, _a as selectHostCohort, _i as evaluateConfiguredHostLock, _n as decisionBoundaryKey, _o as resolvePrivateLedgerRoot, _r as isInformationalMessage, _t as PROOF_MANIFEST_DOMAIN_V2, a as scanActivationInventory, aa as EXPECTED_HOST_PACKAGES, ai as statefulActionsOfScope, an as evidenceCoverage, ao as activationCanonical, ar as capabilityConsequence, at as withDurability, b as gitCommandMatchesTarget, ba as MIN_SUPPORTED_HOST_VERSION, bi as injectActiveProfileHostLock, bn as latestAssistantText, bo as contractById, br as npmEscapedPackageName, bt as bindProofToProjection, c as validateActivationSelection, ca as HOST_COHORTS, ci as validateManifest, cn as CONTROL_RECORD_PREFIX, co as sessionBirthIdentity, cr as removalIsComplete, ct as parsePwshCommand, d as prepareActivationMigration, da as evaluateExternalWaitCapability, di as auditedDefaultWorkdirHost, dn as assessmentAction, do as applyPrivateLedger, dr as captureItem, dt as segmentAuthorityBlocks, ea as ACTIVE_HOST_COHORT_ID, ei as questionHeadsClause, en as confirmedV6CoreDiagnostic, eo as readActivationMigrationReceipt, er as nativeFileTwoRole, et as extractToolSubject, f as verifyMigrationInventory, fa as evaluateGraphDerivedHostLock, fi as auditedDefaultWorkdirProvider, fn as assessmentOutcomePredicate, fo as hasPrivateRestartIntent, fr as classifyClause, ft as bindingIndividuallyAccepted, g as commitIndexSnapshotDigest, ga as hostVersionFromPackages, gi as evaluateActiveHostLock, gn as decideTurnStopping, go as readPrivateLedger, gr as extractOperation, gt as PROOF_KINDS_V2, h as GIT_COMMAND_TEMPLATES, ha as evaluateToolSurfaceCapability, hi as combineHostPolicy, hn as decideTurnBoundary, ho as privateLedgerTargetDigest, hr as extractMethod, ht as PROOF_KINDS, i as prepareSelectedActivationMigration, ia as DEFAULT_HOST_LOCK, ii as splitTextFragments, in as bindingSatisfies, io as writeActivationBinding, ir as admissibleForRemoval, it as shellReadbackOutcome, j as sessionCoreSnapshot, ja as CERTIFICATE_VERSION_V2, ji as resolveInstalledHostLock, jn as needsReviewObligations, jo as sanitizeClauseText, jr as governedClauseRestrictsExecution, jt as proofV2Rejection, k as previewFirstStepInjection, ka as BOUNDED_ARTIFACT_TYPES, ki as resolveActiveProfileHostLock, kn as certifiableOpenItems, ko as digestStrings, kr as clauseIsProtected, kt as proofHostSurfacesOf, l as verifySelectedMigrationInventory, la as bindExecutableIdentity, li as HostProfileError, ln as NO_PROGRESS_RECORD_PREFIX, lo as validateActivationBinding, lr as removalIsPartiallyKnown, lt as parseShellCommand, m as GIT_COMMAND_MANIFEST_IDS, ma as evaluateHostLock, mi as auditedHostImplementation, mn as currentActionBases, mo as privateLedgerContractDigest, mr as extractArtifactPaths, mt as PROOF_CAPABILITY_MATRIX, n as createActivationSelection, na as ACTIVE_HOST_LAUNCHER_VERSION, ni as restatedContentOf, nn as isV6PendingRootWait, no as resolveSessionActivation, nr as DEPENDENCY_FREE_ONLY_CONDITION, nt as nativeGitParentOidVerified, o as selectedActivationInventory, oa as GOAL_HOST_PACKAGES, oi as verbIsNegated, on as evidenceMatchesItem, oo as activationDigest, or as capabilityFactOf, ot as canonicalArgvFromCommand, p as RC020_RC1_HOST_PACKAGES, pa as evaluateHostCapability, pi as auditedForegroundRenderers, pn as classifyCompletionClaim, po as initializePrivateLedger, pr as environmentDefaultRepositoryTarget, pt as certifyCheckpoint, q as deriveProjection, qa as RC020_RC2_HOST_PACKAGES, qi as HostTrustError, qn as CONFIRM_LINE_PATTERN, qr as maskCodeSpans, qt as cleanupConditionFor, r as isSelectedActivationReceipt, ra as BASE_HOST_PACKAGES, ri as semanticActionOfScope, rn as sourceItemForCoreRequirement, ro as validateActivationMigrationReceipt, rr as actionHasCertificationPath, rt as persistedToolResultStatus, s as validateActivationInventorySnapshot, sa as HOST_CAPABILITY_PACKAGE_GROUPS, si as COMMAND_SURFACE_MANIFEST, sn as isVerifyingCapability, so as activationJson, sr as partialFailureOf, st as isRunExecutable, t as activationSelectionPending, ta as ACTIVE_HOST_COHORT_IDS, ti as reportingHeadGoverns, tn as currentV6Feedback, to as resolveActivationBindingsRoot, tr as relevantEvidence, tt as isDeterministicCheck, u as inspectActivationInventory, ua as bindLiveGoalCapability, ui as activeRendererModule, un as NO_PROGRESS_TURNS_BEFORE_STOP, uo as appendPrivateLedger, ur as captureClause, ut as authorityCaptureCounts, v as createGitPrestateEnvelope, va as HOST_VALIDATED_VERSIONS, vi as hostLockContextFromComposedDump, vn as isRootPauseRequest, vo as RELEASE_OPERATIONS, vr as segmentClauses, vt as PROOF_PROTOCOL_VERSION, w as FIRST_STEP_GUIDANCE, wa as evaluateMinimumHostVersion, wi as packageRowsFromPnpmLock, wn as testOutcomePredicate, wo as releaseContractFor, wr as LEGACY_QUALIFICATION, wt as createProofManifestV2, x as parseGitCommandManifest, xa as SUPPORTED_HOST_RANGE, xi as inspectDesktopTargetGraph, xn as latestRootInstruction, xo as inFlightReservation, xr as classifyTaskIntent, xt as bindProofV2ToProjection, y as executeRevalidatedGitEffect, ya as LATEST_TESTED_HOST_VERSION, yi as hostLockRowsFromComposedDump, yn as isWholeTaskCompletionClaim, yo as RELEASE_OPERATION_SURFACES, yr as canonicalRegistryBase, yt as PROOF_PROTOCOL_VERSION_V2, z as projectCoreV2, za as isStatefulAction, zi as memoizedAsarFile, zn as createProjection, zr as isExplanationScope, zt as CLEANUP_CONDITION_RULE_COMPACT } from "./domain-CE_dWoec.js";
2
2
  import { boundContextSummary, createUserMessage } from "@deepseek-ai/dsh-llm";
3
+ import { constants, existsSync, readFileSync } from "node:fs";
3
4
  import { basename, delimiter, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
5
+ import { homedir, tmpdir } from "node:os";
6
+ import { createHash } from "node:crypto";
4
7
  import { fileURLToPath } from "node:url";
5
- import { createHash, randomBytes } from "node:crypto";
6
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, unlinkSync, writeSync } from "node:fs";
7
8
  import { gunzip } from "node:zlib";
8
9
  import { execFile } from "node:child_process";
9
- import { homedir, hostname, tmpdir } from "node:os";
10
10
  import { JobId } from "@deepseek-ai/dsh-jobs";
11
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -2471,9 +2471,9 @@ async function profilePackage(profilePath, packageId) {
2471
2471
  }
2472
2472
  }
2473
2473
  async function registryIntegrity(registry, packageId, version, roots, signal) {
2474
- const canonical$1 = canonicalRegistryBase(registry, { allowLoopbackHttp: roots.allowLoopbackHttpRegistry });
2475
- if (!canonical$1 || canonical$1 !== registry) return void 0;
2476
- const response = await (roots.fetcher ?? fetch)(new URL(npmEscapedPackageName(packageId), canonical$1), {
2474
+ const canonical = canonicalRegistryBase(registry, { allowLoopbackHttp: roots.allowLoopbackHttpRegistry });
2475
+ if (!canonical || canonical !== registry) return void 0;
2476
+ const response = await (roots.fetcher ?? fetch)(new URL(npmEscapedPackageName(packageId), canonical), {
2477
2477
  signal,
2478
2478
  headers: { accept: "application/json" },
2479
2479
  redirect: "error"
@@ -2569,14 +2569,14 @@ async function executableIdentity(executable, signal) {
2569
2569
  const candidate = resolve(directory, `${executable}${suffix}`);
2570
2570
  try {
2571
2571
  await access(candidate, constants.X_OK);
2572
- const canonical$1 = await realpath(candidate);
2573
- const interpreter = process.platform === "win32" && /\.(?:cmd|bat)$/i.test(canonical$1) ? await windowsCommandInterpreter(signal) : void 0;
2574
- if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(canonical$1) && !interpreter) continue;
2575
- const { stdout, stderr } = await execAuditedFile(canonical$1, ["--version"], { signal }, interpreter);
2572
+ const canonical = await realpath(candidate);
2573
+ const interpreter = process.platform === "win32" && /\.(?:cmd|bat)$/i.test(canonical) ? await windowsCommandInterpreter(signal) : void 0;
2574
+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(canonical) && !interpreter) continue;
2575
+ const { stdout, stderr } = await execAuditedFile(canonical, ["--version"], { signal }, interpreter);
2576
2576
  const version = `${stdout}${stderr}`.trim();
2577
2577
  if (version && !version.includes("\n") && !version.includes("\r")) return {
2578
2578
  executable,
2579
- realpath: canonical$1,
2579
+ realpath: canonical,
2580
2580
  version,
2581
2581
  ...interpreter
2582
2582
  };
@@ -5609,7 +5609,7 @@ defineMethod("transform", [
5609
5609
  //#endregion
5610
5610
  //#region src/config.ts
5611
5611
  const Config = Schema.object({
5612
- activation: Schema.string().default("opt-in"),
5612
+ activation: Schema.string(),
5613
5613
  policy: Schema.string().default("standard"),
5614
5614
  hostLockPlatform: Schema.string(),
5615
5615
  hostLockProfile: Schema.string(),
@@ -5622,10 +5622,10 @@ const Config = Schema.object({
5622
5622
  name: Schema.string().required(),
5623
5623
  version: Schema.string(),
5624
5624
  integrity: Schema.string()
5625
- }))
5625
+ })).default(void 0)
5626
5626
  });
5627
5627
  function resolveConfig(config) {
5628
- const activation = config.activation ?? "opt-in";
5628
+ const activation = config.activation ?? "always";
5629
5629
  if (activation !== "opt-in" && activation !== "always") throw new TypeError(`activation must be "opt-in" or "always", received ${JSON.stringify(activation)}`);
5630
5630
  const policy = config.policy ?? "standard";
5631
5631
  if (policy !== "standard" && policy !== "strict" && policy !== "release") throw new TypeError(`policy must be "standard", "strict", or "release", received ${JSON.stringify(policy)}`);
@@ -5663,6 +5663,7 @@ function resolveConfig(config) {
5663
5663
  ...typeof config.hostLockRuntimeRoot === "string" ? { hostLockRuntimeRoot: config.hostLockRuntimeRoot } : {},
5664
5664
  ...typeof config.hostLockProfileRoot === "string" ? { hostLockProfileRoot: config.hostLockProfileRoot } : {},
5665
5665
  activation,
5666
+ activationSource: config.activation == null ? "default" : "explicit",
5666
5667
  policy,
5667
5668
  ...hostLockPackages ? { hostLockPackages } : {},
5668
5669
  ...config.hostLockPlatform ? { hostLockPlatform: config.hostLockPlatform } : {},
@@ -5670,714 +5671,6 @@ function resolveConfig(config) {
5670
5671
  };
5671
5672
  }
5672
5673
 
5673
- //#endregion
5674
- //#region src/domain/private-ledger.ts
5675
- const normalizeContext = (value) => typeof value === "string" ? {
5676
- sessionId: value,
5677
- sessionHeader: { id: value },
5678
- cwd: "/",
5679
- hostLockDigest: "test-seam"
5680
- } : value;
5681
- const canonical = (value) => {
5682
- if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
5683
- if (typeof value === "number") {
5684
- if (!Number.isFinite(value) || Object.is(value, -0)) throw new TypeError("private_ledger_non_json_number");
5685
- return JSON.stringify(value);
5686
- }
5687
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
5688
- if (value && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
5689
- throw new TypeError("private_ledger_non_json_value");
5690
- };
5691
- const digestRecord = (record$2) => sha256(canonical(record$2));
5692
- const sessionDigest = (sessionId) => sha256(`dsh-completion-guard/private-ledger/v1\0${sessionId}`);
5693
- const contextDigest = (context, root) => sha256(canonical({
5694
- session_sha256: sessionDigest(context.sessionId),
5695
- session_header: context.sessionHeader,
5696
- cwd_sha256: sha256(context.cwd),
5697
- host_lock_sha256: context.hostLockDigest,
5698
- ledger_root_sha256: sha256(realpathSync(root))
5699
- }));
5700
- const ledgerPath = (root, context) => join(root, `${sessionDigest(context.sessionId)}.jsonl`);
5701
- const anchorPath = (root) => join(root, "session-anchors.v1.jsonl");
5702
- const privateLedgerContractDigest = (contract) => {
5703
- if (!contract || typeof contract !== "object" || Array.isArray(contract)) return sha256(canonical(contract));
5704
- const { revokedAtSeq: _mutableRevocation,...immutable } = contract;
5705
- return sha256(canonical(immutable));
5706
- };
5707
- const privateLedgerTargetDigest = (target) => sha256(canonical(target));
5708
- /** Mirrors the audited dsh-home-paths precedence without importing another host package. */
5709
- function resolvePrivateLedgerRoot(configured, envHome, osHome) {
5710
- const selected = configured ?? (envHome?.trim() ? envHome : join(osHome, ".dsh"));
5711
- if (!selected || !osHome) return void 0;
5712
- return join(resolve(selected === "~" ? osHome : selected.startsWith("~/") || selected.startsWith("~\\") ? join(osHome, selected.slice(2)) : selected), "completion-guard", "private-ledger-v1");
5713
- }
5714
- function ensureRoot(root) {
5715
- if (resolve(root) !== root) throw new Error("private_ledger_root_not_normalized");
5716
- mkdirSync(root, {
5717
- recursive: true,
5718
- mode: 448
5719
- });
5720
- const stat = lstatSync(root);
5721
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("private_ledger_root_unsafe");
5722
- }
5723
- function openRegular(path, flags, mode = 384) {
5724
- try {
5725
- const entry = lstatSync(path);
5726
- if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("private_ledger_file_unsafe");
5727
- } catch (error) {
5728
- if (error.code !== "ENOENT") throw error;
5729
- }
5730
- const fd = openSync(path, flags | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW), mode);
5731
- try {
5732
- const stat = fstatSync(fd);
5733
- const entry = lstatSync(path);
5734
- if (!stat.isFile() || !entry.isFile() || entry.isSymbolicLink() || stat.dev !== entry.dev || stat.ino !== entry.ino) throw new Error("private_ledger_file_unsafe");
5735
- if (process.platform !== "win32" && (stat.mode & 63) !== 0) fchmodSync(fd, 384);
5736
- return fd;
5737
- } catch (error) {
5738
- closeSync(fd);
5739
- throw error;
5740
- }
5741
- }
5742
- function writeAll(fd, text) {
5743
- const bytes = Buffer.from(text);
5744
- let offset = 0;
5745
- while (offset < bytes.length) {
5746
- const written = writeSync(fd, bytes, offset, bytes.length - offset);
5747
- if (written <= 0) throw new Error("private_ledger_partial_write");
5748
- offset += written;
5749
- }
5750
- }
5751
- function syncDirectory(root) {
5752
- if (process.platform === "win32") return;
5753
- const fd = openSync(root, constants.O_RDONLY);
5754
- try {
5755
- fsyncSync(fd);
5756
- } finally {
5757
- closeSync(fd);
5758
- }
5759
- }
5760
- function readAnchors(root) {
5761
- const path = anchorPath(root);
5762
- if (!existsSync(path)) return /* @__PURE__ */ new Map();
5763
- const fd = openRegular(path, constants.O_RDONLY);
5764
- let raw;
5765
- try {
5766
- raw = readFileSync(fd, "utf8");
5767
- } finally {
5768
- closeSync(fd);
5769
- }
5770
- if (raw && !raw.endsWith("\n")) throw new Error("private_ledger_anchor_truncated");
5771
- const anchors = /* @__PURE__ */ new Map();
5772
- for (const line of raw.split("\n").filter(Boolean)) {
5773
- const value = JSON.parse(line);
5774
- const unsigned = {
5775
- version: 1,
5776
- session_sha256: value.session_sha256,
5777
- context_sha256: value.context_sha256
5778
- };
5779
- if (value.version !== 1 || typeof value.session_sha256 !== "string" || typeof value.context_sha256 !== "string" || value.anchor_sha256 !== sha256(canonical(unsigned))) throw new Error("private_ledger_anchor_invalid");
5780
- const existing = anchors.get(value.session_sha256);
5781
- if (existing && existing !== value.context_sha256) throw new Error("private_ledger_anchor_conflict");
5782
- anchors.set(value.session_sha256, value.context_sha256);
5783
- }
5784
- return anchors;
5785
- }
5786
- /**
5787
- * The one full ledger read+chain-verify, shared by the read and append paths
5788
- * (CG-083-PERF05: an append used to re-read the anchors AND the whole ledger
5789
- * after already reading the anchors under the lock). Callers must already
5790
- * hold the writer lock or accept the unlocked-read race the public API had.
5791
- * Returns `undefined` for "ledger file missing" so callers can distinguish
5792
- * the anchored-but-missing (damaged) case from an empty ledger.
5793
- */
5794
- function readVerifiedLedgerRecords(root, context, session, expectedContext) {
5795
- const path = ledgerPath(root, context);
5796
- if (!existsSync(path)) return void 0;
5797
- const fd = openRegular(path, constants.O_RDONLY);
5798
- let raw;
5799
- try {
5800
- raw = readFileSync(fd, "utf8");
5801
- } finally {
5802
- closeSync(fd);
5803
- }
5804
- if (raw && !raw.endsWith("\n")) return void 0;
5805
- const records = [];
5806
- let prior = null;
5807
- for (const [index, line] of raw.split("\n").filter(Boolean).entries()) {
5808
- const value = JSON.parse(line);
5809
- const { record_sha256,...unsigned } = value;
5810
- if (value.version !== 1 || value.session_sha256 !== session || value.context_sha256 !== expectedContext || value.position !== index + 1 || value.prior_sha256 !== prior || ![
5811
- "release_reservation",
5812
- "release_settlement",
5813
- "restart_intent"
5814
- ].includes(value.kind) || !value.payload || typeof value.payload !== "object" || Array.isArray(value.payload) || record_sha256 !== digestRecord(unsigned)) return void 0;
5815
- records.push(value);
5816
- prior = record_sha256;
5817
- }
5818
- return records;
5819
- }
5820
- /**
5821
- * CG-083-F1 (revision 3): arbitration-log writer lock with optimistic
5822
- * concurrency control. See docs/WRITER_LOCK_PROTOCOL.md "Revision 3".
5823
- *
5824
- * All authority decisions are records appended to `arbitration.log` (atomicity
5825
- * assumptions A1/A2 in the doc). A claim carries `prev` — the holder nonce the
5826
- * claimant observed — and the deterministic replay grants it only if the
5827
- * current holder at its log position equals `prev`. Recovery appends
5828
- * `evict {prev: deadNonce}` after an ESRCH probe; a delayed recoverer's record
5829
- * is adjudicated against the CURRENT holder and simply has no effect when the
5830
- * holder changed (L1/L2 structurally impossible: nothing is ever deleted from
5831
- * or done to a pathname on the basis of an older observation).
5832
- *
5833
- * Bidirectional v2 upgrade barrier (L3): the v3 critical section also holds
5834
- * the v2-shaped root `.writer.lock` (O_EXCL, version-2-shaped owner record).
5835
- * A live v2 writer refuses (file exists); v3 refuses while a live/unknown v2
5836
- * record exists; a v2 record whose pid answers ESRCH is removed by name (v2
5837
- * has no self-recovery) and the migration proceeds.
5838
- */
5839
- const ARBITRATION_NAME = "arbitration.log";
5840
- const LEGACY_V2_LOCK_NAME = ".writer.lock";
5841
- const PENDING_PREFIX = "pending.";
5842
- const LOG_COMPACTION_RECORDS = 8192;
5843
- function arbitrationPath(root) {
5844
- return join(root, ARBITRATION_NAME);
5845
- }
5846
- function legacyV2Path(root) {
5847
- return join(root, LEGACY_V2_LOCK_NAME);
5848
- }
5849
- /**
5850
- * Parse the log (docs/WRITER_LOCK_PROTOCOL.md Revision 3.1, correction 3).
5851
- * Unparseable lines — torn tails from a crash mid-append — are SKIPPED: they
5852
- * never took effect, so skipping revokes nothing, and later complete records
5853
- * stay visible (there is no truncation anywhere in the protocol, so a
5854
- * truncate-and-revive race cannot exist). A final line without a trailing
5855
- * newline is still replayed when it parses: it was fully written.
5856
- */
5857
- function parseArbitration(root) {
5858
- let raw;
5859
- try {
5860
- raw = readFileSync(arbitrationPath(root), "utf8");
5861
- } catch {
5862
- return [];
5863
- }
5864
- const records = [];
5865
- for (const line of raw.split("\n")) {
5866
- if (line === "") continue;
5867
- try {
5868
- const value = JSON.parse(line);
5869
- if (value && value.v === 3 && (value.op === "claim" || value.op === "release" || value.op === "evict") && typeof value.nonce === "string" && value.nonce.length === 32 && typeof value.pid === "number" && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.hostname === "string" && typeof value.created_at_epoch_ms === "number" && (value.prev === null || typeof value.prev === "string")) records.push(value);
5870
- } catch {}
5871
- }
5872
- return records;
5873
- }
5874
- /**
5875
- * Deterministic replay (docs/WRITER_LOCK_PROTOCOL.md Revision 3.1). A claim
5876
- * is effective ONLY when the slot is empty: a claim recorded while another
5877
- * holder is current (e.g. one whose barrier was stolen on a stale legacy
5878
- * observation) is stored but INEFFECTIVE, and the claimant exits on its
5879
- * read-back. Release/evict take effect only for the current holder nonce.
5880
- */
5881
- function replayHolder(records) {
5882
- let holder = null;
5883
- for (const record$2 of records) {
5884
- const isHolder = holder !== null && holder.nonce === record$2.prev;
5885
- if (record$2.op === "claim") {
5886
- if (holder === null) holder = {
5887
- nonce: record$2.nonce,
5888
- pid: record$2.pid,
5889
- hostname: record$2.hostname,
5890
- created_at_epoch_ms: record$2.created_at_epoch_ms
5891
- };
5892
- } else if (record$2.op === "release" || record$2.op === "evict") {
5893
- if (isHolder) holder = null;
5894
- }
5895
- }
5896
- return holder;
5897
- }
5898
- function readHolder(root) {
5899
- return replayHolder(parseArbitration(root));
5900
- }
5901
- /** Only ESRCH proves a recorded owner is gone; any other answer refuses. */
5902
- function processExists(pid) {
5903
- try {
5904
- process.kill(pid, 0);
5905
- return true;
5906
- } catch (error) {
5907
- return error.code !== "ESRCH";
5908
- }
5909
- }
5910
- function unlinkIfExists(path) {
5911
- try {
5912
- unlinkSync(path);
5913
- } catch (error) {
5914
- if (error.code !== "ENOENT") throw error;
5915
- }
5916
- }
5917
- function appendArbitration(root, record$2) {
5918
- let needsNewline = false;
5919
- try {
5920
- const raw = readFileSync(arbitrationPath(root), "utf8");
5921
- needsNewline = raw.length > 0 && !raw.endsWith("\n");
5922
- } catch {
5923
- needsNewline = false;
5924
- }
5925
- const fd = openRegular(arbitrationPath(root), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, 384);
5926
- try {
5927
- writeAll(fd, `${needsNewline ? "\n" : ""}${canonical(record$2)}\n`);
5928
- fsyncSync(fd);
5929
- } finally {
5930
- closeSync(fd);
5931
- }
5932
- }
5933
- function readLegacyV2(root) {
5934
- let raw;
5935
- try {
5936
- raw = readFileSync(legacyV2Path(root), "utf8");
5937
- } catch {
5938
- return;
5939
- }
5940
- if (!raw.trim()) return "legacy";
5941
- try {
5942
- const value = JSON.parse(raw);
5943
- if (value && (value.version === 2 || value.version === 3) && typeof value.nonce === "string" && (value.nonce.length === 32 || value.version === 2) && typeof value.pid === "number" && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.hostname === "string" && typeof value.created_at_epoch_ms === "number") return value;
5944
- } catch {}
5945
- return "legacy";
5946
- }
5947
- function pendingPath(root, nonce) {
5948
- return join(root, `${PENDING_PREFIX}${nonce}.json`);
5949
- }
5950
- function removeOwnPending(root, nonce) {
5951
- unlinkIfExists(pendingPath(root, nonce));
5952
- }
5953
- function readRecord(path) {
5954
- let raw;
5955
- try {
5956
- raw = readFileSync(path, "utf8");
5957
- } catch {
5958
- return;
5959
- }
5960
- if (!raw.trim()) return "legacy";
5961
- try {
5962
- const value = JSON.parse(raw);
5963
- if (value && (value.version === 2 || value.version === 3) && typeof value.nonce === "string" && (value.nonce.length === 32 || value.version === 2) && typeof value.pid === "number" && Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.hostname === "string" && typeof value.created_at_epoch_ms === "number") return value;
5964
- } catch {}
5965
- return "legacy";
5966
- }
5967
- function recordIsProvablyDead(record$2) {
5968
- return record$2.hostname === hostname() && !processExists(record$2.pid);
5969
- }
5970
- /** Append one arbitration record (the ONLY mutation of the log). */
5971
- function appendLog(root, op, nonce, prev) {
5972
- appendArbitration(root, {
5973
- v: 3,
5974
- op,
5975
- nonce,
5976
- prev,
5977
- pid: process.pid,
5978
- hostname: hostname(),
5979
- created_at_epoch_ms: Date.now()
5980
- });
5981
- }
5982
- /**
5983
- * Acquire the writer lock. Returns the held nonce, or undefined when refused
5984
- * (live/unknown holder, v2 barrier, or a lost optimistic claim).
5985
- */
5986
- /**
5987
- * Admission (Revision 3.1 + 3.2). The v2-compat barrier is PUBLISHED
5988
- * atomically: the writer prepares `pending.<nonce>` with its complete owner
5989
- * record (write + fsync) and hard-links it to `.writer.lock` — the barrier
5990
- * therefore never exists with empty or partial content from this protocol
5991
- * (S2 closed: a crash before the link leaves only an inert pending file, and
5992
- * a crash after it leaves a complete record naming a provably dead owner,
5993
- * both recoverable). A barrier left by a crashed V2 WRITER (empty, partial,
5994
- * or complete-with-dead-pid) is classified separately: unknown owners refuse
5995
- * with the documented manual migration; a complete same-host record whose
5996
- * pid answers ESRCH is ADOPTED untouched. The log claim is effective only on
5997
- * an empty slot and is verified by read-back.
5998
- */
5999
- function acquireWriterLock(root) {
6000
- for (let attempt = 0; attempt < 16; attempt += 1) {
6001
- gcPendingFiles(root);
6002
- let barrierState = "absent";
6003
- const legacy = readLegacyV2(root);
6004
- if (legacy !== void 0) if (legacy === "legacy") barrierState = "unknown";
6005
- else if (legacy.hostname !== hostname()) barrierState = "unknown";
6006
- else if (processExists(legacy.pid)) barrierState = "live";
6007
- else barrierState = "adopted";
6008
- if (barrierState === "unknown" || barrierState === "live") return void 0;
6009
- const observed = readHolder(root);
6010
- if (observed !== null) {
6011
- if (observed.hostname !== hostname()) return void 0;
6012
- if (!processExists(observed.pid)) {
6013
- appendLog(root, "evict", randomBytes(16).toString("hex"), observed.nonce);
6014
- continue;
6015
- }
6016
- return;
6017
- }
6018
- const nonce = randomBytes(16).toString("hex");
6019
- let ownedBarrier = false;
6020
- if (barrierState === "absent") {
6021
- if (!publishBarrier(root, nonce)) continue;
6022
- ownedBarrier = true;
6023
- }
6024
- appendLog(root, "claim", nonce, null);
6025
- const holder = readHolder(root);
6026
- if (holder !== null && holder.nonce === nonce) {
6027
- compactLogInTenure(root, {
6028
- nonce,
6029
- ownedBarrier
6030
- });
6031
- return {
6032
- nonce,
6033
- ownedBarrier
6034
- };
6035
- }
6036
- if (ownedBarrier) {
6037
- const barrier = readLegacyV2(root);
6038
- if (barrier !== void 0 && barrier !== "legacy" && barrier.nonce === nonce) unlinkIfExists(legacyV2Path(root));
6039
- }
6040
- unlinkIfExists(pendingPath(root, nonce));
6041
- return;
6042
- }
6043
- }
6044
- /**
6045
- * Publish the v2-compat barrier atomically (Revision 3.2): write the complete
6046
- * owner record to a unique pending file (O_EXCL + fsync), then hard-link it
6047
- * onto the barrier pathname. link() succeeds only when the barrier is absent,
6048
- * and the linked content is the fully written record — the barrier can never
6049
- * be observed empty or partial from this protocol. Returns false when the
6050
- * barrier exists (caller re-classifies).
6051
- */
6052
- function publishBarrier(root, nonce) {
6053
- const pending = pendingPath(root, nonce);
6054
- let fd;
6055
- try {
6056
- fd = openRegular(pending, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);
6057
- } catch (error) {
6058
- if (error.code === "EEXIST") return false;
6059
- throw error;
6060
- }
6061
- try {
6062
- const record$2 = {
6063
- version: 2,
6064
- nonce,
6065
- pid: process.pid,
6066
- hostname: hostname(),
6067
- created_at_epoch_ms: Date.now()
6068
- };
6069
- writeAll(fd, `${canonical(record$2)}\n`);
6070
- fsyncSync(fd);
6071
- } finally {
6072
- try {
6073
- closeSync(fd);
6074
- } catch {}
6075
- }
6076
- try {
6077
- linkSync(pending, legacyV2Path(root));
6078
- return true;
6079
- } catch (error) {
6080
- unlinkIfExists(pending);
6081
- if (error.code === "EEXIST") return false;
6082
- throw error;
6083
- }
6084
- }
6085
- /** GC pending files whose embedded creator is provably dead (by name). */
6086
- function gcPendingFiles(root) {
6087
- let entries;
6088
- try {
6089
- entries = readdirSync(root);
6090
- } catch {
6091
- return;
6092
- }
6093
- for (const entry of entries) {
6094
- if (!entry.startsWith(PENDING_PREFIX)) continue;
6095
- const record$2 = readRecord(join(root, entry));
6096
- if (record$2 !== void 0 && record$2 !== "legacy" && recordIsProvablyDead(record$2)) unlinkIfExists(join(root, entry));
6097
- }
6098
- }
6099
- /**
6100
- * Release (Revision 3.1): append the release record, then remove ONLY a
6101
- * barrier this writer created in its own critical section (nonce-conditional).
6102
- * An ADOPTED legacy barrier is left untouched — it keeps blocking v2 writers
6103
- * until the documented manual migration removes it, and every later v3
6104
- * admission re-adopts it.
6105
- */
6106
- function releaseWriterLock(root, held) {
6107
- if (held === void 0) return;
6108
- appendLog(root, "release", held.nonce, held.nonce);
6109
- if (held.ownedBarrier) {
6110
- const barrier = readLegacyV2(root);
6111
- if (barrier !== void 0 && barrier !== "legacy" && barrier.nonce === held.nonce) unlinkIfExists(legacyV2Path(root));
6112
- }
6113
- removeOwnPending(root, held.nonce);
6114
- }
6115
- /** Compaction threshold; test-overridable via the internals hook. */
6116
- let compactionRecordThreshold = LOG_COMPACTION_RECORDS;
6117
- /**
6118
- * Compaction (Revision 3.1, correction 4): performed ONLY by the current
6119
- * holder inside its verified critical section. During a live holder's tenure
6120
- * no concurrent record can be effective (claims need an empty slot; evicts
6121
- * need a dead holder), so the rename window cannot drop an effective record:
6122
- * the baseline re-installs the holder, and readers see the old or the new
6123
- * file, both replaying to the same holder. State-equivalence is asserted by
6124
- * the lock tests.
6125
- */
6126
- function compactLogInTenure(root, held) {
6127
- if (parseArbitration(root).length <= compactionRecordThreshold) return;
6128
- const baseline = {
6129
- v: 3,
6130
- op: "claim",
6131
- nonce: held.nonce,
6132
- pid: process.pid,
6133
- hostname: hostname(),
6134
- created_at_epoch_ms: Date.now(),
6135
- prev: null
6136
- };
6137
- const tmp = join(root, `${ARBITRATION_NAME}.compact`);
6138
- const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, 384);
6139
- try {
6140
- writeAll(fd, `${canonical(baseline)}\n`);
6141
- fsyncSync(fd);
6142
- } finally {
6143
- closeSync(fd);
6144
- }
6145
- try {
6146
- renameSync(tmp, arbitrationPath(root));
6147
- } catch {}
6148
- }
6149
- function readPrivateLedger(root, input) {
6150
- if (!root) return {
6151
- records: [],
6152
- damaged: true,
6153
- anchored: false
6154
- };
6155
- try {
6156
- const context = normalizeContext(input);
6157
- if (!existsSync(root)) return {
6158
- records: [],
6159
- damaged: false,
6160
- anchored: false
6161
- };
6162
- const rootStat = lstatSync(root);
6163
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) return {
6164
- records: [],
6165
- damaged: true,
6166
- anchored: false
6167
- };
6168
- const session = sessionDigest(context.sessionId);
6169
- const expectedContext = contextDigest(context, root);
6170
- const anchored = readAnchors(root).get(session);
6171
- if (anchored !== void 0 && anchored !== expectedContext) return {
6172
- records: [],
6173
- damaged: true,
6174
- anchored: true
6175
- };
6176
- if (anchored === void 0) {
6177
- if (existsSync(ledgerPath(root, context))) return {
6178
- records: [],
6179
- damaged: true,
6180
- anchored: false
6181
- };
6182
- return {
6183
- records: [],
6184
- damaged: false,
6185
- anchored: false
6186
- };
6187
- }
6188
- const records = readVerifiedLedgerRecords(root, context, session, expectedContext);
6189
- if (records === void 0) return {
6190
- records: [],
6191
- damaged: true,
6192
- anchored: true
6193
- };
6194
- return {
6195
- records,
6196
- damaged: false,
6197
- anchored: true
6198
- };
6199
- } catch {
6200
- return {
6201
- records: [],
6202
- damaged: true,
6203
- anchored: false
6204
- };
6205
- }
6206
- }
6207
- /** Establish the provider-invisible anchor when a live runtime observes a new adoption. */
6208
- function initializePrivateLedger(root, input) {
6209
- if (!root) return false;
6210
- let lockFd;
6211
- try {
6212
- const context = normalizeContext(input);
6213
- ensureRoot(root);
6214
- lockFd = acquireWriterLock(root);
6215
- if (lockFd === void 0) return false;
6216
- const session = sessionDigest(context.sessionId);
6217
- const expectedContext = contextDigest(context, root);
6218
- const anchored = readAnchors(root).get(session);
6219
- if (anchored !== void 0) return anchored === expectedContext;
6220
- const unsignedAnchor = {
6221
- version: 1,
6222
- session_sha256: session,
6223
- context_sha256: expectedContext
6224
- };
6225
- const fd = openRegular(anchorPath(root), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND);
6226
- try {
6227
- writeAll(fd, `${canonical({
6228
- ...unsignedAnchor,
6229
- anchor_sha256: sha256(canonical(unsignedAnchor))
6230
- })}\n`);
6231
- fsyncSync(fd);
6232
- } finally {
6233
- closeSync(fd);
6234
- }
6235
- const ledgerFd = openRegular(ledgerPath(root, context), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL);
6236
- try {
6237
- fsyncSync(ledgerFd);
6238
- } finally {
6239
- closeSync(ledgerFd);
6240
- }
6241
- syncDirectory(root);
6242
- return true;
6243
- } catch {
6244
- return false;
6245
- } finally {
6246
- releaseWriterLock(root, lockFd);
6247
- }
6248
- }
6249
- function appendPrivateLedger(root, input, kind, payload) {
6250
- if (!root) return false;
6251
- let lockFd;
6252
- try {
6253
- const context = normalizeContext(input);
6254
- ensureRoot(root);
6255
- lockFd = acquireWriterLock(root);
6256
- if (lockFd === void 0) return false;
6257
- const session = sessionDigest(context.sessionId);
6258
- const expectedContext = contextDigest(context, root);
6259
- const anchored = readAnchors(root).get(session);
6260
- if (anchored !== void 0 && anchored !== expectedContext) return false;
6261
- let records = [];
6262
- if (anchored !== void 0) {
6263
- const verified = readVerifiedLedgerRecords(root, context, session, expectedContext);
6264
- if (verified === void 0) return false;
6265
- records = verified;
6266
- } else {
6267
- const unsignedAnchor = {
6268
- version: 1,
6269
- session_sha256: session,
6270
- context_sha256: expectedContext
6271
- };
6272
- const fd$1 = openRegular(anchorPath(root), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND);
6273
- try {
6274
- writeAll(fd$1, `${canonical({
6275
- ...unsignedAnchor,
6276
- anchor_sha256: sha256(canonical(unsignedAnchor))
6277
- })}\n`);
6278
- fsyncSync(fd$1);
6279
- } finally {
6280
- closeSync(fd$1);
6281
- }
6282
- syncDirectory(root);
6283
- }
6284
- if (kind === "release_settlement") {
6285
- const settlement = normalizeSettlement(payload);
6286
- const reservation = settlement && [...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);
6287
- if (!reservation) return false;
6288
- payload = {
6289
- ...payload,
6290
- reservation_sha256: reservation.record_sha256,
6291
- contract_sha256: reservation.payload.contract_sha256,
6292
- target_sha256: reservation.payload.target_sha256
6293
- };
6294
- }
6295
- const unsigned = {
6296
- version: 1,
6297
- session_sha256: session,
6298
- context_sha256: expectedContext,
6299
- position: records.length + 1,
6300
- prior_sha256: records.at(-1)?.record_sha256 ?? null,
6301
- kind,
6302
- payload
6303
- };
6304
- const record$2 = {
6305
- ...unsigned,
6306
- record_sha256: digestRecord(unsigned)
6307
- };
6308
- const fd = openRegular(ledgerPath(root, context), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND);
6309
- try {
6310
- writeAll(fd, `${canonical(record$2)}\n`);
6311
- fsyncSync(fd);
6312
- } finally {
6313
- closeSync(fd);
6314
- }
6315
- syncDirectory(root);
6316
- return true;
6317
- } catch {
6318
- return false;
6319
- } finally {
6320
- releaseWriterLock(root, lockFd);
6321
- }
6322
- }
6323
- function applyPrivateLedger(projection, snapshot$1) {
6324
- if (snapshot$1.damaged || projection.releaseContracts.length > 0 && snapshot$1.anchored === false) {
6325
- projection.releaseStateDamaged = true;
6326
- if (!projection.releaseDiagnostics.some((row) => row.reasonCode === "private_ledger_damaged")) projection.releaseDiagnostics.push({
6327
- seq: 0,
6328
- reasonCode: "private_ledger_damaged"
6329
- });
6330
- return;
6331
- }
6332
- const reservations = /* @__PURE__ */ new Map();
6333
- for (const record$2 of snapshot$1.records) if (record$2.kind === "release_reservation") {
6334
- const normalized = normalizeReservation(record$2.payload);
6335
- const contract = normalized && projection.releaseContracts.find((entry) => entry.contractId === normalized.contractId);
6336
- if (!normalized || !contract || record$2.payload.contract_sha256 !== privateLedgerContractDigest(contract) || typeof record$2.payload.target_sha256 !== "string") {
6337
- projection.releaseStateDamaged = true;
6338
- continue;
6339
- }
6340
- const key = `${normalized.contractId}\0${normalized.operation}\0${normalized.callId}`;
6341
- if (reservations.has(key)) {
6342
- projection.releaseStateDamaged = true;
6343
- continue;
6344
- }
6345
- reservations.set(key, record$2);
6346
- const existing = projection.releaseReservations.find((entry) => entry.callId === normalized.callId);
6347
- if (existing && (existing.contractId !== normalized.contractId || existing.operation !== normalized.operation)) {
6348
- projection.releaseStateDamaged = true;
6349
- continue;
6350
- }
6351
- if (!existing) projection.releaseReservations.push({
6352
- ...normalized,
6353
- startedAtSeq: 0,
6354
- ledgerPosition: record$2.position
6355
- });
6356
- } else if (record$2.kind === "release_settlement") {
6357
- const normalized = normalizeSettlement(record$2.payload);
6358
- const key = normalized && `${normalized.contractId}\0${normalized.operation}\0${normalized.callId}`;
6359
- const reservationRecord = key ? reservations.get(key) : void 0;
6360
- const contract = normalized && projection.releaseContracts.find((entry) => entry.contractId === normalized.contractId);
6361
- const source = record$2.payload.settlement_source;
6362
- const readbackVerdict = normalized && contract ? readbackSettlesContract(contract, normalized.readback, reservationRecord ? normalizeReservation(reservationRecord.payload)?.observedArtifactSri : void 0) : void 0;
6363
- if (!normalized || !reservationRecord || !contract || source !== "effect" && source !== "reconcile" || normalized.outcome === "not_effected" && source !== "effect" || source === "reconcile" && normalized.readback === "unavailable" || record$2.payload.reservation_sha256 !== reservationRecord.record_sha256 || record$2.payload.contract_sha256 !== reservationRecord.payload.contract_sha256 || record$2.payload.target_sha256 !== reservationRecord.payload.target_sha256 || normalized.outcome === "settled" && readbackVerdict !== "settled" || source === "reconcile" && readbackVerdict === "mismatch") {
6364
- projection.releaseStateDamaged = true;
6365
- continue;
6366
- }
6367
- const pinned = {
6368
- ...normalized,
6369
- settledAtSeq: 0,
6370
- ledgerPosition: record$2.position
6371
- };
6372
- const index = projection.releaseSettlements.findIndex((entry) => entry.contractId === pinned.contractId && entry.operation === pinned.operation && entry.callId === pinned.callId);
6373
- if (index < 0) projection.releaseSettlements.push(pinned);
6374
- else if (OUTCOME_STRENGTH[pinned.outcome] >= OUTCOME_STRENGTH[projection.releaseSettlements[index].outcome]) projection.releaseSettlements[index] = pinned;
6375
- }
6376
- }
6377
- function hasPrivateRestartIntent(snapshot$1, resolutionCallId, serviceId, preGeneration) {
6378
- 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);
6379
- }
6380
-
6381
5674
  //#endregion
6382
5675
  //#region src/runtime.ts
6383
5676
  const name = "context-guard";
@@ -6582,6 +5875,8 @@ async function handleGuardTurnStopping(agent, runtime, access$1) {
6582
5875
  runtime.setDurability(durable);
6583
5876
  runtime.sync({ revalidateHostLock: true });
6584
5877
  if (!durable) return "boundary_flush_failed";
5878
+ const modeFailure = runtime.projection.integrityViolations.find((code) => code.startsWith("activation_"));
5879
+ if (modeFailure) return modeFailure;
6585
5880
  const hostSupported = access$1.hostSupported && runtime.projection.hostStatus === "supported";
6586
5881
  const rootInstruction = latestRootInstruction(agent.session?.snapshotEvents?.() ?? []);
6587
5882
  if (rootInstruction !== void 0 && isRootPauseRequest(rootInstruction.text) && !runtime.projection.handledControlSeqs.has(rootInstruction.seq) && access$1.pauseAccess) {
@@ -6741,7 +6036,7 @@ function sessionHeaderForDigest(session) {
6741
6036
  delegationDepth: typeof raw.delegationDepth === "number" ? raw.delegationDepth : 0
6742
6037
  };
6743
6038
  }
6744
- function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalState, refreshHostLock, readPrivateRecords, initializePrivateRecords) {
6039
+ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalState, refreshHostLock, readPrivateRecords, initializePrivateRecords, readActivation) {
6745
6040
  const projection = createProjection();
6746
6041
  const session = agent.session;
6747
6042
  let pendingRecovery = false;
@@ -6761,6 +6056,8 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6761
6056
  const persistenceCorrectionAttempts = projection.persistenceCorrectionAttempts;
6762
6057
  let refreshEpoch = 0;
6763
6058
  let lastFullSync;
6059
+ let activationRead;
6060
+ let originalActivationKey;
6764
6061
  const sameSnapshotIdentity = (candidate, consumed) => {
6765
6062
  if (candidate.length !== consumed.length) return false;
6766
6063
  for (let index = 0; index < candidate.length; index += 1) if (candidate[index] !== consumed[index]) return false;
@@ -6775,10 +6072,11 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6775
6072
  * every container in the snapshot is Object.isFrozen, checked recursively
6776
6073
  * under a node budget. A snapshot that fails (or exhausts) the check is
6777
6074
  * "not provable" and always takes the full rebuild — fail-closed, never
6778
- * cached. Passing results are remembered per array object: freezing is
6779
- * irreversible, so a previously proven snapshot cannot become mutable.
6075
+ * cached. Passing results are remembered per fully proven container:
6076
+ * freezing is irreversible. Appending an event creates a new snapshot
6077
+ * array, but does not invalidate proofs of its unchanged frozen children.
6780
6078
  */
6781
- const provenImmutableSnapshots = /* @__PURE__ */ new WeakSet();
6079
+ const provenImmutableContainers = /* @__PURE__ */ new WeakSet();
6782
6080
  const IMMUTABILITY_PROOF_NODE_BUDGET = 4e5;
6783
6081
  /**
6784
6082
  * F2 (round 3): freezing a container does NOT freeze its content when a
@@ -6791,23 +6089,33 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6791
6089
  * anything mutable; only the descriptor SHAPE plus frozen containers are.
6792
6090
  */
6793
6091
  const snapshotIsProvablyImmutable = (events) => {
6794
- if (provenImmutableSnapshots.has(events)) return true;
6092
+ if (provenImmutableContainers.has(events)) return true;
6795
6093
  let visited = 0;
6094
+ const active = /* @__PURE__ */ new WeakSet();
6796
6095
  const walk = (value) => {
6797
6096
  if (value === null || typeof value !== "object") return true;
6097
+ if (provenImmutableContainers.has(value)) return true;
6798
6098
  if (++visited > IMMUTABILITY_PROOF_NODE_BUDGET) return false;
6799
6099
  if (!Object.isFrozen(value)) return false;
6100
+ const prototype = Object.getPrototypeOf(value);
6101
+ if (prototype !== null && prototype !== (Array.isArray(value) ? Array.prototype : Object.prototype)) return false;
6102
+ if (active.has(value)) return false;
6103
+ active.add(value);
6800
6104
  for (const key of Object.getOwnPropertyNames(value)) {
6801
6105
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
6802
6106
  if (!descriptor) return false;
6803
6107
  if (descriptor.get !== void 0 || descriptor.set !== void 0) return false;
6804
6108
  if (descriptor.value !== void 0 && !walk(descriptor.value)) return false;
6805
6109
  }
6110
+ active.delete(value);
6111
+ provenImmutableContainers.add(value);
6806
6112
  return true;
6807
6113
  };
6808
- if (!walk(events)) return false;
6809
- provenImmutableSnapshots.add(events);
6810
- return true;
6114
+ try {
6115
+ return walk(events);
6116
+ } catch {
6117
+ return false;
6118
+ }
6811
6119
  };
6812
6120
  const readGoalOnce = () => {
6813
6121
  if (!readGoalState) return {
@@ -6834,13 +6142,18 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6834
6142
  const priorRecoveryDigest = projection.lastRecoveryDigest;
6835
6143
  const sessionHeader = sessionHeaderForDigest(session);
6836
6144
  const derived = deriveProjection(events, {
6837
- activation: config.activation,
6145
+ activation: readActivation ? activationRead?.status === "bound" ? activationRead.mode : "opt-in" : config.activation,
6838
6146
  policy: config.policy
6839
6147
  }, {
6840
6148
  cwd: typeof header?.cwd === "string" ? header.cwd : "",
6841
6149
  sessionHeader
6842
6150
  }, durabilityConfirmed, hostLock);
6843
6151
  Object.assign(projection, derived.projection);
6152
+ if (readActivation && activationRead?.status !== "bound") {
6153
+ projection.enabled = false;
6154
+ projection.integrity = "unknown";
6155
+ projection.integrityViolations.push(activationRead?.reasonCode ?? "activation_mode_unknown");
6156
+ }
6844
6157
  if (readPrivateRecords && ledger) {
6845
6158
  let privateSnapshot = ledger;
6846
6159
  if (!synchronizedOnce && events.length === 0 && !privateSnapshot.damaged && !privateSnapshot.anchored && initializePrivateRecords?.()) privateSnapshot = readPrivateRecords();
@@ -6860,6 +6173,7 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6860
6173
  durability: durabilityConfirmed,
6861
6174
  goalKey: goalKeyOf(goal),
6862
6175
  ledgerKey: ledger ? ledgerSnapshotKey(ledger) : "",
6176
+ activationKey: activationRead?.key ?? "explicit-runtime",
6863
6177
  refreshEpoch
6864
6178
  };
6865
6179
  if (!sessionHeader) {
@@ -6940,9 +6254,26 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6940
6254
  lastFullSync = void 0;
6941
6255
  return;
6942
6256
  }
6257
+ if (readActivation) try {
6258
+ activationRead = readActivation();
6259
+ if (activationRead.status === "bound") {
6260
+ if (originalActivationKey === void 0) originalActivationKey = activationRead.key;
6261
+ else if (activationRead.key !== originalActivationKey) activationRead = {
6262
+ status: "unavailable",
6263
+ reasonCode: "activation_binding_changed",
6264
+ key: "changed"
6265
+ };
6266
+ }
6267
+ } catch {
6268
+ activationRead = {
6269
+ status: "unavailable",
6270
+ reasonCode: "activation_storage_unavailable",
6271
+ key: "error"
6272
+ };
6273
+ }
6943
6274
  const goal = readGoalOnce();
6944
6275
  const ledger = readPrivateRecords ? readPrivateRecords() : void 0;
6945
- if (lastFullSync && snapshotIsProvablyImmutable(events) && lastFullSync.refreshEpoch === refreshEpoch && sameSnapshotIdentity(events, lastFullSync.events) && Object.is(lastFullSync.headerRef, session.header) && lastFullSync.durability === durabilityConfirmed && lastFullSync.goalKey === goalKeyOf(goal) && (!readPrivateRecords || lastFullSync.ledgerKey === ledgerSnapshotKey(ledger))) return;
6276
+ if (lastFullSync && lastFullSync.activationKey === (activationRead?.key ?? "explicit-runtime") && lastFullSync.refreshEpoch === refreshEpoch && Object.is(lastFullSync.headerRef, session.header) && lastFullSync.durability === durabilityConfirmed && lastFullSync.goalKey === goalKeyOf(goal) && (!readPrivateRecords || lastFullSync.ledgerKey === ledgerSnapshotKey(ledger)) && sameSnapshotIdentity(events, lastFullSync.events) && snapshotIsProvablyImmutable(events)) return;
6946
6277
  rebuild(events, goal, ledger);
6947
6278
  };
6948
6279
  const runHostLockEntry = async (operation) => {
@@ -6974,6 +6305,9 @@ function createRuntime(agent, config, hostLock = DEFAULT_HOST_LOCK, readGoalStat
6974
6305
  return {
6975
6306
  projection,
6976
6307
  session,
6308
+ get initialActivation() {
6309
+ return readActivation ? activationRead?.status === "bound" ? activationRead.mode : void 0 : config.activation;
6310
+ },
6977
6311
  get lifecycle() {
6978
6312
  return lifecycle;
6979
6313
  },
@@ -7140,6 +6474,8 @@ function apply(ctx, rawConfig = {}, seams = {}) {
7140
6474
  } : configuredHostLock);
7141
6475
  const runtimes = /* @__PURE__ */ new Map();
7142
6476
  const privateLedgerRoot = seams.privateLedgerRoot ?? resolvePrivateLedgerRoot(void 0, process.env.DSH_HOME, homedir());
6477
+ const activationBindingsRoot = seams.activationBindingsRoot ?? resolveActivationBindingsRoot(process.env.DSH_HOME, homedir());
6478
+ const startSources = /* @__PURE__ */ new WeakMap();
7143
6479
  const hostLocks = /* @__PURE__ */ new Map();
7144
6480
  const qualifiedGoalService = (agent) => (hostLocks.get(agent) ?? installedHostLock).goalQualificationFailure ? void 0 : optionalGoalService(ctx, agent);
7145
6481
  const ledgerContext = (agent, fallback = installedHostLock) => ({
@@ -7180,7 +6516,36 @@ function apply(ctx, rawConfig = {}, seams = {}) {
7180
6516
  if (!runtime) {
7181
6517
  const goals = qualifiedGoalService(agent);
7182
6518
  const agentHostLock = refreshAgentHostLock(agent);
7183
- runtime = createRuntime(agent, config, agentHostLock, goals ? () => goals.get(agent) : void 0, () => refreshAgentHostLock(agent), privateLedgerRoot ? () => readPrivateLedger(privateLedgerRoot, ledgerContext(agent, agentHostLock)) : void 0, privateLedgerRoot ? () => initializePrivateLedger(privateLedgerRoot, ledgerContext(agent, agentHostLock)) : void 0);
6519
+ let birth;
6520
+ let initialization;
6521
+ try {
6522
+ birth = sessionBirthIdentity(agent.session.header, agent.session.inheritedEventCount);
6523
+ const qualified = agentHostLock.status === "supported" && ctx.get?.("agents")?.get(agent.id) === agent && ctx.sessions.get?.(agent.session.id) === agent.session;
6524
+ initialization = resolveSessionActivation(activationBindingsRoot, birth, config, startSources.get(agent), qualified);
6525
+ } catch {
6526
+ initialization = {
6527
+ status: "unavailable",
6528
+ reasonCode: "activation_identity_unavailable",
6529
+ key: "identity"
6530
+ };
6531
+ }
6532
+ const readMode = () => {
6533
+ if (!birth) return initialization;
6534
+ try {
6535
+ const fresh = readActivationBinding(activationBindingsRoot, sessionBirthIdentity(agent.session.header, agent.session.inheritedEventCount), config.activationSource === "explicit" ? config.activation : void 0);
6536
+ return fresh.status === "unavailable" && fresh.reasonCode === "activation_mode_unknown" && initialization.status === "unavailable" ? {
6537
+ ...initialization,
6538
+ key: fresh.key
6539
+ } : fresh;
6540
+ } catch {
6541
+ return {
6542
+ status: "unavailable",
6543
+ reasonCode: "activation_identity_unavailable",
6544
+ key: "identity"
6545
+ };
6546
+ }
6547
+ };
6548
+ runtime = createRuntime(agent, config, agentHostLock, goals ? () => goals.get(agent) : void 0, () => refreshAgentHostLock(agent), privateLedgerRoot ? () => readPrivateLedger(privateLedgerRoot, ledgerContext(agent, agentHostLock)) : void 0, privateLedgerRoot ? () => initializePrivateLedger(privateLedgerRoot, ledgerContext(agent, agentHostLock)) : void 0, readMode);
7184
6549
  runtimes.set(agent, runtime);
7185
6550
  created = true;
7186
6551
  }
@@ -7422,6 +6787,13 @@ function apply(ctx, rawConfig = {}, seams = {}) {
7422
6787
  }));
7423
6788
  ownedTools.register(createExternalOperationTool((id, toolAgent) => readExternalOperation(ctx, toolAgent, id), () => evaluateExternalWaitCapability(hostLocks.get(agent) ?? installedHostLock)));
7424
6789
  ownedTools.guard((exec) => {
6790
+ const privateDenial = privateStorageToolDenial(exec.name, exec.arguments, sessionCwd(agent.session) ?? process.cwd(), [activationBindingsRoot, ...privateLedgerRoot ? [privateLedgerRoot] : []]);
6791
+ if (privateDenial) return privateDenial;
6792
+ if (exec.name === "update_goal" && exec.arguments?.action === "complete") {
6793
+ runtime.sync();
6794
+ const modeFailure = runtime.projection.integrityViolations.find((code) => code.startsWith("activation_"));
6795
+ if (modeFailure) return `[${modeFailure}] Session initial activation is unavailable; inspect/adopt its binding before certification.`;
6796
+ }
7425
6797
  if (exec.name === "update_goal" && exec.arguments?.action === "complete" && runtime.projection.enabled) runtime.sync({ revalidateHostLock: true });
7426
6798
  return goalCompletionDenial(runtime.projection, exec.name, exec.arguments);
7427
6799
  });
@@ -7432,6 +6804,7 @@ function apply(ctx, rawConfig = {}, seams = {}) {
7432
6804
  };
7433
6805
  ctx.on("agent/created", ({ agent, source, signal }) => {
7434
6806
  signal?.throwIfAborted();
6807
+ startSources.set(agent, source);
7435
6808
  return attach(agent, source);
7436
6809
  });
7437
6810
  for (const agent of ctx.get?.("agents")?.list() ?? []) attach(agent);
@@ -7446,7 +6819,7 @@ function apply(ctx, rawConfig = {}, seams = {}) {
7446
6819
  const delegated = isDelegatedSession(agent.session);
7447
6820
  let boundaryPending = !runtime.protocolV6Present;
7448
6821
  const firstStep = previewFirstStepInjection({
7449
- activation: config.activation,
6822
+ activation: runtime.initialActivation ?? "opt-in",
7450
6823
  enabled: runtime.projection.enabled,
7451
6824
  boundaryV5Present: runtime.protocolV5Present,
7452
6825
  boundaryV6Present: runtime.protocolV6Present,
@@ -7725,4 +7098,4 @@ async function replayRawV2(input) {
7725
7098
  }
7726
7099
 
7727
7100
  //#endregion
7728
- 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, DESKTOP_IDENTITY_FACTS, DESKTOP_PROFILE_PACKAGE_NAME, DESKTOP_RUNTIME_PACKAGE_NAME, EXPECTED_HOST_PACKAGES, FIRST_STEP_GUIDANCE, GIT_COMMAND_MANIFEST_IDS, GIT_COMMAND_TEMPLATES, GOAL_HOST_PACKAGES, GRANTED_QUALIFICATION, HOST_CAPABILITY_PACKAGE_GROUPS, HOST_COHORTS, HOST_VALIDATED_VERSIONS, HostProfileError, HostTrustError, LATEST_TESTED_HOST_VERSION, LEGACY_QUALIFICATION, MIN_RECOVERY_CHAR_BUDGET, MIN_SUPPORTED_HOST_VERSION, NATIVE_GIT_ROOT_PARENT_OID, 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, RC020_RC1_HOST_PACKAGES, RC020_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, acquireHostTrust, actionCompatible, actionHasCertificationPath, actionVerbMatches, activeRendererModule, admissibleForRemoval, apply, applyUpgradeEligibility, assessmentAction, assessmentOutcomePredicate, auditDesktopInstalledImplementation, 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, evaluateActiveHostLock, evaluateConfiguredHostLock, evaluateExternalWaitCapability, evaluateGraphDerivedHostLock, evaluateHostCapability, evaluateHostLock, evaluateMinimumHostVersion, evaluateToolSurfaceCapability, evidenceAvailabilityReason, evidenceCoverage, evidenceFromPersistedToolResult, evidenceMatchesItem, executeRevalidatedGitEffect, explanationHasActionResidue, extractArtifactPaths, extractMethod, extractOperation, extractTextContent, extractToolSubject, firstStepGuidance, firstStepGuidanceV6, gitCommandMatchesTarget, goalCompletionDenial, governedClauseRestrictsExecution, hasCurrentCertificate, hasDesktopImporterState, hasOrderedCoordination, hasQuestionScope, hasWorkPredicate, hostLockContextFromComposedDump, hostLockRowsFromComposedDump, hostTrustDigest, hostVersionFromPackages, inject, injectActiveProfileHostLock, inspectDesktopTargetGraph, 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, nativeGitParentOidVerified, normalizeClause, observeAssistantOutcome, openItems, opensConditionLead, opensWithDirective, packageRowsFromActiveGraph, packageRowsFromPnpmLock, parseConfirmationMessage, parseGitCommandManifest, parseHostTrust, parseHostVersion, parsePwshCommand, parseShellCommand, partialFailureOf, persistedToolResultStatus, prepareActiveHostTrust, prepareDesktopHostTrust, prepareTargetHostTrust, presentExplanationHead, previewFirstStepInjection, progressFingerprint, projectCoreV2, projectSessionCoreV2, proofCapabilityReport, proofDigest, proofDigestV2, proofEvidenceConstraints, proofHostSurfacesOf, proofOperationMatches, proofV2Rejection, proposeRebind, proposeRebindOutcome, proposeRebindV042, qualificationOfClause, qualifyBoundary, qualifyHostTrust, questionHeadsClause, readActiveHostGraph, readAsarFile, readAsarIndex, readDesktopAppRuntime, readDesktopDependency, readDesktopTargetGraph, rebindAttemptKey, rebindResponse, recoveryDigest, recoveryTitle, registryArchiveFiles, registryArchiveModules, relevantEvidence, removalIsComplete, removalIsPartiallyKnown, renderRecoveryPacket, replayRawV2, replayRebindResult, reportingHeadGoverns, requestedIdentityKey, requestedTargetAuthorizesMutation, requestedTargetMatchesResolved, requiredSubjectsOf, resolveActiveProfileHostLock, resolveDesktopProfileHostLock, resolveInstalledHostLock, restatedContentOf, revalidateDesktopCoreLock, revalidateGitPrestate, rootLocatorFlavor, sanitizeClauseText, sanitizeUrl, satisfiesSupportedHostRange, scopeCoverageDigest, segmentAuthorityBlocks, segmentClauses, selectHostCohort, semanticActionFromCommand, semanticActionFromText, semanticActionOfScope, sessionQuery, sessionQueryV2, sha256, shellReadbackOutcome, snapshotSessionEvents, splitTextFragments, statefulActionsOfScope, supersedeItem, testOutcomePredicate, v6CurrentRootBoundaries, v6TestPredicate, validateActionManifest, validateActionTarget, validateManifest, validateProofManifest, validateProofManifestV2, verbIsNegated, verifiedLinearCommitReadback, verifyComposedHostLockDump, withDurability, writeDesktopRuntimeReceipt };
7101
+ 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, DESKTOP_IDENTITY_FACTS, DESKTOP_PROFILE_PACKAGE_NAME, DESKTOP_RUNTIME_PACKAGE_NAME, EXPECTED_HOST_PACKAGES, FIRST_STEP_GUIDANCE, GIT_COMMAND_MANIFEST_IDS, GIT_COMMAND_TEMPLATES, GOAL_HOST_PACKAGES, GRANTED_QUALIFICATION, HOST_CAPABILITY_PACKAGE_GROUPS, HOST_COHORTS, HOST_VALIDATED_VERSIONS, HostProfileError, HostTrustError, LATEST_TESTED_HOST_VERSION, LEGACY_QUALIFICATION, MIN_RECOVERY_CHAR_BUDGET, MIN_SUPPORTED_HOST_VERSION, NATIVE_GIT_ROOT_PARENT_OID, 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, RC020_RC1_HOST_PACKAGES, RC020_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, __activationBindingInternals, acquireHostTrust, actionCompatible, actionHasCertificationPath, actionVerbMatches, activationBindingPath, activationCanonical, activationDigest, activationJson, activationSelectionPending, activeRendererModule, admissibleForRemoval, adoptActivationReceipt, apply, applyUpgradeEligibility, assessmentAction, assessmentOutcomePredicate, auditDesktopInstalledImplementation, 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, createActivationMigrationReceipt, createActivationSelection, createGitPrestateEnvelope, createProjection, createProofManifest, createProofManifestV2, currentActionBases, currentContractDigest, decideTurnBoundary, decideTurnStopping, decisionBoundaryKey, deriveItemDiagnosis, deriveProjection, digestStrings, effectuateBoundary, environmentDefaultRepositoryTarget, evaluateActiveHostLock, evaluateConfiguredHostLock, evaluateExternalWaitCapability, evaluateGraphDerivedHostLock, evaluateHostCapability, evaluateHostLock, evaluateMinimumHostVersion, evaluateToolSurfaceCapability, evidenceAvailabilityReason, evidenceCoverage, evidenceFromPersistedToolResult, evidenceMatchesItem, executeRevalidatedGitEffect, explanationHasActionResidue, extractArtifactPaths, extractMethod, extractOperation, extractTextContent, extractToolSubject, firstStepGuidance, firstStepGuidanceV6, gitCommandMatchesTarget, goalCompletionDenial, governedClauseRestrictsExecution, hasCurrentCertificate, hasDesktopImporterState, hasOrderedCoordination, hasQuestionScope, hasWorkPredicate, hostLockContextFromComposedDump, hostLockRowsFromComposedDump, hostTrustDigest, hostVersionFromPackages, inject, injectActiveProfileHostLock, inspectActivationInventory, inspectDesktopTargetGraph, inspectTargetHostGraph, interpretClause, interpretMessage, introducesActionClause, isCurrentAcceptedBoundary, isDeterministicCheck, isExecutableItem, isExplanationScope, isFrozenV042RebindResponse, isInformationalFragment, isInformationalMessage, isOpenObligation, isQuestionScopeNeedingReview, isRestatement, isRootPauseRequest, isRunExecutable, isSelectedActivationReceipt, isStatefulAction, isVerifyingCapability, isWholeTaskCompletionClaim, itemDiagnosis, itemHoldsExecutionAuthority, kindOfScope, latestAssistantText, latestRootInstruction, legacyQuestionReadingIsInformational, legacyRecordsNeedingReview, lifecyclePhase, maskCodeSpans, maskQuotedSpans, memoizedAsarFile, memoizedAsarIndex, name, namedActions, nativeFileTwoRole, nativeGitParentOidVerified, normalizeClause, observeAssistantOutcome, openItems, opensConditionLead, opensWithDirective, packageRowsFromActiveGraph, packageRowsFromPnpmLock, parseConfirmationMessage, parseGitCommandManifest, parseHostTrust, parseHostVersion, parsePwshCommand, parseShellCommand, partialFailureOf, persistedToolResultStatus, prepareActivationMigration, prepareActiveHostTrust, prepareDesktopHostTrust, prepareSelectedActivationMigration, prepareTargetHostTrust, presentExplanationHead, previewFirstStepInjection, privateStorageToolDenial, progressFingerprint, projectCoreV2, projectSessionCoreV2, proofCapabilityReport, proofDigest, proofDigestV2, proofEvidenceConstraints, proofHostSurfacesOf, proofOperationMatches, proofV2Rejection, proposeRebind, proposeRebindOutcome, proposeRebindV042, qualificationOfClause, qualifyBoundary, qualifyHostTrust, questionHeadsClause, readActivationBinding, readActivationMigrationReceipt, readActiveHostGraph, readAsarFile, readAsarIndex, readDesktopAppRuntime, readDesktopDependency, readDesktopTargetGraph, rebindAttemptKey, rebindResponse, recoveryDigest, recoveryTitle, registryArchiveFiles, registryArchiveModules, relevantEvidence, removalIsComplete, removalIsPartiallyKnown, renderRecoveryPacket, replayRawV2, replayRebindResult, reportingHeadGoverns, requestedIdentityKey, requestedTargetAuthorizesMutation, requestedTargetMatchesResolved, requiredSubjectsOf, resolveActivationBindingsRoot, resolveActiveProfileHostLock, resolveDesktopProfileHostLock, resolveInstalledHostLock, resolveSessionActivation, restatedContentOf, revalidateDesktopCoreLock, revalidateGitPrestate, rootLocatorFlavor, sanitizeClauseText, sanitizeUrl, satisfiesSupportedHostRange, scanActivationInventory, scopeCoverageDigest, segmentAuthorityBlocks, segmentClauses, selectHostCohort, selectedActivationInventory, semanticActionFromCommand, semanticActionFromText, semanticActionOfScope, sessionBirthIdentity, sessionQuery, sessionQueryV2, sha256, shellReadbackOutcome, snapshotSessionEvents, splitTextFragments, statefulActionsOfScope, supersedeItem, testOutcomePredicate, v6CurrentRootBoundaries, v6TestPredicate, validateActionManifest, validateActionTarget, validateActivationBinding, validateActivationInventorySnapshot, validateActivationMigrationReceipt, validateActivationSelection, validateManifest, validateProofManifest, validateProofManifestV2, verbIsNegated, verifiedLinearCommitReadback, verifyComposedHostLockDump, verifyMigrationInventory, verifySelectedMigrationInventory, withDurability, writeActivationBinding, writeDesktopRuntimeReceipt };