@lmzhen/dsh-evolution-core 0.60.0 → 0.61.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.
@@ -1,5 +1,5 @@
1
- import { n as MutationAuthority } from "./mutation-authority-C3RYyiaT.js";
2
- import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
1
+ import { n as MutationAuthority } from "./mutation-authority-Dkt4PVsM.js";
2
+ import { t as evolutionHome } from "./state-store-BLchnUkV.js";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  //#region lib/types/authority-plugin.js
5
5
  const Config = z.object({ keyedSkillLocks: z.boolean().default(false) });
package/lib/extract.js CHANGED
@@ -2,7 +2,7 @@ import { p as isPresent } from "./io-DT4-MXLr.js";
2
2
  import { i as DEFAULT_SKILL_LIMITS } from "./limits-CO4JGSJL.js";
3
3
  import { a as measureUnit } from "./text-metrics-CyJhxWBs.js";
4
4
  import { p as parseFrontmatter, r as contentHash } from "./mutations-JKFlfhSO.js";
5
- import { C as EXTRACT_PROMPT_VERSION, S as EXTRACT_PROMPT_V1, T as ownerCandidatesFromSummaries, _ as readProposalReport, b as proposalFromPlan, d as nearDuplicateSummaries, m as readExternalSupport, v as readProposalReports, w as findOwnerCandidate, x as EXTRACT_PROMPT_HASH, y as writeProposalReport } from "./quality-C0ri2SgY.js";
5
+ import { C as EXTRACT_PROMPT_VERSION, S as EXTRACT_PROMPT_V1, T as ownerCandidatesFromSummaries, _ as readProposalReport, b as proposalFromPlan, d as nearDuplicateSummaries, m as readExternalSupport, v as readProposalReports, w as findOwnerCandidate, x as EXTRACT_PROMPT_HASH, y as writeProposalReport } from "./quality-DFWvykek.js";
6
6
  import { n as projectExtractBodies, t as planExtract } from "./extract-plan-CP__XlEs.js";
7
7
  import { dirname, join } from "node:path";
8
8
  //#region lib/types/extract-request.js
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { S as reportTime, _ as probeMtime, a as isProcessAlive, b as probeText, c as transactIo, d as isAbsent, f as isMissingPath, g as probeList, h as probeAbsent, i as isCommittedWarning, l as writeDurableTmp, m as isUnknown, n as atomicWriteFiles, o as nodeEvolutionIo, p as isPresent, r as evolutionIoAdapter, s as renameWithRetry, t as TransactionNotInvokedError, u as declaredReportStamp, v as probePresent, x as probeUnknown, y as probeReason } from "./io-DT4-MXLr.js";
2
- import { a as DEFAULT_LEASE_TTL_MS, c as HomeFence, d as AuthorityOrderError, f as AuthorityReentryError, g as leaseAsTreeLock, h as authorityHolder, i as mutationLockFrom, l as HomeFenceError, m as TargetLockSet, n as MutationAuthority, o as LeaseStore, p as HomeAuthority, r as TargetMutationLock, s as leaseFile, t as HybridMutationLock, u as AuthorityBusyError } from "./mutation-authority-C3RYyiaT.js";
2
+ import { _ as TargetLockSet, a as liveHomeFence, c as DEFAULT_LEASE_TTL_MS, d as HomeFence, f as HomeFenceError, g as HomeAuthority, h as AuthorityReentryError, i as homeFenceFrom, l as LeaseStore, m as AuthorityOrderError, n as MutationAuthority, o as mutationAuthorityFrom, p as AuthorityBusyError, r as TargetMutationLock, s as mutationLockFrom, t as HybridMutationLock, u as leaseFile, v as authorityHolder, y as leaseAsTreeLock } from "./mutation-authority-Dkt4PVsM.js";
3
3
  import { a as isFileShapedPath, i as KEEP_LINE_RE, n as DEFAULT_CITATION_REF_BUDGET, o as resolveCitations, r as HOOK_LINE_RE, s as scanBodyHooks, t as CITATION_SUPPORT_DIRS } from "./citations-CZKTUGQF.js";
4
4
  import { $ as SUPPORT_SPRAWL_FILES, A as DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, B as MAX_SKILL_CONTENT_CHARS, C as DEFAULT_REVIEW_TIMEOUT_MS, D as DEFAULT_SKILL_VERSION_KEEP, E as DEFAULT_SKILL_REVIEW_TRIGGER, F as DEFAULT_USER_TOKENS, G as MEMORY_GUIDANCE_SECTION_ORDER, H as MAX_SKILL_NAME_LENGTH, I as ENTRY_DELIMITER, J as REVIEW_TEXT_PREVIEW_GRAPHEMES, K as MERGE_BODY_PREVIEW_BYTES, L as EVOLUTION_WRITE_TOOLS, M as DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, N as DEFAULT_THREAT_MAX_SCAN_CHARS, O as DEFAULT_SOFT_BODY_TOKENS, P as DEFAULT_USER_CHAR_LIMIT, Q as SUPPORT_DIRS, R as FORBIDDEN_CONTROL_KEYS, S as DEFAULT_REVIEW_SKILL_INTERVAL, T as DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, U as MAX_TIMER_DELAY_MS, V as MAX_SKILL_FILE_BYTES, W as MEMORY_ENTRY_PREVIEW_GRAPHEMES, X as SKILL_ACTION_REQUIRED_FIELDS, Y as SKILLS_GUIDANCE_SECTION_ORDER, Z as SKILL_NAME_RE, _ as DEFAULT_MEMORY_CHAR_LIMIT, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, b as DEFAULT_PROBE_TIMEOUT_MS, c as AUTHORING_DESCRIPTION_BAR, d as DEFAULT_ARCHIVE_AFTER_DAYS, et as TEXT_DIFF_MAX_GRAPHEMES, f as DEFAULT_CONSOLIDATION_FAILURES, g as DEFAULT_CURATOR_REVIEW_MAX_TOKENS, h as DEFAULT_CURATOR_MODEL, i as DEFAULT_SKILL_LIMITS, j as DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, k as DEFAULT_STALE_AFTER_DAYS, l as AUTHORING_SPLIT_LINE_CHARS, m as DEFAULT_CURATOR_INTERVAL_HOURS, n as DEFAULT_CITATION_POLICY, nt as VERSION_BODY_PREVIEW_GRAPHEMES, o as POLICY_STAGE_DEFAULTS, p as DEFAULT_CURATOR_BOOT_GRACE_SECONDS, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, tt as UPSTREAM_LIMIT_CHARS_PER_TOKEN, u as CONTENT_SPLIT_HINT, v as DEFAULT_MEMORY_TOKENS, w as DEFAULT_SKILL_CONTENT_CHARS, x as DEFAULT_REVIEW_MEMORY_INTERVAL, y as DEFAULT_MIN_IDLE_HOURS, z as MAX_DESCRIPTION_LENGTH } from "./limits-CO4JGSJL.js";
5
5
  import { _ as scopedPackageName, d as RESTRICTED_TOOLS_ROW_ID, f as RESTRICTOR_MODULE, g as scopeOfNearestManifest, l as MAINTAINER_PRESET_ID, p as REVIEWER_PRESET_ID, s as EVOLUTION_PRESET_IDS, u as RESTRICTED_PRESET_DISPLAY } from "./ensure-DTCuxAxR.js";
@@ -10,8 +10,8 @@ import { a as measureUnit, i as measureText, n as conservativeTokenEstimator, o
10
10
  import { A as h2Sections, C as saveUsage, D as usageObserved, E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, M as externalRefs, N as supportRefs, O as selectSections, P as applyReferenceRewrite, S as saveSuppressedNames, T as updateSuppressedNames, _ as loadUsage, a as applyCuratorMetaFields, b as normalizeUsageRecord, c as bumpUse, d as emptyRecord, f as foldCuratorFields, g as loadSuppressedNames, h as latestActivityAt, i as applyCuratorLifecycleFields, j as readingStats, k as displayBodyOf, l as bumpView, m as idleDays, n as SUPPRESSED_FILE_VERSION, o as bumpPatch, p as getRecord, r as VIEW_WINDOW_DAYS, s as bumpSupportRead, t as MAX_SUPPORT_READ_PATHS, u as daysSinceIso, v as markAgentCreated, w as suppressedFile, x as recentViewCount, y as mutateUsage } from "./usage-BO4Zj_zB.js";
11
11
  import { n as isRecord, t as asRecord } from "./guards-3f02mnf2.js";
12
12
  import { a as mutationsFile, i as loadMutations, n as MUTATIONS_FILE_VERSION, o as recordMutation, r as contentHash, t as DEFAULT_MUTATION_CAP } from "./mutations-JKFlfhSO.js";
13
- import { T as ownerCandidatesFromSummaries, _ as readProposalReport, a as SUMMARY_DUPLICATE_HINT_THRESHOLD, b as proposalFromPlan, c as computePrefixClusters, d as nearDuplicateSummaries, f as projectionText, g as proposalReportName, h as proposalReportDir, i as QUALITY_WEIGHTS, l as computeQualityScores, m as readExternalSupport, n as DEDUP_SIMILARITY_THRESHOLD, o as affinity, p as vocabulary, r as LOW_QUALITY_THRESHOLD, s as computeDedupGroups, t as DEDUP_MAX_PAIR_COMPARISONS, u as identity, v as readProposalReports, w as findOwnerCandidate, y as writeProposalReport } from "./quality-C0ri2SgY.js";
14
- import { n as evolutionRoot, t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
13
+ import { T as ownerCandidatesFromSummaries, _ as readProposalReport, a as SUMMARY_DUPLICATE_HINT_THRESHOLD, b as proposalFromPlan, c as computePrefixClusters, d as nearDuplicateSummaries, f as projectionText, g as proposalReportName, h as proposalReportDir, i as QUALITY_WEIGHTS, l as computeQualityScores, m as readExternalSupport, n as DEDUP_SIMILARITY_THRESHOLD, o as affinity, p as vocabulary, r as LOW_QUALITY_THRESHOLD, s as computeDedupGroups, t as DEDUP_MAX_PAIR_COMPARISONS, u as identity, v as readProposalReports, w as findOwnerCandidate, y as writeProposalReport } from "./quality-DFWvykek.js";
14
+ import { n as evolutionRoot, t as evolutionHome } from "./state-store-BLchnUkV.js";
15
15
  import "./skill-history-BOZ4HCDB.js";
16
16
  import { HOST_ROUTES, MAX_REQUEST_BODY_BYTES, hostSurface, json, methodNotAllowed, readJsonObject, registerHostRoutes } from "./http-routes.js";
17
17
  import { w as allowRowCollisions } from "./composition-BSqh70z_.js";
@@ -2451,7 +2451,8 @@ function newRunRegistry(options) {
2451
2451
  const run = async () => {
2452
2452
  await transactIo(options.io, path, task);
2453
2453
  };
2454
- if (options.fence !== void 0) await options.fence.run(run);
2454
+ const fence = options.resolveFence?.() ?? options.fence;
2455
+ if (fence !== void 0) await fence.run(run);
2455
2456
  else await run();
2456
2457
  };
2457
2458
  /** Rows THIS process started: its memory is the only truth for them. */
@@ -5551,4 +5552,4 @@ function classifySessionEvent(event) {
5551
5552
  return MODEL_EVENT_TYPES.has(type) ? "model" : "unknown";
5552
5553
  }
5553
5554
  //#endregion
5554
- export { AUTHORING_DESCRIPTION_BAR, AUTHORING_SPLIT_LINE_CHARS, AuthorityBusyError, AuthorityOrderError, AuthorityReentryError, CITATION_SUPPORT_DIRS, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CONTENT_SPLIT_HINT, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEDUP_MAX_PAIR_COMPARISONS, DEDUP_SIMILARITY_THRESHOLD, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_CITATION_REF_BUDGET, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_BOOT_GRACE_SECONDS, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_CURATOR_MODEL, DEFAULT_CURATOR_REVIEW_MAX_TOKENS, DEFAULT_LEASE_TTL_MS, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MEMORY_TOKENS, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_PROBE_TIMEOUT_MS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_RUN_RECORDS, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_SOFT_BODY_TOKENS, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_SUPPORT_READ_TOOL_NAMES, DEFAULT_THREAT_MAX_SCAN_CHARS, DEFAULT_USER_CHAR_LIMIT, DEFAULT_USER_TOKENS, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, DISPATCH_EVENT_TYPES, DRIFT_MAX_LINE_CHARS, DRIFT_SIGNALS_VERSION, DRIFT_SIGNAL_NOUNS, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_ARCHIVE_PREFIX, EVENT_LOG_RETAIN_ARCHIVES, EVENT_LOG_ROTATE_AT, EVENT_LOG_VERSION, EVOLUTION_ERRORS, EVOLUTION_PRESET_IDS, EVOLUTION_WRITE_TOOLS, EvolutionGateSet, FAMILY_SESSION_TOOL_NAMES, FORBIDDEN_CONTROL_KEYS, FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, GOVERNANCE_PROMPT_TEMPLATE, HOOK_LINE_RE, HOST_LOCALES, HOST_ROUTES, HomeAuthority, HomeFence, HomeFenceError, HybridMutationLock, INJECT_COMBINED_REVIEW_PROMPT, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, INJECT_MEMORY_REVIEW_PROMPT, INJECT_SKILL_REVIEW_PROMPT, INSTANCE_KEYS, KEEP_LINE_RE, LONG_RUNS, LOW_QUALITY_THRESHOLD, LeaseStore, MAINTAINER_PRESET_ID, MAINTAIN_OUTPUT_INSTRUCTION, MAINTAIN_PROMPT, MAX_DESCRIPTION_LENGTH, MAX_REQUEST_BODY_BYTES, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MAX_SUPPORT_READ_PATHS, MAX_TIMER_DELAY_MS, MEMORY_ENTRY_PREVIEW_GRAPHEMES, MEMORY_GUIDANCE_SECTION_ORDER, MEMORY_REVIEW_PROMPT, MEMORY_TOKENS, MERGE_BODY_PREVIEW_BYTES, MODEL_SESSION_EVENT_TYPES, MUTATIONS_FILE_VERSION, MemoryStore, MutationAuthority, NAMESPACE_MIGRATIONS, NATIVE_CALL_EVENT, NATIVE_RESULT_EVENT, PARAM_ALIASES, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PARAM_NAMESPACES, PATTERN_OVERLAP, PLATFORM_LINE, PLATFORM_SERVICE_PROBES, POLICY_STAGE_DEFAULTS, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROMPT_BUNDLE_VERSION, PROTECTED_BUILTIN_SKILLS, PTC_DISPATCH_EVENT, PTC_DISPATCH_START_EVENT, QUALITY_WEIGHTS, RESTRICTED_PRESET_DISPLAY, RESTRICTED_TOOLS_ROW_ID, RESTRICTOR_MODULE, REVIEWER_PRESET_ID, REVIEW_TEXT_PREVIEW_GRAPHEMES, RUNS_SCHEMA_VERSION, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, SKILL_ACTION_REQUIRED_FIELDS, SKILL_NAME_RE, SKILL_REVIEW_PROMPT, SOFT_BODY_TOKENS, STORE_LEDGER, SUMMARY_DUPLICATE_HINT_THRESHOLD, SUPPORT_DIRS, SUPPORT_SPRAWL_FILES, SUPPRESSED_FILE_VERSION, TEXT_BUDGETS, TEXT_DIFF_MAX_GRAPHEMES, THREAT_EXEMPTION_HINT, TargetLockSet, TargetMutationLock, ToolDispatchNormalizer, ToolDispatchPayloadError, TransactionNotInvokedError, UPSTREAM_LIMIT_CHARS_PER_TOKEN, USER_TOKENS, VERSION_BODY_PREVIEW_GRAPHEMES, VIEW_WINDOW_DAYS, abortLink, absentHostServices, advanceReview, affinity, allowRowCollisions, appendEvolutionEvent, applyCuratorLifecycleFields, applyCuratorMetaFields, applyNamespaceMigration, applyReferenceRewrite, asRecord, assertDispatchPayload, atomicWriteFiles, authorityFrom, authorityHolder, backupsReachability, buildCuratorRunReport, buildHealthBaseline, buildLearnPrompt, bumpPatch, bumpSupportRead, bumpUse, bumpView, callingScope, claimInstance, clampOnce, clampedNumber, classifyNamespaceMigration, classifySessionEvent, clearReviewChannel, codePointCount, collectReadSkillNames, collectReadSupportFiles, compareTextBudget, computeDedupGroups, computeDriftSignals, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, conservativeTokenEstimator, contentHash, createGateSet, createSubagentKernel as createSubagentChannel, createSubagentKernel, createSubagentRun, currentReviewContext, daysSinceIso, declaredReportStamp, describeReferenceRewrite, dispatchKeyOf, dispatchPathOf, dispatchStepOf, displayBodyOf, duplicateHeadings, emptyRecord, errorText, errorTextIn, evaluateThreat, eventsFile, evidenceKindIndex, evolutionActivityProjection, evolutionEventPayloadIssue, evolutionEvidenceProjection, evolutionHome, evolutionIoAdapter, evolutionProjectionHistoryProjection, evolutionReadsProjection, evolutionRoot, evolutionSignalsProjection, externalRefs, findDriftSignal, findOwnerCandidate, foldCuratorFields, foldToolDispatches, foldTurnEvent, foldTurnEvents, fuzzyPatch, getRecord, graphemeCount, h2Sections, historyReachability, hostSurface, identity, idleDays, initialTurnFold, instanceClaimKey, instanceHolder, isAbsent, isBookkeepingFrame, isCommittedWarning, isDeprecatedParamId, isFileShapedPath, isMissingPath, isPresent, isProcessAlive, isProjectableSession, isRecord, isReviewChannelSession, isSkillReadToolName, isSkillToolName, isUnknown, json, latestActivityAt, leaseAsTreeLock, leaseFile, lifecycleCandidate, listEventArchives, liveBool, liveNumber, loadMutations, loadSuppressedNames, loadUsage, makeSerialQueue, markAgentCreated, markReviewChannel, measureText, measureUnit, memoryRoot, methodNotAllowed, missingSupportPointers, mutateUsage, mutationLockFrom, mutationsFile, narrowNameMatches, nearDuplicateSummaries, newRunRegistry, nodeEvolutionIo, normalizeUsageRecord, observeEvent, overlongLines, ownerCandidatesFromSummaries, paramRowId, paramSettingsId, parseCuratorNominations, parseEvolutionEvents, payloadText, persistedWriteSites, pickWithPolicy, planNamespaceMigration, planReferenceRewrite, planRehoming, policyStageLimits, probeAbsent, probeChannelState, probeList, probeMtime, probePresent, probeReason, probeText, probeUnknown, projectionText, proposalFromPlan, proposalReportDir, proposalReportName, protectedSkillNamesOf, readDispatchSignal, readEvolutionEvents, readEvolutionTimeline, readExternalSupport, readJsonObject, readNumberParam, readParam, readProposalReport, readProposalReports, readingStats, recentViewCount, recordMutation, recordReviewRead, redactSecrets, referencedBlobs, registerHostRoutes, releaseInstance, renameWithRetry, renderCuratorReportMarkdown, reportTime, reportsReachability, reportsSweepLockTarget, resolveCitations, resolveParamId, retainEventArchives, retirementReport, reviewPrompt, runWriteGates, runsFile, saveSuppressedNames, saveUsage, scanBodyHooks, scanContentThreats, scanMemoryThreats, scanThreats, scopeOfNearestManifest, scopedPackageName, scopedProbeReport, selectSections, sessionAudited, sessionEvidenceIndex, sessionLastEventTime, sessionReadNames, sessionSeesFamilyTools, sessionTurnSignals, skillReadNameOf, skillWriteGateContext, supportFileReadFromPath, supportFileReadOf, supportRefs, suppressedFile, sweepReports, sweepReviewChannelSessions, textOfValue, transactIo, trimPatternBoundaries, truncateGraphemes, unhookedSupportPointers, unwrapLive, updateSuppressedNames, usageFile, usageObserved, userSetKeys, utf8ByteLength, verifyPromptBundle, vocabulary, waitForSubagentEnd, withReviewContext, withTreeWrite, writeDurableTmp, writeProposalReport };
5555
+ export { AUTHORING_DESCRIPTION_BAR, AUTHORING_SPLIT_LINE_CHARS, AuthorityBusyError, AuthorityOrderError, AuthorityReentryError, CITATION_SUPPORT_DIRS, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CONTENT_SPLIT_HINT, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEDUP_MAX_PAIR_COMPARISONS, DEDUP_SIMILARITY_THRESHOLD, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_CITATION_REF_BUDGET, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_BOOT_GRACE_SECONDS, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_CURATOR_MODEL, DEFAULT_CURATOR_REVIEW_MAX_TOKENS, DEFAULT_LEASE_TTL_MS, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MEMORY_TOKENS, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_PROBE_TIMEOUT_MS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_RUN_RECORDS, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_SOFT_BODY_TOKENS, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_SUPPORT_READ_TOOL_NAMES, DEFAULT_THREAT_MAX_SCAN_CHARS, DEFAULT_USER_CHAR_LIMIT, DEFAULT_USER_TOKENS, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, DISPATCH_EVENT_TYPES, DRIFT_MAX_LINE_CHARS, DRIFT_SIGNALS_VERSION, DRIFT_SIGNAL_NOUNS, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_ARCHIVE_PREFIX, EVENT_LOG_RETAIN_ARCHIVES, EVENT_LOG_ROTATE_AT, EVENT_LOG_VERSION, EVOLUTION_ERRORS, EVOLUTION_PRESET_IDS, EVOLUTION_WRITE_TOOLS, EvolutionGateSet, FAMILY_SESSION_TOOL_NAMES, FORBIDDEN_CONTROL_KEYS, FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, GOVERNANCE_PROMPT_TEMPLATE, HOOK_LINE_RE, HOST_LOCALES, HOST_ROUTES, HomeAuthority, HomeFence, HomeFenceError, HybridMutationLock, INJECT_COMBINED_REVIEW_PROMPT, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, INJECT_MEMORY_REVIEW_PROMPT, INJECT_SKILL_REVIEW_PROMPT, INSTANCE_KEYS, KEEP_LINE_RE, LONG_RUNS, LOW_QUALITY_THRESHOLD, LeaseStore, MAINTAINER_PRESET_ID, MAINTAIN_OUTPUT_INSTRUCTION, MAINTAIN_PROMPT, MAX_DESCRIPTION_LENGTH, MAX_REQUEST_BODY_BYTES, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MAX_SUPPORT_READ_PATHS, MAX_TIMER_DELAY_MS, MEMORY_ENTRY_PREVIEW_GRAPHEMES, MEMORY_GUIDANCE_SECTION_ORDER, MEMORY_REVIEW_PROMPT, MEMORY_TOKENS, MERGE_BODY_PREVIEW_BYTES, MODEL_SESSION_EVENT_TYPES, MUTATIONS_FILE_VERSION, MemoryStore, MutationAuthority, NAMESPACE_MIGRATIONS, NATIVE_CALL_EVENT, NATIVE_RESULT_EVENT, PARAM_ALIASES, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PARAM_NAMESPACES, PATTERN_OVERLAP, PLATFORM_LINE, PLATFORM_SERVICE_PROBES, POLICY_STAGE_DEFAULTS, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROMPT_BUNDLE_VERSION, PROTECTED_BUILTIN_SKILLS, PTC_DISPATCH_EVENT, PTC_DISPATCH_START_EVENT, QUALITY_WEIGHTS, RESTRICTED_PRESET_DISPLAY, RESTRICTED_TOOLS_ROW_ID, RESTRICTOR_MODULE, REVIEWER_PRESET_ID, REVIEW_TEXT_PREVIEW_GRAPHEMES, RUNS_SCHEMA_VERSION, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, SKILL_ACTION_REQUIRED_FIELDS, SKILL_NAME_RE, SKILL_REVIEW_PROMPT, SOFT_BODY_TOKENS, STORE_LEDGER, SUMMARY_DUPLICATE_HINT_THRESHOLD, SUPPORT_DIRS, SUPPORT_SPRAWL_FILES, SUPPRESSED_FILE_VERSION, TEXT_BUDGETS, TEXT_DIFF_MAX_GRAPHEMES, THREAT_EXEMPTION_HINT, TargetLockSet, TargetMutationLock, ToolDispatchNormalizer, ToolDispatchPayloadError, TransactionNotInvokedError, UPSTREAM_LIMIT_CHARS_PER_TOKEN, USER_TOKENS, VERSION_BODY_PREVIEW_GRAPHEMES, VIEW_WINDOW_DAYS, abortLink, absentHostServices, advanceReview, affinity, allowRowCollisions, appendEvolutionEvent, applyCuratorLifecycleFields, applyCuratorMetaFields, applyNamespaceMigration, applyReferenceRewrite, asRecord, assertDispatchPayload, atomicWriteFiles, authorityFrom, authorityHolder, backupsReachability, buildCuratorRunReport, buildHealthBaseline, buildLearnPrompt, bumpPatch, bumpSupportRead, bumpUse, bumpView, callingScope, claimInstance, clampOnce, clampedNumber, classifyNamespaceMigration, classifySessionEvent, clearReviewChannel, codePointCount, collectReadSkillNames, collectReadSupportFiles, compareTextBudget, computeDedupGroups, computeDriftSignals, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, conservativeTokenEstimator, contentHash, createGateSet, createSubagentKernel as createSubagentChannel, createSubagentKernel, createSubagentRun, currentReviewContext, daysSinceIso, declaredReportStamp, describeReferenceRewrite, dispatchKeyOf, dispatchPathOf, dispatchStepOf, displayBodyOf, duplicateHeadings, emptyRecord, errorText, errorTextIn, evaluateThreat, eventsFile, evidenceKindIndex, evolutionActivityProjection, evolutionEventPayloadIssue, evolutionEvidenceProjection, evolutionHome, evolutionIoAdapter, evolutionProjectionHistoryProjection, evolutionReadsProjection, evolutionRoot, evolutionSignalsProjection, externalRefs, findDriftSignal, findOwnerCandidate, foldCuratorFields, foldToolDispatches, foldTurnEvent, foldTurnEvents, fuzzyPatch, getRecord, graphemeCount, h2Sections, historyReachability, homeFenceFrom, hostSurface, identity, idleDays, initialTurnFold, instanceClaimKey, instanceHolder, isAbsent, isBookkeepingFrame, isCommittedWarning, isDeprecatedParamId, isFileShapedPath, isMissingPath, isPresent, isProcessAlive, isProjectableSession, isRecord, isReviewChannelSession, isSkillReadToolName, isSkillToolName, isUnknown, json, latestActivityAt, leaseAsTreeLock, leaseFile, lifecycleCandidate, listEventArchives, liveBool, liveHomeFence, liveNumber, loadMutations, loadSuppressedNames, loadUsage, makeSerialQueue, markAgentCreated, markReviewChannel, measureText, measureUnit, memoryRoot, methodNotAllowed, missingSupportPointers, mutateUsage, mutationAuthorityFrom, mutationLockFrom, mutationsFile, narrowNameMatches, nearDuplicateSummaries, newRunRegistry, nodeEvolutionIo, normalizeUsageRecord, observeEvent, overlongLines, ownerCandidatesFromSummaries, paramRowId, paramSettingsId, parseCuratorNominations, parseEvolutionEvents, payloadText, persistedWriteSites, pickWithPolicy, planNamespaceMigration, planReferenceRewrite, planRehoming, policyStageLimits, probeAbsent, probeChannelState, probeList, probeMtime, probePresent, probeReason, probeText, probeUnknown, projectionText, proposalFromPlan, proposalReportDir, proposalReportName, protectedSkillNamesOf, readDispatchSignal, readEvolutionEvents, readEvolutionTimeline, readExternalSupport, readJsonObject, readNumberParam, readParam, readProposalReport, readProposalReports, readingStats, recentViewCount, recordMutation, recordReviewRead, redactSecrets, referencedBlobs, registerHostRoutes, releaseInstance, renameWithRetry, renderCuratorReportMarkdown, reportTime, reportsReachability, reportsSweepLockTarget, resolveCitations, resolveParamId, retainEventArchives, retirementReport, reviewPrompt, runWriteGates, runsFile, saveSuppressedNames, saveUsage, scanBodyHooks, scanContentThreats, scanMemoryThreats, scanThreats, scopeOfNearestManifest, scopedPackageName, scopedProbeReport, selectSections, sessionAudited, sessionEvidenceIndex, sessionLastEventTime, sessionReadNames, sessionSeesFamilyTools, sessionTurnSignals, skillReadNameOf, skillWriteGateContext, supportFileReadFromPath, supportFileReadOf, supportRefs, suppressedFile, sweepReports, sweepReviewChannelSessions, textOfValue, transactIo, trimPatternBoundaries, truncateGraphemes, unhookedSupportPointers, unwrapLive, updateSuppressedNames, usageFile, usageObserved, userSetKeys, utf8ByteLength, verifyPromptBundle, vocabulary, waitForSubagentEnd, withReviewContext, withTreeWrite, writeDurableTmp, writeProposalReport };
@@ -722,9 +722,46 @@ var HybridMutationLock = class {
722
722
  return await this.keyedLock.repair();
723
723
  }
724
724
  };
725
- function mutationLockFrom(ctx) {
725
+ /** Resolve the authority now; callers that live past one apply must re-read this. */
726
+ function mutationAuthorityFrom(ctx) {
726
727
  if (ctx?.get === void 0) return void 0;
727
- return ctx.get("evolutionMutationAuthority")?.mutationLock;
728
+ return ctx.get("evolutionMutationAuthority");
729
+ }
730
+ function mutationLockFrom(ctx) {
731
+ return mutationAuthorityFrom(ctx)?.mutationLock;
732
+ }
733
+ function homeFenceFrom(ctx) {
734
+ return mutationAuthorityFrom(ctx)?.homeFence;
735
+ }
736
+ /** A stable HomeFence whose target is re-resolved on every use; HMR/late provide heal. */
737
+ var LiveHomeFence = class extends HomeFence {
738
+ liveCtx;
739
+ homePath;
740
+ fallback;
741
+ constructor(liveCtx, homePath) {
742
+ super({ home: homePath });
743
+ this.liveCtx = liveCtx;
744
+ this.homePath = homePath;
745
+ }
746
+ current() {
747
+ return homeFenceFrom(this.liveCtx) ?? (this.fallback ??= new HomeFence({ home: this.homePath }));
748
+ }
749
+ get releaseFailure() {
750
+ return this.current().releaseFailure;
751
+ }
752
+ holdsTree() {
753
+ return this.current().holdsTree();
754
+ }
755
+ async run(body) {
756
+ return await this.current().run(body);
757
+ }
758
+ async acquire() {
759
+ return await this.current().acquire();
760
+ }
761
+ };
762
+ /** A stable HomeFence whose target is re-resolved on every use; HMR/late provide heal. */
763
+ function liveHomeFence(ctx, home) {
764
+ return new LiveHomeFence(ctx, home);
728
765
  }
729
766
  //#endregion
730
- export { DEFAULT_LEASE_TTL_MS as a, HomeFence as c, AuthorityOrderError as d, AuthorityReentryError as f, leaseAsTreeLock as g, authorityHolder as h, mutationLockFrom as i, HomeFenceError as l, TargetLockSet as m, MutationAuthority as n, LeaseStore as o, HomeAuthority as p, TargetMutationLock as r, leaseFile as s, HybridMutationLock as t, AuthorityBusyError as u };
767
+ export { TargetLockSet as _, liveHomeFence as a, DEFAULT_LEASE_TTL_MS as c, HomeFence as d, HomeFenceError as f, HomeAuthority as g, AuthorityReentryError as h, homeFenceFrom as i, LeaseStore as l, AuthorityOrderError as m, MutationAuthority as n, mutationAuthorityFrom as o, AuthorityBusyError as p, TargetMutationLock as r, mutationLockFrom as s, HybridMutationLock as t, leaseFile as u, authorityHolder as v, leaseAsTreeLock as y };
@@ -397,6 +397,7 @@ var UnitKernel = class {
397
397
  targetKeyResolver;
398
398
  journal;
399
399
  snapshots;
400
+ preparedStates = /* @__PURE__ */ new WeakMap();
400
401
  claim;
401
402
  claimRunId;
402
403
  hooks;
@@ -478,7 +479,12 @@ var UnitKernel = class {
478
479
  };
479
480
  }
480
481
  let claim;
482
+ let handle;
481
483
  const release = async () => {
484
+ if (handle !== void 0) {
485
+ if (this.preparedStates.get(handle) === "released") return;
486
+ this.preparedStates.set(handle, "released");
487
+ }
482
488
  await claim?.release().catch(() => {});
483
489
  await lease.release();
484
490
  };
@@ -572,7 +578,7 @@ var UnitKernel = class {
572
578
  warnings.push(error instanceof Error ? error.message : String(error));
573
579
  }
574
580
  };
575
- return {
581
+ handle = {
576
582
  kind: "prepared",
577
583
  unitId,
578
584
  request,
@@ -585,9 +591,23 @@ var UnitKernel = class {
585
591
  bestEffort,
586
592
  release
587
593
  };
594
+ this.preparedStates.set(handle, "prepared");
595
+ return handle;
588
596
  }
589
597
  /** Phase 2: the only durable write phase. Releases the prepare lease in all paths. */
590
598
  async commit(prepared) {
599
+ const current = this.preparedStates.get(prepared);
600
+ if (current !== "prepared") return {
601
+ ok: false,
602
+ unitId: prepared.unitId,
603
+ dryRun: false,
604
+ changed: [],
605
+ errors: [{
606
+ code: "unit-handle-consumed",
607
+ message: "prepared mutation is already " + String(current)
608
+ }]
609
+ };
610
+ this.preparedStates.set(prepared, "committing");
591
611
  const { unitId, request, primary, validation, snapshots, eventOps, changed, warnings, bestEffort } = prepared;
592
612
  const cleanup = request.cleanupPaths === void 0 ? {} : { cleanup: request.cleanupPaths };
593
613
  try {
@@ -631,7 +651,7 @@ var UnitKernel = class {
631
651
  target: primary,
632
652
  roots: validation.roots.map((root) => root.name)
633
653
  }));
634
- if (this.snapshots !== void 0) await bestEffort(() => this.snapshots.write({
654
+ if (this.snapshots !== void 0) await this.snapshots.write({
635
655
  unitId,
636
656
  journalId: this.journalId,
637
657
  state: "committed",
@@ -639,16 +659,20 @@ var UnitKernel = class {
639
659
  ...cleanup,
640
660
  createdAt: this.now(),
641
661
  ...this.contextFields()
642
- }));
643
- await bestEffort(async () => this.journal?.write({
644
- unitId,
645
- journalId: this.journalId,
646
- ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
647
- phase: "committed",
648
- changed,
649
- target: primary,
650
- roots: validation.roots.map((root) => root.name)
651
- }));
662
+ });
663
+ try {
664
+ await this.journal?.write({
665
+ unitId,
666
+ journalId: this.journalId,
667
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
668
+ phase: "committed",
669
+ changed,
670
+ target: primary,
671
+ roots: validation.roots.map((root) => root.name)
672
+ });
673
+ } catch (error) {
674
+ warnings.push("journal committed write failed: " + (error instanceof Error ? error.message : String(error)));
675
+ }
652
676
  try {
653
677
  await this.hooks?.committed?.({
654
678
  unitId,
@@ -675,14 +699,18 @@ var UnitKernel = class {
675
699
  }
676
700
  const detail = rollbackFailure === "" ? message : message + "; rollback failed: " + rollbackFailure;
677
701
  const failureCode = error?.code === "transact-not-invoked" ? "transact-not-invoked" : "write-failed";
678
- await this.journal?.write({
679
- unitId,
680
- journalId: this.journalId,
681
- ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
682
- phase: "failed",
683
- changed,
684
- error: detail
685
- });
702
+ try {
703
+ await this.journal?.write({
704
+ unitId,
705
+ journalId: this.journalId,
706
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
707
+ phase: "failed",
708
+ changed,
709
+ error: detail
710
+ });
711
+ } catch (journalError) {
712
+ warnings.push("journal failed write failed: " + (journalError instanceof Error ? journalError.message : String(journalError)));
713
+ }
686
714
  try {
687
715
  await this.hooks?.rolledBack?.({
688
716
  unitId,
@@ -1,6 +1,6 @@
1
1
  import { b as probeText, g as probeList, m as isUnknown, p as isPresent } from "./io-DT4-MXLr.js";
2
2
  import { A as h2Sections, M as externalRefs, h as latestActivityAt } from "./usage-BO4Zj_zB.js";
3
- import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
3
+ import { t as evolutionHome } from "./state-store-BLchnUkV.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { readFile, realpath, stat } from "node:fs/promises";
6
6
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
package/lib/skills.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-DT4-MXLr.js";
2
- import { i as mutationLockFrom } from "./mutation-authority-C3RYyiaT.js";
2
+ import { s as mutationLockFrom } from "./mutation-authority-Dkt4PVsM.js";
3
3
  import { o as resolveCitations } from "./citations-CZKTUGQF.js";
4
4
  import { Q as SUPPORT_DIRS, Z as SKILL_NAME_RE, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-CO4JGSJL.js";
5
5
  import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-D2LIOEi-.js";
6
6
  import { a as measureUnit } from "./text-metrics-CyJhxWBs.js";
7
7
  import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-BO4Zj_zB.js";
8
8
  import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-JKFlfhSO.js";
9
- import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
9
+ import { n as evolutionRoot } from "./state-store-BLchnUkV.js";
10
10
  import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-BOZ4HCDB.js";
11
- import { D as fileMutationLock, E as UnitKernel, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-CSVn34dK.js";
11
+ import { D as fileMutationLock, E as UnitKernel, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-B8QoG2Oy.js";
12
12
  import { n as projectExtractBodies } from "./extract-plan-CP__XlEs.js";
13
13
  import { AsyncLocalStorage } from "node:async_hooks";
14
14
  import { createHash } from "node:crypto";
@@ -1861,11 +1861,13 @@ var SkillLibrary = class {
1861
1861
  authority;
1862
1862
  /** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
1863
1863
  mutationLock;
1864
+ mutationLockResolver;
1864
1865
  fence;
1866
+ fenceResolver;
1865
1867
  /** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
1866
1868
  * but it is a deployment condition, not a per-write event, so it warns once per instance. */
1867
1869
  historyWarned = false;
1868
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
1870
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence, mutationLockResolver, fenceResolver) {
1869
1871
  this.root = root;
1870
1872
  this.targetLocks = targetLocksFor(root);
1871
1873
  this.rootGate = rootGateFor(root);
@@ -1875,7 +1877,9 @@ var SkillLibrary = class {
1875
1877
  this.threatExemptLabels = threatExemptLabels ?? [];
1876
1878
  this.authority = authority;
1877
1879
  this.mutationLock = mutationLock;
1880
+ this.mutationLockResolver = mutationLockResolver;
1878
1881
  this.fence = fence;
1882
+ this.fenceResolver = fenceResolver;
1879
1883
  this.transact = transact ?? (io.transact ? transactIo : void 0);
1880
1884
  this.serial = serialForRoot(this.root);
1881
1885
  this.model = new SkillModel({
@@ -2056,13 +2060,23 @@ var SkillLibrary = class {
2056
2060
  };
2057
2061
  }
2058
2062
  /** True when the injected lock port is per-target rather than the home fence. */
2063
+ /** Resolve the home fence at use time too: it arrives with the same late service. */
2064
+ currentFence() {
2065
+ return this.fence ?? this.fenceResolver?.();
2066
+ }
2067
+ /** Resolve at use time: the authority row may provide its lock after this library mounts. */
2068
+ currentMutationLock() {
2069
+ return this.mutationLock ?? this.mutationLockResolver?.();
2070
+ }
2059
2071
  keyedTargetLocks() {
2060
- if (this.mutationLock !== void 0) return this.mutationLock.keyed === true;
2072
+ const lock = this.currentMutationLock();
2073
+ if (lock !== void 0) return lock.keyed === true;
2061
2074
  if (process.env["VITEST"] !== "true" && process.env["NODE_ENV"] !== "test") this.lockPort();
2062
2075
  return false;
2063
2076
  }
2064
2077
  lockPort() {
2065
- if (this.mutationLock !== void 0) return this.mutationLock;
2078
+ const lock = this.currentMutationLock();
2079
+ if (lock !== void 0) return lock;
2066
2080
  if (process.env["VITEST"] === "true" || process.env["NODE_ENV"] === "test") return fileMutationLock(this.io, this.root);
2067
2081
  throw new Error("skill-store: no authority mutationLock was supplied; refusing an unfenced production write");
2068
2082
  }
@@ -2573,7 +2587,7 @@ var SkillLibrary = class {
2573
2587
  supportFiles,
2574
2588
  restructureRounds: 0,
2575
2589
  source
2576
- }, void 0, fenceHeld ? void 0 : this.fence);
2590
+ }, void 0, fenceHeld ? void 0 : this.currentFence());
2577
2591
  } catch (error) {
2578
2592
  console.warn("skill-store: hard-cap event not recorded for \"" + name + "\": " + (error instanceof Error ? error.message : String(error)));
2579
2593
  }
@@ -2598,7 +2612,7 @@ var SkillLibrary = class {
2598
2612
  * history stopped growing is a degradation worth seeing once (the ledger keeps hashes either
2599
2613
  * way). */
2600
2614
  async audit(skillName, action, before, after, summary, path, unitId, unitHead, origin, fenceHeld = false, change) {
2601
- const fence = fenceHeld ? void 0 : this.fence;
2615
+ const fence = fenceHeld ? void 0 : this.currentFence();
2602
2616
  const at = (/* @__PURE__ */ new Date()).toISOString();
2603
2617
  const planSummary = PLAN_SUMMARY.getStore();
2604
2618
  const finalSummary = planSummary !== void 0 ? (() => {
@@ -5778,7 +5792,7 @@ function newSkillLibrary(options) {
5778
5792
  const { config, io, limits, ctx, transact, threatExemptLabels, authority } = options;
5779
5793
  return new SkillLibrary(resolveSkillsRoot(config ?? {}), io, limits, ctx ? (event) => {
5780
5794
  ctx.emit("evolution/skill-mutated", event);
5781
- } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
5795
+ } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock, options.fence, options.mutationLock === void 0 && ctx !== void 0 ? () => mutationLockFrom(ctx) : void 0, options.fence === void 0 && ctx !== void 0 ? () => ctx.get?.("evolutionMutationAuthority")?.homeFence : void 0);
5782
5796
  }
5783
5797
  //#endregion
5784
5798
  export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, SkillObservationStore, SkillRootGate, SkillTargetLocks, SkillWriteService, SystemSkillWriter, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, decideLiteralEdit, decideSkillWrite, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, projectRestructureMarkdown, readHistoryIndex, recentlyUsedAt, recordFsSkillObservation, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillBodyTarget, skillContentVersion, skillHostIdentity, skillMdOnDisk, skillNamespaceKey, skillRowCells, skillStateKey, skillSupportTarget, skillTarget, skillTargetFromHostPath, skillVersionOf, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
@@ -1,5 +1,5 @@
1
1
  import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, PENDING_KINDS, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, REVIEW_STATE_TABLE, assertCloneable, canClaimPending, canResolvePending, cloneRecord, recordIssue, releasedStatus, selectPendingOverflow, selectSessionOverflow } from "../storage.js";
2
- import "../index.js";
2
+ import "../../state-BJf0a66B.js";
3
3
  import { z } from "zod";
4
4
  import { storageDomainPort } from "@lmzhen/dsh-evolution-platform/ports";
5
5
  import { DomainError, defineDomain, domainTable } from "@lmzhen/dsh-evolution-platform/values";
@@ -1,136 +1,3 @@
1
- import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
2
1
  import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, EvolutionStateStorageRegistry, MEDIUM_PROCESS_DECLARATION, PENDING_KINDS, PENDING_RESOLVED_CAP, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, PROVIDER_STORE, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER, assertCloneable, canClaimPending, canResolvePending, cloneRecord, processScopeViolations, recordIssue, releasedStatus, runStateProviderConsistency, selectPendingOverflow, selectSessionOverflow } from "./storage.js";
3
- import { mkdir } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { withFileLock } from "@lmzhen/dsh-evolution-platform/values/fs";
6
- import { existsSync, readFileSync } from "node:fs";
7
- import { Service } from "@deepseek-ai/cordis";
8
- import z from "@deepseek-ai/schemastery";
9
- //#region lib/types/state/index.js
10
- /**
11
- * Durable evolution state consumer.
12
- *
13
- * The service owns no medium and performs no IO. It resolves the mounted
14
- * provider from `ctx.evolutionStateStorage` (see evolution-state-json and
15
- * evolution-state-domain); `provider` config may pin one by name.
16
- * @module @lmzhen/dsh-evolution-core/state
17
- */
18
- var EvolutionState = class extends Service {
19
- static inject = ["evolutionStateStorage"];
20
- static Config = z.object({
21
- provider: z.string().default(""),
22
- home: z.string().default("")
23
- });
24
- providerName;
25
- home;
26
- constructor(ctx, config = {}) {
27
- super(ctx, "evolutionState");
28
- this.providerName = config.provider ?? "";
29
- this.home = config.home !== void 0 && config.home !== "" ? config.home : evolutionHome();
30
- if (this.providerName !== "" && this.providerName !== "auto" && ctx.evolutionStateStorage.hasProviders()) ctx.evolutionStateStorage.provider(this.providerName);
31
- if (this.providerName !== "auto") this.assertProviderChoice();
32
- }
33
- /** P2-5: the multi-provider refusal is not a mount-time-only check. A provider
34
- * registered after this row mounted used to make registration order the effective
35
- * medium with no pin — exactly the silent rebind the mount check exists to stop. */
36
- /** Validate the marker + a real store image before auto may select it. */
37
- assertMarkerStore() {
38
- const marker = join(this.home, "state", STATE_MIGRATION_MARKER);
39
- if (!existsSync(marker)) return;
40
- const storePath = join(this.home, "state", "store.json");
41
- let markerBody;
42
- let storeBody;
43
- try {
44
- markerBody = JSON.parse(readFileSync(marker, "utf8"));
45
- storeBody = JSON.parse(readFileSync(storePath, "utf8"));
46
- } catch (error) {
47
- throw new Error("evolution-state: the migration marker/store is missing or unreadable: " + (error instanceof Error ? error.message : String(error)));
48
- }
49
- if (typeof markerBody !== "object" || markerBody === null || markerBody.target !== "store") throw new Error("evolution-state: the migration marker is invalid (target != store): " + marker);
50
- const image = storeBody;
51
- if (typeof image !== "object" || image === null || image.version !== 1 || typeof image.review !== "object" || image.review === null || Array.isArray(image.review) || typeof image.pending !== "object" || image.pending === null || Array.isArray(image.pending)) throw new Error("evolution-state: the migration marker points at an invalid/empty store image: " + storePath);
52
- }
53
- assertProviderChoice() {
54
- if (this.providerName === "auto") {
55
- const names = this.ctx.evolutionStateStorage.providerNames();
56
- if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
57
- if (!names.includes("store")) throw new Error("evolution-state: the migration marker exists but no \"" + PROVIDER_STORE + "\" provider is registered");
58
- this.assertMarkerStore();
59
- }
60
- return;
61
- }
62
- if (this.providerName !== "") return;
63
- const names = this.ctx.evolutionStateStorage.providerNames();
64
- if (names.length <= 1) return;
65
- throw new Error("evolution-state: " + String(names.length) + " state providers are registered (" + names.join(", ") + ") and this row pins none, so the effective medium would be registration order — a silent rebind that leaves existing state on disk and unreadable. Pin one: provider: <name>.");
66
- }
67
- /** `auto` is the migration switch: the marker is the explicit one-way signal. */
68
- autoProviderName() {
69
- const names = this.ctx.evolutionStateStorage.providerNames();
70
- if (existsSync(join(this.home, "state", ".migrated-from-domain.json"))) {
71
- this.assertMarkerStore();
72
- return PROVIDER_STORE;
73
- }
74
- if (names.includes("domain")) return PROVIDER_DOMAIN;
75
- throw new Error("evolution-state: auto has no migration marker and no \"" + PROVIDER_DOMAIN + "\" provider; refusing to guess a state authority");
76
- }
77
- /** Validate synchronously (legacy callers rely on a throw, not a rejected promise). */
78
- assertResolvable() {
79
- this.assertProviderChoice();
80
- if (this.providerName !== "" && this.providerName !== "auto") this.ctx.evolutionStateStorage.provider(this.providerName);
81
- }
82
- /** Validate, then serialize against migration across processes. */
83
- run(task) {
84
- this.assertResolvable();
85
- return this.withStateLock(task);
86
- }
87
- /** Serialize state operations against the migration command across processes. */
88
- async withStateLock(task) {
89
- await mkdir(this.home, { recursive: true });
90
- return withFileLock(join(this.home, "state.lock"), task);
91
- }
92
- storage() {
93
- this.assertProviderChoice();
94
- const name = this.providerName === "auto" ? this.autoProviderName() : this.providerName;
95
- return this.ctx.evolutionStateStorage.provider(name || void 0);
96
- }
97
- /** A2: refresh the mounted provider before a decision reads pending state. */
98
- reload() {
99
- return this.run(async () => this.storage().reload?.() ?? Promise.resolve());
100
- }
101
- loadReviewState(sessionId) {
102
- return this.run(async () => this.storage().loadReviewState(sessionId));
103
- }
104
- saveReviewState(sessionId, record) {
105
- return this.run(async () => this.storage().saveReviewState(sessionId, record));
106
- }
107
- loadCuratorState() {
108
- return this.run(async () => this.storage().loadCuratorState());
109
- }
110
- saveCuratorState(record) {
111
- return this.run(async () => this.storage().saveCuratorState(record));
112
- }
113
- /** Atomic read-modify-write the curator-state record (S5.5): `task` returns
114
- * the next record; returning null keeps the current record unchanged (the
115
- * seam has no delete semantic). */
116
- transactCuratorState(task) {
117
- return this.run(async () => this.storage().transactCuratorState(task));
118
- }
119
- listPending(status = "pending") {
120
- return this.run(async () => this.storage().listPending(status));
121
- }
122
- savePending(record) {
123
- return this.run(async () => this.storage().savePending(record));
124
- }
125
- tryResolvePending(id, status, expectedClaimId) {
126
- return this.run(async () => this.storage().tryResolvePending(id, status, expectedClaimId));
127
- }
128
- claimPending(id, claimId) {
129
- return this.run(async () => this.storage().claimPending(id, claimId));
130
- }
131
- releasePendingClaim(id, claimId) {
132
- return this.run(async () => this.storage().releasePendingClaim(id, claimId));
133
- }
134
- };
135
- //#endregion
2
+ import { t as EvolutionState } from "../state-BJf0a66B.js";
136
3
  export { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, EvolutionState, EvolutionState as default, EvolutionStateStorageRegistry, MEDIUM_PROCESS_DECLARATION, PENDING_KINDS, PENDING_RESOLVED_CAP, PENDING_STATUSES, PENDING_TABLE, PROVIDER_DOMAIN, PROVIDER_STORE, REVIEW_STATE_SESSION_CAP, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER, assertCloneable, canClaimPending, canResolvePending, cloneRecord, processScopeViolations, recordIssue, releasedStatus, runStateProviderConsistency, selectPendingOverflow, selectSessionOverflow };
@@ -1,8 +1,7 @@
1
- import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
1
+ import { t as evolutionHome } from "../state-store-BLchnUkV.js";
2
2
  import { CURATOR_STATE_KEY, CURATOR_STATE_TABLE, PENDING_STATUSES, PENDING_TABLE, REVIEW_STATE_TABLE, STATE_MIGRATION_MARKER } from "./storage.js";
3
- import "./index.js";
3
+ import { a as writeStateStoreSnapshot, i as readStateStoreSnapshot } from "../state-BJf0a66B.js";
4
4
  import { EVOLUTION_DOMAIN } from "./domain/index.js";
5
- import { writeStateStoreSnapshot } from "./store.js";
6
5
  import { mkdir } from "node:fs/promises";
7
6
  import { join } from "node:path";
8
7
  import { withFileLock } from "@lmzhen/dsh-evolution-platform/values/fs";
@@ -25,7 +24,29 @@ async function migrateDomainToStoreUnlocked(ctx, options) {
25
24
  const storePath = join(home, "state", "store.json");
26
25
  const markerPath = join(home, "state", STATE_MIGRATION_MARKER);
27
26
  const io = options.io;
28
- if (await io.exists(storePath)) throw new Error("evolution-state-migrate: store already exists; refusing to overwrite it: " + storePath);
27
+ if (await io.exists(storePath)) try {
28
+ const existing = await readStateStoreSnapshot(io, storePath);
29
+ const recovered = {
30
+ reviewSessions: Object.keys(existing.review).length,
31
+ pending: Object.keys(existing.pending).length,
32
+ curator: existing.curator !== null,
33
+ path: storePath,
34
+ dryRun: options.dryRun === true
35
+ };
36
+ if (options.dryRun === true) return recovered;
37
+ if (!await io.exists(markerPath)) await io.writeText(markerPath, JSON.stringify({
38
+ migratedAt: new Date(options.now?.() ?? Date.now()).toISOString(),
39
+ source: "domain-store-recovered",
40
+ target: "store",
41
+ reviewSessions: recovered.reviewSessions,
42
+ pending: recovered.pending,
43
+ curator: recovered.curator
44
+ }, null, 2) + "\n");
45
+ return recovered;
46
+ } catch (error) {
47
+ if (error instanceof Error && error.message.includes("refusing to overwrite")) throw error;
48
+ throw new Error("evolution-state-migrate: store already exists; refusing to overwrite it: " + storePath);
49
+ }
29
50
  const mounted = ctx.evolutionStateStorage?.provider?.("domain");
30
51
  let review = {};
31
52
  let pending = {};
@@ -1,22 +1,15 @@
1
- import { t as evolutionHome } from "../state-store-Jpa-iYIZ.js";
2
- import { createStateStoreProvider } from "./store.js";
1
+ import { t as evolutionHome } from "../state-store-BLchnUkV.js";
2
+ import { n as createStateStoreProvider } from "../state-BJf0a66B.js";
3
3
  //#region lib/types/state/store-plugin.js
4
4
  const name = "evolution-state-store";
5
5
  const inject = ["evolutionStateStorage", "evolutionIo"];
6
- /** HMR re-applies the row in the same ctx; the registry only treats the SAME object as
7
- * idempotent, so keep one provider per home instead of constructing a new registrant. */
8
- const providers = /* @__PURE__ */ new Map();
9
6
  async function apply(ctx) {
10
7
  await ctx.evolutionIo.whenReady();
11
8
  const home = evolutionHome();
12
- let provider = providers.get(home);
13
- if (provider === void 0) {
14
- provider = createStateStoreProvider({
15
- io: ctx.evolutionIo.provider(),
16
- home
17
- });
18
- providers.set(home, provider);
19
- }
9
+ const provider = createStateStoreProvider({
10
+ io: ctx.evolutionIo.provider(),
11
+ home
12
+ });
20
13
  ctx.effect(() => ctx.evolutionStateStorage.registerProvider(provider), "evolution-state-store.provider");
21
14
  }
22
15
  //#endregion