@lmzhen/dsh-evolution-core 0.59.2 → 0.59.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/lib/authority-plugin.js +7 -4
  2. package/lib/{extract-plan-BxDhKSki.js → extract-plan-D3ALlAmN.js} +2 -2
  3. package/lib/extract.js +4 -4
  4. package/lib/index.js +9 -9
  5. package/lib/io-node.js +1 -1
  6. package/lib/{mutation-authority-Du-ON0NY.js → mutation-authority-CZpc9F20.js} +222 -4
  7. package/lib/{mutation-storage-adapter-7R3ra0wj.js → mutation-storage-adapter-z1_hyrQn.js} +10 -6
  8. package/lib/{mutations-mvTnWkua.js → mutations-Y-wKod7W.js} +2 -2
  9. package/lib/{quality-CREp6s1G.js → quality-NPGr3VzA.js} +3 -3
  10. package/lib/{review-context-CW_kJAzn.js → review-context-yNiZadPw.js} +1 -1
  11. package/lib/{skill-history-YX84wO20.js → skill-history-BvLWFoOo.js} +2 -2
  12. package/lib/skills.js +1023 -189
  13. package/lib/types/authority-plugin.d.ts +7 -1
  14. package/lib/types/authority-plugin.js +10 -2
  15. package/lib/types/authority.d.ts +49 -0
  16. package/lib/types/authority.js +194 -0
  17. package/lib/types/events.d.ts +2 -0
  18. package/lib/types/mutation-authority.d.ts +31 -2
  19. package/lib/types/mutation-authority.js +45 -1
  20. package/lib/types/mutation-unit.d.ts +23 -1
  21. package/lib/types/mutation-unit.js +7 -3
  22. package/lib/types/skill-observation-source.d.ts +26 -0
  23. package/lib/types/skill-observation-source.js +56 -0
  24. package/lib/types/skill-observation.d.ts +87 -0
  25. package/lib/types/skill-observation.js +110 -0
  26. package/lib/types/skill-root-gate.d.ts +40 -0
  27. package/lib/types/skill-root-gate.js +98 -0
  28. package/lib/types/skill-store.d.ts +22 -3
  29. package/lib/types/skill-store.js +437 -217
  30. package/lib/types/skill-target-locks.d.ts +39 -0
  31. package/lib/types/skill-target-locks.js +64 -0
  32. package/lib/types/skill-write-intent.d.ts +63 -0
  33. package/lib/types/skill-write-intent.js +104 -0
  34. package/lib/types/skill-write-service.d.ts +85 -0
  35. package/lib/types/skill-write-service.js +180 -0
  36. package/lib/types/skills.d.ts +6 -0
  37. package/lib/types/skills.js +6 -0
  38. package/lib/{usage-DrczLTP4.js → usage-D7yHG2Cb.js} +2 -2
  39. package/lib/write.js +3 -3
  40. package/package.json +3 -3
  41. package/lib/{io-GxghO3Ip.js → io-Cpa8wuvj.js} +1 -1
@@ -1,15 +1,18 @@
1
- import { t as MutationAuthority } from "./mutation-authority-Du-ON0NY.js";
1
+ import { n as MutationAuthority } from "./mutation-authority-CZpc9F20.js";
2
2
  import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
3
+ import z from "@deepseek-ai/schemastery";
3
4
  //#region lib/types/authority-plugin.js
5
+ const Config = z.object({ keyedSkillLocks: z.boolean().default(false) });
4
6
  const name = "evolution-authority";
5
7
  const inject = ["evolutionIo"];
6
8
  /** Expose the single home/run-fenced mutation authority to domain packages. */
7
- function apply(ctx) {
9
+ function apply(ctx, config = { keyedSkillLocks: false }) {
8
10
  const authority = new MutationAuthority({
9
11
  io: ctx.evolutionIo.provider(),
10
- home: evolutionHome()
12
+ home: evolutionHome(),
13
+ keyed: config.keyedSkillLocks === true
11
14
  });
12
15
  ctx.provide("evolutionMutationAuthority", authority);
13
16
  }
14
17
  //#endregion
15
- export { apply, inject, name };
18
+ export { Config, apply, inject, name };
@@ -1,5 +1,5 @@
1
- import { I as planReferenceRewrite, L as planRehoming, M as externalRefs, N as supportRefs, O as selectSections, P as applyReferenceRewrite } from "./usage-DrczLTP4.js";
2
- import { u as frontmatterBlock } from "./mutations-mvTnWkua.js";
1
+ import { I as planReferenceRewrite, L as planRehoming, M as externalRefs, N as supportRefs, O as selectSections, P as applyReferenceRewrite } from "./usage-D7yHG2Cb.js";
2
+ import { u as frontmatterBlock } from "./mutations-Y-wKod7W.js";
3
3
  import { createHash } from "node:crypto";
4
4
  //#region lib/types/extract-plan.js
5
5
  const LF = String.fromCharCode(10);
package/lib/extract.js CHANGED
@@ -1,9 +1,9 @@
1
- import { p as isPresent } from "./io-GxghO3Ip.js";
1
+ import { p as isPresent } from "./io-Cpa8wuvj.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
- import { p as parseFrontmatter, r as contentHash } from "./mutations-mvTnWkua.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-CREp6s1G.js";
6
- import { n as projectExtractBodies, t as planExtract } from "./extract-plan-BxDhKSki.js";
4
+ import { p as parseFrontmatter, r as contentHash } from "./mutations-Y-wKod7W.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-NPGr3VzA.js";
6
+ import { n as projectExtractBodies, t as planExtract } from "./extract-plan-D3ALlAmN.js";
7
7
  import { dirname, join } from "node:path";
8
8
  //#region lib/types/extract-request.js
9
9
  /** The one human-readable owner decision shared by tool and CLI. */
package/lib/index.js CHANGED
@@ -1,26 +1,26 @@
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-GxghO3Ip.js";
2
- import { a as leaseFile, c as AuthorityBusyError, d as HomeAuthority, f as authorityHolder, i as LeaseStore, l as AuthorityOrderError, n as mutationLockFrom, o as HomeFence, p as leaseAsTreeLock, r as DEFAULT_LEASE_TTL_MS, s as HomeFenceError, t as MutationAuthority, u as AuthorityReentryError } from "./mutation-authority-Du-ON0NY.js";
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-Cpa8wuvj.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-CZpc9F20.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-BpVDuDnA.js";
6
- import { A as retainEventArchives, C as appendEvolutionEvent, D as parseEvolutionEvents, E as listEventArchives, G as DEFAULT_WRITE_CONFIRM_MODE, H as isUnreadWrite, I as softBodyTokenBudget, K as DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, L as RULES, O as readEvolutionEvents, P as assessStructureHealth, S as EVENT_LOG_VERSION, T as evolutionEventPayloadIssue, _ as fuzzyPatch, a as isReviewChannelSession, b as EVENT_LOG_RETAIN_ARCHIVES, c as PATTERN_OVERLAP, d as scanContentThreats, f as scanMemoryThreats, g as FUZZY_MAX_WORK, h as FUZZY_MAX_PATTERN_CHARS, i as clearReviewChannel, j as DEFAULT_HEALTH_THRESHOLDS, k as readEvolutionTimeline, l as THREAT_EXEMPTION_HINT, m as makeSerialQueue, n as recordReviewRead, o as markReviewChannel, p as scanThreats, q as authorityFrom, r as withReviewContext, s as sweepReviewChannelSessions, t as currentReviewContext, u as evaluateThreat, v as trimPatternBoundaries, w as eventsFile, x as EVENT_LOG_ROTATE_AT, y as EVENT_ARCHIVE_PREFIX, z as lintSkill } from "./review-context-CW_kJAzn.js";
6
+ import { A as retainEventArchives, C as appendEvolutionEvent, D as parseEvolutionEvents, E as listEventArchives, G as DEFAULT_WRITE_CONFIRM_MODE, H as isUnreadWrite, I as softBodyTokenBudget, K as DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, L as RULES, O as readEvolutionEvents, P as assessStructureHealth, S as EVENT_LOG_VERSION, T as evolutionEventPayloadIssue, _ as fuzzyPatch, a as isReviewChannelSession, b as EVENT_LOG_RETAIN_ARCHIVES, c as PATTERN_OVERLAP, d as scanContentThreats, f as scanMemoryThreats, g as FUZZY_MAX_WORK, h as FUZZY_MAX_PATTERN_CHARS, i as clearReviewChannel, j as DEFAULT_HEALTH_THRESHOLDS, k as readEvolutionTimeline, l as THREAT_EXEMPTION_HINT, m as makeSerialQueue, n as recordReviewRead, o as markReviewChannel, p as scanThreats, q as authorityFrom, r as withReviewContext, s as sweepReviewChannelSessions, t as currentReviewContext, u as evaluateThreat, v as trimPatternBoundaries, w as eventsFile, x as EVENT_LOG_ROTATE_AT, y as EVENT_ARCHIVE_PREFIX, z as lintSkill } from "./review-context-yNiZadPw.js";
7
7
  import { i as HOST_LOCALES, n as errorText, r as errorTextIn, t as EVOLUTION_ERRORS } from "./errors-BxzLTVbS.js";
8
8
  import { A as dispatchKeyOf, C as PTC_DISPATCH_EVENT, D as assertDispatchPayload, E as ToolDispatchPayloadError, F as isSkillToolName, I as readDispatchSignal, L as skillReadNameOf, M as dispatchStepOf, N as foldToolDispatches, O as collectReadSkillNames, P as isSkillReadToolName, R as supportFileReadFromPath, S as NATIVE_RESULT_EVENT, T as ToolDispatchNormalizer, _ as isBookkeepingFrame, a as evolutionSignalsProjection, b as MODEL_SESSION_EVENT_TYPES, c as sessionLastEventTime, d as advanceReview, f as foldTurnEvent, g as evidenceKindIndex, h as observeEvent, i as evolutionReadsProjection, j as dispatchPathOf, k as collectReadSupportFiles, l as sessionReadNames, m as initialTurnFold, n as evolutionEvidenceProjection, o as isProjectableSession, p as foldTurnEvents, r as evolutionProjectionHistoryProjection, s as sessionEvidenceIndex, t as evolutionActivityProjection, u as sessionTurnSignals, v as DEFAULT_SUPPORT_READ_TOOL_NAMES, w as PTC_DISPATCH_START_EVENT, x as NATIVE_CALL_EVENT, y as DISPATCH_EVENT_TYPES, z as supportFileReadOf } from "./session-projection-DM15fsRp.js";
9
9
  import { a as measureUnit, i as measureText, n as conservativeTokenEstimator, o as truncateGraphemes, r as graphemeCount, s as utf8ByteLength, t as codePointCount } from "./text-metrics-CyJhxWBs.js";
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-DrczLTP4.js";
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-D7yHG2Cb.js";
11
11
  import { n as isRecord, t as asRecord } from "./guards-3f02mnf2.js";
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-mvTnWkua.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-CREp6s1G.js";
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-Y-wKod7W.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-NPGr3VzA.js";
14
14
  import { n as evolutionRoot, t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
15
- import "./skill-history-YX84wO20.js";
15
+ import "./skill-history-BvLWFoOo.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-B_F4TYOD.js";
18
18
  import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
19
19
  import { abortLink, createSubagentChannel as createSubagentKernel, createSubagentRun, probeChannelState, textOfValue, waitForSubagentEnd } from "./subagent/index.js";
20
+ import { createHash, randomUUID } from "node:crypto";
20
21
  import { basename, join } from "node:path";
21
22
  import { scopeOf } from "@lmzhen/dsh-evolution-adapter/values";
22
23
  import { readFileSync } from "node:fs";
23
- import { createHash, randomUUID } from "node:crypto";
24
24
  import { fileURLToPath } from "node:url";
25
25
  import { parse } from "yaml";
26
26
  import { settingsPort, toolsPort } from "@lmzhen/dsh-evolution-adapter/ports";
@@ -5551,4 +5551,4 @@ function classifySessionEvent(event) {
5551
5551
  return MODEL_EVENT_TYPES.has(type) ? "model" : "unknown";
5552
5552
  }
5553
5553
  //#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, 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, 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 };
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 };
package/lib/io-node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
1
+ import { o as nodeEvolutionIo } from "./io-Cpa8wuvj.js";
2
2
  //#region lib/types/io-node.js
3
3
  /**
4
4
  * Local atomic node:fs IO provider.
@@ -1,9 +1,9 @@
1
- import { a as isProcessAlive, c as transactIo } from "./io-GxghO3Ip.js";
1
+ import { a as isProcessAlive, c as transactIo } from "./io-Cpa8wuvj.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { createHash, randomUUID } from "node:crypto";
3
4
  import { mkdir, readFile, rm } from "node:fs/promises";
4
5
  import { dirname, join } from "node:path";
5
6
  import { withFileLock } from "@lmzhen/dsh-evolution-adapter/values";
6
- import { randomUUID } from "node:crypto";
7
7
  //#region lib/types/authority.js
8
8
  /**
9
9
  * The family's one mutual-exclusion entry (W9-authority, invariant I1).
@@ -72,6 +72,185 @@ function isBusy(error) {
72
72
  * One home-wide writer authority. Every durable writer calls {@link HomeAuthority.runExclusive};
73
73
  * an operation that runs inside another held operation calls {@link HomeAuthority.runNested}.
74
74
  */
75
+ /**
76
+ * Per-target cross-process locks for the scoped authority.
77
+ *
78
+ * Each key gets its own platform writer lock under
79
+ * `<home>/.authority/targets/<sha256(key)>.lock`; keys are acquired in lexical
80
+ * order. Different keys therefore do not exclude each other across processes,
81
+ * while one key remains mutually exclusive. This class is the kernel only; the
82
+ * mutation authority wires it into UnitTransaction after its behavior is
83
+ * proven.
84
+ */
85
+ var TargetLockSet = class {
86
+ home;
87
+ waitMs;
88
+ lock;
89
+ tails = /* @__PURE__ */ new Map();
90
+ releaseError;
91
+ brokenKeys = /* @__PURE__ */ new Set();
92
+ /** Last release failure; diagnostics only, never a reason to wedge the key queue. */
93
+ get lastReleaseError() {
94
+ return this.releaseError;
95
+ }
96
+ constructor(home, waitMs = DEFAULT_WAIT_MS, lock = withFileLock) {
97
+ this.home = home;
98
+ this.waitMs = waitMs;
99
+ this.lock = lock;
100
+ }
101
+ /**
102
+ * Run a task under all supplied target keys.
103
+ * @param keys - canonical target keys; duplicate/unsorted input is normalized.
104
+ * @param body - the critical section.
105
+ * @returns the body's value.
106
+ */
107
+ async run(keys, body) {
108
+ const ordered = [...new Set(keys)].sort();
109
+ return await this.acquire(ordered, 0, body);
110
+ }
111
+ /** Held target queues, for leak assertions. */
112
+ get size() {
113
+ return this.tails.size;
114
+ }
115
+ /**
116
+ * Acquire a lease over one or more target keys without running a body.
117
+ * Keys are normalized/sorted; a failed acquisition releases every already-held key.
118
+ */
119
+ async acquireLease(keys) {
120
+ const ordered = [...new Set(keys)].sort();
121
+ const leases = [];
122
+ try {
123
+ for (const key of ordered) leases.push(await this.acquireKey(key));
124
+ } catch (error) {
125
+ for (const release of leases.reverse()) try {
126
+ await release();
127
+ } catch {}
128
+ throw error;
129
+ }
130
+ let released = false;
131
+ return { release: async () => {
132
+ if (released) return;
133
+ released = true;
134
+ for (const release of leases.reverse()) await release();
135
+ } };
136
+ }
137
+ async acquireKey(key) {
138
+ const prior = this.tails.get(key) ?? Promise.resolve();
139
+ let releaseGate;
140
+ const gate = new Promise((resolve) => {
141
+ releaseGate = resolve;
142
+ });
143
+ const tail = prior.then(() => gate);
144
+ this.tails.set(key, tail);
145
+ await prior;
146
+ let releaseLock;
147
+ const held = new Promise((resolve) => {
148
+ releaseLock = resolve;
149
+ });
150
+ let acquiredResolve;
151
+ const acquired = new Promise((resolve) => {
152
+ acquiredResolve = resolve;
153
+ });
154
+ const done = this.withLockFile(key, async () => {
155
+ acquiredResolve();
156
+ await held;
157
+ });
158
+ done.catch(() => {});
159
+ try {
160
+ await Promise.race([acquired, done]);
161
+ } catch (error) {
162
+ releaseGate();
163
+ if (this.tails.get(key) === tail) this.tails.delete(key);
164
+ throw error;
165
+ }
166
+ let released = false;
167
+ return async () => {
168
+ if (released) return;
169
+ released = true;
170
+ releaseLock();
171
+ try {
172
+ await done;
173
+ } catch (error) {
174
+ this.releaseError = error instanceof Error ? error : new Error(String(error));
175
+ this.brokenKeys.add(key);
176
+ } finally {
177
+ releaseGate();
178
+ if (this.tails.get(key) === tail) this.tails.delete(key);
179
+ }
180
+ };
181
+ }
182
+ async acquire(keys, index, body) {
183
+ const key = keys[index];
184
+ if (key === void 0) return await body();
185
+ const prior = this.tails.get(key) ?? Promise.resolve();
186
+ let release;
187
+ const gate = new Promise((resolve) => {
188
+ release = resolve;
189
+ });
190
+ const tail = prior.then(() => gate);
191
+ this.tails.set(key, tail);
192
+ await prior;
193
+ try {
194
+ return await this.withLockFile(key, async () => await this.acquire(keys, index + 1, body));
195
+ } finally {
196
+ release();
197
+ if (this.tails.get(key) === tail) this.tails.delete(key);
198
+ }
199
+ }
200
+ /**
201
+ * Remove target lock files left by a release failure, but only when the
202
+ * recorded owner process is gone. A live owner is reported as skipped.
203
+ */
204
+ async repair() {
205
+ const repaired = [];
206
+ const skipped = [];
207
+ for (const key of [...this.brokenKeys]) {
208
+ const path = this.lockPath(key) + ".lock";
209
+ let raw;
210
+ try {
211
+ raw = await readFile(path, "utf8");
212
+ } catch (error) {
213
+ if (error.code === "ENOENT") {
214
+ this.brokenKeys.delete(key);
215
+ repaired.push(key);
216
+ } else skipped.push(key);
217
+ continue;
218
+ }
219
+ const pid = Number.parseInt(raw.trim(), 10);
220
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && isProcessAlive(pid)) {
221
+ skipped.push(key);
222
+ continue;
223
+ }
224
+ try {
225
+ await rm(path, { force: true });
226
+ try {
227
+ await readFile(path, "utf8");
228
+ skipped.push(key);
229
+ } catch (error) {
230
+ if (error.code === "ENOENT") {
231
+ this.brokenKeys.delete(key);
232
+ repaired.push(key);
233
+ } else skipped.push(key);
234
+ }
235
+ } catch {
236
+ skipped.push(key);
237
+ }
238
+ }
239
+ return {
240
+ repaired,
241
+ skipped
242
+ };
243
+ }
244
+ lockPath(key) {
245
+ const digest = createHash("sha256").update(key).digest("hex");
246
+ return join(this.home, ".authority", "targets", digest);
247
+ }
248
+ async withLockFile(key, body) {
249
+ const path = this.lockPath(key);
250
+ await mkdir(dirname(path), { recursive: true });
251
+ return await this.lock(path, body, { waitMs: this.waitMs });
252
+ }
253
+ };
75
254
  var HomeAuthority = class {
76
255
  options;
77
256
  held = /* @__PURE__ */ new Map();
@@ -446,6 +625,8 @@ var LeaseStore = class {
446
625
  var MutationAuthority = class {
447
626
  leases;
448
627
  fence;
628
+ keyed;
629
+ targetLocks;
449
630
  /** Lease primitives for run/claim owners (review, approval). */
450
631
  get lease() {
451
632
  return this.leases;
@@ -454,8 +635,12 @@ var MutationAuthority = class {
454
635
  get homeFence() {
455
636
  return this.fence;
456
637
  }
457
- /** Adapter for MutationUnit call sites that accept a lock port. It is the fence, no more. */
638
+ /** Adapter for MutationUnit call sites; root fence or, when opted in, keyed targets. */
458
639
  get mutationLock() {
640
+ if (!this.keyed) return this.rootMutationLock;
641
+ return new HybridMutationLock(new TargetMutationLock(this.targetLocks), this.rootMutationLock);
642
+ }
643
+ get rootMutationLock() {
459
644
  return { acquire: async () => {
460
645
  if (this.fence.holdsTree()) return { release: async () => {} };
461
646
  const lease = await this.fence.acquire();
@@ -465,6 +650,8 @@ var MutationAuthority = class {
465
650
  } };
466
651
  }
467
652
  constructor(options) {
653
+ this.keyed = options.keyed === true;
654
+ this.targetLocks = this.keyed ? new TargetLockSet(options.home) : void 0;
468
655
  this.leases = options.leases ?? new LeaseStore({
469
656
  io: options.io,
470
657
  home: options.home,
@@ -479,9 +666,40 @@ var MutationAuthority = class {
479
666
  }
480
667
  };
481
668
  /** Read the authority's fence adapter from a context; undefined means no authority is mounted. */
669
+ /** A keyed MutationLockPort over TargetLockSet; empty key sets are refused, not silently unlocked. */
670
+ var TargetMutationLock = class {
671
+ locks;
672
+ keyed = true;
673
+ constructor(locks) {
674
+ this.locks = locks;
675
+ }
676
+ async acquire(targetKeys = []) {
677
+ if (targetKeys.length === 0) throw new Error("target mutation lock requires at least one target key");
678
+ return await this.locks.acquireLease(targetKeys);
679
+ }
680
+ async repair() {
681
+ return await this.locks.repair();
682
+ }
683
+ };
684
+ /** Routes keyed writes to the target lock set and keyless writes to the root fence. */
685
+ var HybridMutationLock = class {
686
+ keyedLock;
687
+ fallback;
688
+ keyed = true;
689
+ constructor(keyedLock, fallback) {
690
+ this.keyedLock = keyedLock;
691
+ this.fallback = fallback;
692
+ }
693
+ async acquire(targetKeys = []) {
694
+ return targetKeys.length === 0 ? await this.fallback.acquire() : await this.keyedLock.acquire(targetKeys);
695
+ }
696
+ async repair() {
697
+ return await this.keyedLock.repair();
698
+ }
699
+ };
482
700
  function mutationLockFrom(ctx) {
483
701
  if (ctx?.get === void 0) return void 0;
484
702
  return ctx.get("evolutionMutationAuthority")?.mutationLock;
485
703
  }
486
704
  //#endregion
487
- export { leaseFile as a, AuthorityBusyError as c, HomeAuthority as d, authorityHolder as f, LeaseStore as i, AuthorityOrderError as l, mutationLockFrom as n, HomeFence as o, leaseAsTreeLock as p, DEFAULT_LEASE_TTL_MS as r, HomeFenceError as s, MutationAuthority as t, AuthorityReentryError as u };
705
+ 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 };
@@ -1,7 +1,7 @@
1
- import { a as isProcessAlive, c as transactIo, i as isCommittedWarning, t as TransactionNotInvokedError } from "./io-GxghO3Ip.js";
2
- import { l as exceedsContentLimit, r as contentHash } from "./mutations-mvTnWkua.js";
3
- import { basename, dirname, isAbsolute, join, relative } from "node:path";
1
+ import { a as isProcessAlive, c as transactIo, i as isCommittedWarning, t as TransactionNotInvokedError } from "./io-Cpa8wuvj.js";
2
+ import { l as exceedsContentLimit, r as contentHash } from "./mutations-Y-wKod7W.js";
4
3
  import { createHash, randomUUID } from "node:crypto";
4
+ import { basename, dirname, isAbsolute, join, relative } from "node:path";
5
5
  //#region lib/types/write-kernel.js
6
6
  /**
7
7
  * The family's single write primitive: compare the baseline INSIDE the write
@@ -338,6 +338,8 @@ var MutationUnit = class {
338
338
  limits;
339
339
  serial;
340
340
  lock;
341
+ targetKeys;
342
+ targetKeysForSnapshot;
341
343
  journal;
342
344
  snapshots;
343
345
  claim;
@@ -355,6 +357,8 @@ var MutationUnit = class {
355
357
  this.serial = options.serial ?? identitySerial;
356
358
  if (options.lock === void 0 && options.nested !== true) throw new Error("mutation-unit: a lock (or an explicit nested:true under an outer fence) is required");
357
359
  this.lock = options.lock ?? noLock;
360
+ this.targetKeys = options.targetKeys;
361
+ this.targetKeysForSnapshot = options.targetKeysForSnapshot;
358
362
  this.journal = options.journal;
359
363
  this.snapshots = options.snapshots;
360
364
  this.claim = options.claim;
@@ -403,7 +407,7 @@ var MutationUnit = class {
403
407
  return await this.serial(async () => {
404
408
  let lease;
405
409
  try {
406
- lease = await this.lock.acquire();
410
+ lease = await this.lock.acquire(this.targetKeys);
407
411
  } catch (error) {
408
412
  return {
409
413
  ok: false,
@@ -646,7 +650,7 @@ var MutationUnit = class {
646
650
  return await this.serial(async () => {
647
651
  let lease;
648
652
  try {
649
- lease = await this.lock.acquire();
653
+ lease = await this.lock.acquire(this.targetKeysForSnapshot?.(snapshot) ?? this.targetKeys);
650
654
  } catch (error) {
651
655
  return {
652
656
  ok: false,
@@ -774,7 +778,7 @@ var MutationUnit = class {
774
778
  return await this.serial(async () => {
775
779
  let lease;
776
780
  try {
777
- lease = await this.lock.acquire();
781
+ lease = await this.lock.acquire(this.targetKeys);
778
782
  } catch (error) {
779
783
  return {
780
784
  ok: false,
@@ -1,9 +1,9 @@
1
- import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
1
+ import { c as transactIo, o as nodeEvolutionIo } from "./io-Cpa8wuvj.js";
2
2
  import { Z as SKILL_NAME_RE, i as DEFAULT_SKILL_LIMITS, u as CONTENT_SPLIT_HINT } from "./limits-CO4JGSJL.js";
3
3
  import { a as measureUnit, o as truncateGraphemes, r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
4
4
  import { n as isRecord } from "./guards-3f02mnf2.js";
5
- import { join } from "node:path";
6
5
  import { createHash } from "node:crypto";
6
+ import { join } from "node:path";
7
7
  import { parse } from "yaml";
8
8
  //#region lib/types/frontmatter.js
9
9
  /**
@@ -1,9 +1,9 @@
1
- import { b as probeText, g as probeList, m as isUnknown, p as isPresent } from "./io-GxghO3Ip.js";
2
- import { A as h2Sections, M as externalRefs, h as latestActivityAt } from "./usage-DrczLTP4.js";
1
+ import { b as probeText, g as probeList, m as isUnknown, p as isPresent } from "./io-Cpa8wuvj.js";
2
+ import { A as h2Sections, M as externalRefs, h as latestActivityAt } from "./usage-D7yHG2Cb.js";
3
3
  import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
4
+ import { createHash } from "node:crypto";
4
5
  import { readFile, realpath, stat } from "node:fs/promises";
5
6
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
6
- import { createHash } from "node:crypto";
7
7
  //#region lib/types/owner-resolver.js
8
8
  /**
9
9
  * Project the current library listing into owner candidates.
@@ -1,4 +1,4 @@
1
- import { c as transactIo } from "./io-GxghO3Ip.js";
1
+ import { c as transactIo } from "./io-Cpa8wuvj.js";
2
2
  import { N as DEFAULT_THREAT_MAX_SCAN_CHARS, O as DEFAULT_SOFT_BODY_TOKENS, tt as UPSTREAM_LIMIT_CHARS_PER_TOKEN } from "./limits-CO4JGSJL.js";
3
3
  import { O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-DM15fsRp.js";
4
4
  import { a as measureUnit, i as measureText } from "./text-metrics-CyJhxWBs.js";
@@ -1,7 +1,7 @@
1
- import { b as probeText, c as transactIo, m as isUnknown, p as isPresent } from "./io-GxghO3Ip.js";
1
+ import { b as probeText, c as transactIo, m as isUnknown, p as isPresent } from "./io-Cpa8wuvj.js";
2
2
  import { et as TEXT_DIFF_MAX_GRAPHEMES } from "./limits-CO4JGSJL.js";
3
3
  import { o as truncateGraphemes, r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
4
- import { r as contentHash } from "./mutations-mvTnWkua.js";
4
+ import { r as contentHash } from "./mutations-Y-wKod7W.js";
5
5
  import { join } from "node:path";
6
6
  //#region lib/types/skill-history.js
7
7
  /**