@lmzhen/dsh-evolution-core 0.45.0 → 0.47.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.
Files changed (65) hide show
  1. package/lib/authority-plugin.js +1 -1
  2. package/lib/composition/index.js +3 -3
  3. package/lib/{composition-Da8NfRI7.js → composition-Cqjbho0t.js} +1 -1
  4. package/lib/{ensure-C5Mo1dbB.js → ensure-CAjLGd9f.js} +1 -2
  5. package/lib/http-routes.js +21 -96
  6. package/lib/index.js +26 -138
  7. package/lib/{io-AmUf4lVY.js → io-BCBSr6Ot.js} +1 -63
  8. package/lib/io-node.js +1 -1
  9. package/lib/io-registry.js +14 -29
  10. package/lib/{mutation-authority-DeJ_Wz14.js → mutation-authority-CM6wRgyK.js} +4 -14
  11. package/lib/{mutations-DwvbjRHF.js → mutations-DihgpfgG.js} +1 -1
  12. package/lib/runtime/plugin.js +1 -1
  13. package/lib/{session-projection-EB7mUOlJ.js → session-projection-BhlDXqws.js} +2 -2
  14. package/lib/{skill-health-D1pZGk5V.js → skill-health-BzkUQDi7.js} +3 -24
  15. package/lib/{skill-history-CjypdYqv.js → skill-history-RWt1-kbZ.js} +14 -54
  16. package/lib/skills.js +7 -7
  17. package/lib/subagent/index.js +4 -10
  18. package/lib/types/composition/preset-ids.d.ts +0 -1
  19. package/lib/types/composition/preset-ids.js +0 -1
  20. package/lib/types/curator.d.ts +0 -1
  21. package/lib/types/curator.js +0 -1
  22. package/lib/types/document-body.d.ts +0 -12
  23. package/lib/types/document-body.js +0 -14
  24. package/lib/types/http-routes.d.ts +9 -4
  25. package/lib/types/http-routes.js +36 -116
  26. package/lib/types/index.d.ts +0 -3
  27. package/lib/types/index.js +0 -3
  28. package/lib/types/io-registry.d.ts +11 -11
  29. package/lib/types/io-registry.js +13 -16
  30. package/lib/types/io.d.ts +0 -53
  31. package/lib/types/io.js +0 -56
  32. package/lib/types/journal-protocol.d.ts +0 -15
  33. package/lib/types/journal-protocol.js +1 -19
  34. package/lib/types/lease-store.d.ts +1 -1
  35. package/lib/types/lease-store.js +4 -15
  36. package/lib/types/live.d.ts +0 -12
  37. package/lib/types/live.js +0 -18
  38. package/lib/types/memory-store.d.ts +0 -1
  39. package/lib/types/memory-store.js +0 -1
  40. package/lib/types/mutation-unit.js +5 -4
  41. package/lib/types/probe.d.ts +0 -3
  42. package/lib/types/probe.js +0 -7
  43. package/lib/types/run-registry.js +10 -12
  44. package/lib/types/session-fold.d.ts +0 -8
  45. package/lib/types/session-fold.js +0 -5
  46. package/lib/types/session-projection.js +2 -2
  47. package/lib/types/skill-discovery.d.ts +0 -2
  48. package/lib/types/skill-discovery.js +1 -2
  49. package/lib/types/skill-history.d.ts +0 -24
  50. package/lib/types/skill-history.js +0 -41
  51. package/lib/types/skill-lint.d.ts +0 -3
  52. package/lib/types/skill-lint.js +0 -12
  53. package/lib/types/subagent/readiness.d.ts +0 -1
  54. package/lib/types/subagent/readiness.js +2 -8
  55. package/lib/types/unit-journal.d.ts +1 -1
  56. package/lib/types/unit-journal.js +2 -4
  57. package/lib/types/unit-storage.d.ts +1 -1
  58. package/lib/types/unit-storage.js +5 -16
  59. package/lib/write.js +2 -2
  60. package/package.json +1 -1
  61. package/persisted-write-inventory.json +47 -2
  62. package/lib/types/fold-untrusted.d.ts +0 -35
  63. package/lib/types/fold-untrusted.js +0 -44
  64. package/lib/types/unit-recovery.d.ts +0 -5
  65. package/lib/types/unit-recovery.js +0 -12
@@ -1,4 +1,4 @@
1
- import { i as isProcessAlive } from "./io-AmUf4lVY.js";
1
+ import { i as isProcessAlive, s as transactIo } from "./io-BCBSr6Ot.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { mkdir, readFile, rm } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
@@ -375,16 +375,6 @@ function parseLease(raw) {
375
375
  return;
376
376
  }
377
377
  }
378
- async function transact(io, path, task) {
379
- if (io.transact !== void 0) {
380
- await io.transact(path, task);
381
- return;
382
- }
383
- const current = await io.readText(path);
384
- const next = task(current);
385
- if (next === null) await io.remove(path);
386
- else if (next !== current) await io.writeText(path, next);
387
- }
388
378
  function tokenOf(record) {
389
379
  return {
390
380
  id: record.id,
@@ -417,7 +407,7 @@ var LeaseStore = class {
417
407
  const now = this.now();
418
408
  let created;
419
409
  let holder;
420
- await transact(this.io, path, (raw) => {
410
+ await transactIo(this.io, path, (raw) => {
421
411
  const current = parseLease(raw);
422
412
  if (current !== void 0 && current.state === "active" && now < current.expiresAt) {
423
413
  holder = current;
@@ -458,7 +448,7 @@ var LeaseStore = class {
458
448
  async renew(token, ttlMs = this.ttlMs) {
459
449
  const path = this.path(token.runId);
460
450
  let next = null;
461
- await transact(this.io, path, (raw) => {
451
+ await transactIo(this.io, path, (raw) => {
462
452
  const current = parseLease(raw);
463
453
  if (current === void 0 || current.state !== "active" || current.id !== token.id || current.epoch !== token.epoch) return raw;
464
454
  const now = this.now();
@@ -473,7 +463,7 @@ var LeaseStore = class {
473
463
  }
474
464
  async release(token) {
475
465
  const path = this.path(token.runId);
476
- await transact(this.io, path, (raw) => {
466
+ await transactIo(this.io, path, (raw) => {
477
467
  const current = parseLease(raw);
478
468
  if (current === void 0 || current.id !== token.id || current.epoch !== token.epoch) return raw;
479
469
  return JSON.stringify({
@@ -1,4 +1,4 @@
1
- import { a as nodeEvolutionIo, s as transactIo } from "./io-AmUf4lVY.js";
1
+ import { a as nodeEvolutionIo, s as transactIo } from "./io-BCBSr6Ot.js";
2
2
  import { n as isRecord } from "./guards-3f02mnf2.js";
3
3
  import { join } from "node:path";
4
4
  import { createHash } from "node:crypto";
@@ -1,4 +1,4 @@
1
- import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-EB7mUOlJ.js";
1
+ import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-BhlDXqws.js";
2
2
  import { t as presetsPort } from "../presets-C8vuCuNA.js";
3
3
  import { d as EvolutionLlmError, f as llmPort, m as projectionPort, p as modelRoute } from "../platform-CFA12Jam.js";
4
4
  import { n as toolsPort } from "../tools-DzcNFex2.js";
@@ -1038,7 +1038,7 @@ const readsStateSchema = z.object({ reads: z.array(z.object({
1038
1038
  failed: z.boolean(),
1039
1039
  file: z.string().nullable().optional(),
1040
1040
  tool: z.string().optional()
1041
- }).strict()) }).strict();
1041
+ }).strict()).max(512) }).strict();
1042
1042
  const signalsStateSchema = z.object({
1043
1043
  through: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
1044
1044
  lastEventTime: z.number().nonnegative().max(MAX_TIMESTAMP_MS),
@@ -1137,7 +1137,7 @@ const evolutionReadsProjection = {
1137
1137
  arguments: step.arguments,
1138
1138
  ok: step.outcome?.ok
1139
1139
  }) ?? null;
1140
- return { reads: [...state.reads, {
1140
+ return { reads: [...state.reads.slice(-511), {
1141
1141
  key: step.key,
1142
1142
  skill,
1143
1143
  failed: step.outcome?.ok === false
@@ -1,5 +1,5 @@
1
- import { a as nodeEvolutionIo, s as transactIo } from "./io-AmUf4lVY.js";
2
- import { B as supportFileReadFromPath, O as collectReadSkillNames, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, q as resolveCitations, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-EB7mUOlJ.js";
1
+ import { a as nodeEvolutionIo, s as transactIo } from "./io-BCBSr6Ot.js";
2
+ import { B as supportFileReadFromPath, O as collectReadSkillNames, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, q as resolveCitations, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-BhlDXqws.js";
3
3
  import { $ as UPSTREAM_LIMIT_CHARS_PER_TOKEN, P as DEFAULT_THREAT_MAX_SCAN_CHARS, X as SKILL_NAME_RE, a as DEFAULT_SKILL_LIMITS, d as CONTENT_SPLIT_HINT, t as clampedNumber, u as AUTHORING_SPLIT_LINE_CHARS } from "./numeric-DLeLvvGb.js";
4
4
  import { n as isRecord } from "./guards-3f02mnf2.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -906,18 +906,6 @@ function h2Sections(body) {
906
906
  for (const row of rows) row.count = rows.filter((other) => other.title === row.title).length;
907
907
  return rows;
908
908
  }
909
- /**
910
- * The sections a restructure proposal may name: heading unique, section non-empty. Derived from
911
- * `h2Sections`, i.e. from the SAME scan the store validates against.
912
- * @param body - the markdown after the frontmatter block.
913
- * @returns move-ready pairs in document order; empty when nothing qualifies.
914
- */
915
- function restructureCandidates(body) {
916
- return h2Sections(body).filter((section) => section.count === 1 && section.end > section.start + 1).map((section) => ({
917
- heading: section.title,
918
- toFile: "references/" + section.title.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, "-").replace(/^-+|-+$/g, "") + ".md"
919
- }));
920
- }
921
909
  //#endregion
922
910
  //#region lib/types/section-selection.js
923
911
  const LF$1 = String.fromCharCode(10);
@@ -1891,15 +1879,6 @@ function diffFindings(before, after) {
1891
1879
  resolved: before.filter((f) => !afterByRule.has(f.rule)).map((f) => f.rule)
1892
1880
  };
1893
1881
  }
1894
- /** Support files = markdown files under references/ (contract §4: unit frozen, underscore-prefixed
1895
- * excluded). Paths are supplied by the caller — this module never touches the filesystem. */
1896
- function countReferenceFiles(paths) {
1897
- return paths.filter((p) => {
1898
- const n = p.replace(/\\/g, "/");
1899
- if (!(n.includes("/references/") || n.startsWith("references/")) || !n.endsWith(".md")) return false;
1900
- return !n.slice(n.lastIndexOf("/") + 1).startsWith("_");
1901
- }).length;
1902
- }
1903
1882
  //#endregion
1904
1883
  //#region lib/types/evolution-events.js
1905
1884
  /**
@@ -2941,4 +2920,4 @@ function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS)
2941
2920
  };
2942
2921
  }
2943
2922
  //#endregion
2944
- export { bumpUse as $, listEventArchives as A, normalizeFrontmatter as At, COST_ASCII_TOKEN_LOW as B, describeReferenceRewrite as Bt, EVENT_ARCHIVE_PREFIX as C, readingStats as Ct, appendEvolutionEvent as D, exceedsContentLimit as Dt, EVENT_LOG_VERSION as E, ensureSkillFrontmatter as Et, RULES as F, validateFrontmatter as Ft, bodyCost as G, isUnreadWrite as Gt, COST_CJK_TOKEN_LOW as H, planRehoming as Ht, countReferenceFiles as I, yamlPlainScalarNeedsQuotes as It, SUPPRESSED_FILE_VERSION as J, DEFAULT_WRITE_CONFIRM_MODE as Jt, tokenLineFor as K, sessionReadSkillNames as Kt, diffFindings as L, externalRefs as Lt, readEvolutionEvents as M, relatedSkillNames as Mt, readEvolutionTimeline as N, shrinksOverLimit as Nt, eventsFile as O, frontmatterBlock as Ot, retainEventArchives as P, skillMdOnDisk as Pt, bumpSupportRead as Q, lintSkill as R, supportRefs as Rt, trimPatternBoundaries as S, h2Sections as St, EVENT_LOG_ROTATE_AT as T, authoringFeedback as Tt, TOKEN_ASCII_WEIGHT as U, READ_REQUIRED_ACTIONS as Ut, COST_CJK_TOKEN_HIGH as V, planReferenceRewrite as Vt, TOKEN_CJK_WEIGHT as W, filterUnreadSkillOps as Wt, applyCuratorMetaFields as X, authorityFrom as Xt, applyCuratorLifecycleFields as Y, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as Yt, bumpPatch as Z, scanThreats as _, usageObserved as _t, lintBody as a, idleDays as at, FUZZY_MAX_WORK as b, selectSections as bt, clearReviewChannel as c, loadUsage as ct, sweepReviewChannelSessions as d, normalizeUsageRecord as dt, bumpView as et, PATTERN_OVERLAP as f, saveSuppressedNames as ft, scanMemoryThreats as g, usageFile as gt, scanContentThreats as h, updateSuppressedNames as ht, assessStructureHealth as i, getRecord as it, parseEvolutionEvents as j, parseFrontmatter as jt, evolutionEventPayloadIssue as k, frontmatterCatalogInvalid as kt, isReviewChannelSession as l, markAgentCreated as lt, evaluateThreat as m, suppressedFile as mt, HEALTH_STAMP_RE as n, emptyRecord as nt, currentReviewContext as o, latestActivityAt as ot, THREAT_EXEMPTION_HINT as p, saveUsage as pt, MAX_SUPPORT_READ_PATHS as q, sessionReadSupportFiles as qt, MIN_STAMP_BODY_CHARS as r, foldCuratorFields as rt, withReviewContext as s, loadSuppressedNames as st, DEFAULT_HEALTH_THRESHOLDS as t, daysSinceIso as tt, markReviewChannel as u, mutateUsage as ut, makeSerialQueue as v, planExtract as vt, EVENT_LOG_RETAIN_ARCHIVES as w, restructureCandidates as wt, fuzzyPatch as x, displayBodyOf as xt, FUZZY_MAX_PATTERN_CHARS as y, projectExtractBodies as yt, COST_ASCII_TOKEN_HIGH as z, applyReferenceRewrite as zt };
2923
+ export { bumpView as $, listEventArchives as A, relatedSkillNames as At, COST_CJK_TOKEN_HIGH as B, planRehoming as Bt, EVENT_ARCHIVE_PREFIX as C, authoringFeedback as Ct, appendEvolutionEvent as D, frontmatterCatalogInvalid as Dt, EVENT_LOG_VERSION as E, frontmatterBlock as Et, RULES as F, externalRefs as Ft, tokenLineFor as G, sessionReadSupportFiles as Gt, TOKEN_ASCII_WEIGHT as H, filterUnreadSkillOps as Ht, diffFindings as I, supportRefs as It, applyCuratorLifecycleFields as J, authorityFrom as Jt, MAX_SUPPORT_READ_PATHS as K, DEFAULT_WRITE_CONFIRM_MODE as Kt, lintSkill as L, applyReferenceRewrite as Lt, readEvolutionEvents as M, skillMdOnDisk as Mt, readEvolutionTimeline as N, validateFrontmatter as Nt, eventsFile as O, normalizeFrontmatter as Ot, retainEventArchives as P, yamlPlainScalarNeedsQuotes as Pt, bumpUse as Q, COST_ASCII_TOKEN_HIGH as R, describeReferenceRewrite as Rt, trimPatternBoundaries as S, readingStats as St, EVENT_LOG_ROTATE_AT as T, exceedsContentLimit as Tt, TOKEN_CJK_WEIGHT as U, isUnreadWrite as Ut, COST_CJK_TOKEN_LOW as V, READ_REQUIRED_ACTIONS as Vt, bodyCost as W, sessionReadSkillNames as Wt, bumpPatch as X, applyCuratorMetaFields as Y, bumpSupportRead as Z, scanThreats as _, planExtract as _t, lintBody as a, latestActivityAt as at, FUZZY_MAX_WORK as b, displayBodyOf as bt, clearReviewChannel as c, markAgentCreated as ct, sweepReviewChannelSessions as d, saveSuppressedNames as dt, daysSinceIso as et, PATTERN_OVERLAP as f, saveUsage as ft, scanMemoryThreats as g, usageObserved as gt, scanContentThreats as h, usageFile as ht, assessStructureHealth as i, idleDays as it, parseEvolutionEvents as j, shrinksOverLimit as jt, evolutionEventPayloadIssue as k, parseFrontmatter as kt, isReviewChannelSession as l, mutateUsage as lt, evaluateThreat as m, updateSuppressedNames as mt, HEALTH_STAMP_RE as n, foldCuratorFields as nt, currentReviewContext as o, loadSuppressedNames as ot, THREAT_EXEMPTION_HINT as p, suppressedFile as pt, SUPPRESSED_FILE_VERSION as q, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as qt, MIN_STAMP_BODY_CHARS as r, getRecord as rt, withReviewContext as s, loadUsage as st, DEFAULT_HEALTH_THRESHOLDS as t, emptyRecord as tt, markReviewChannel as u, normalizeUsageRecord as ut, makeSerialQueue as v, projectExtractBodies as vt, EVENT_LOG_RETAIN_ARCHIVES as w, ensureSkillFrontmatter as wt, fuzzyPatch as x, h2Sections as xt, FUZZY_MAX_PATTERN_CHARS as y, selectSections as yt, COST_ASCII_TOKEN_LOW as z, planReferenceRewrite as zt };
@@ -1,5 +1,5 @@
1
- import { S as probeText, h as isUnknown, i as isProcessAlive, m as isPresent, r as isCommittedWarning, s as transactIo } from "./io-AmUf4lVY.js";
2
- import { r as contentHash } from "./mutations-DwvbjRHF.js";
1
+ import { f as isPresent, i as isProcessAlive, p as isUnknown, r as isCommittedWarning, s as transactIo, y as probeText } from "./io-BCBSr6Ot.js";
2
+ import { r as contentHash } from "./mutations-DihgpfgG.js";
3
3
  import { basename, dirname, isAbsolute, join, relative } from "node:path";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  //#region lib/types/write-kernel.js
@@ -846,8 +846,12 @@ var MutationUnit = class {
846
846
  const op = snapshot.ops.find((entry) => entry.target === target);
847
847
  if (op === void 0) continue;
848
848
  try {
849
- if (op.after === null) await this.io.remove(target);
850
- else await this.io.writeText(target, op.after);
849
+ const restored = await this.kernel.restore({
850
+ path: target,
851
+ before: op.after,
852
+ after: op.before
853
+ });
854
+ if (!restored.ok) throw new Error(restored.errors[0]?.message ?? "compensation blocked: " + target);
851
855
  } catch {}
852
856
  }
853
857
  return {
@@ -983,8 +987,7 @@ function unitIndexPath(home) {
983
987
  async function writeUnitSnapshot(io, home, snapshot, scope = "merge") {
984
988
  const path = unitSnapshotPath(home, snapshot.unitId, scope);
985
989
  const content = JSON.stringify(snapshot, null, 2) + "\n";
986
- if (io.transact !== void 0) await io.transact(path, () => content);
987
- else await io.writeText(path, content);
990
+ await transactIo(io, path, () => content);
988
991
  return path;
989
992
  }
990
993
  async function readUnitSnapshot(io, home, unitId, scope = "merge") {
@@ -999,8 +1002,7 @@ async function readUnitSnapshot(io, home, unitId, scope = "merge") {
999
1002
  async function writeUnitEvidence(io, home, evidence) {
1000
1003
  const path = unitEvidencePath(home, evidence.unitId);
1001
1004
  const content = JSON.stringify(evidence, null, 2) + "\n";
1002
- if (io.transact !== void 0) await io.transact(path, () => content);
1003
- else await io.writeText(path, content);
1005
+ await transactIo(io, path, () => content);
1004
1006
  await upsertUnitIndex(io, home, {
1005
1007
  unitId: evidence.unitId,
1006
1008
  storageKey: unitStorageKey(evidence.unitId),
@@ -1045,8 +1047,7 @@ async function upsertUnitIndex(io, home, entry) {
1045
1047
  entries: next
1046
1048
  }, null, 2) + "\n";
1047
1049
  };
1048
- if (io.transact !== void 0) await io.transact(path, content);
1049
- else await io.writeText(path, content(await io.readText(path)));
1050
+ await transactIo(io, path, content);
1050
1051
  }
1051
1052
  function unitReceiptPath(home, unitId) {
1052
1053
  return join(home, "merge", "unit-receipts", unitStorageKey(unitId) + ".json");
@@ -1054,8 +1055,7 @@ function unitReceiptPath(home, unitId) {
1054
1055
  async function writeUnitReceipt(io, home, receipt) {
1055
1056
  const path = unitReceiptPath(home, receipt.unitId);
1056
1057
  const text = JSON.stringify(receipt, null, 2) + "\n";
1057
- if (io.transact !== void 0) await io.transact(path, () => text);
1058
- else await io.writeText(path, text);
1058
+ await transactIo(io, path, () => text);
1059
1059
  return path;
1060
1060
  }
1061
1061
  async function readUnitReceipt(io, home, unitId) {
@@ -1102,8 +1102,7 @@ async function writeUnitJournal(io, home, journal, scope = "merge") {
1102
1102
  const existing = await readUnitJournal(io, home, key, scope);
1103
1103
  if (existing !== null) assertUnitJournalTransition(existing.phase, journal.phase);
1104
1104
  const content = JSON.stringify(journal, null, 2) + "\n";
1105
- if (io.transact !== void 0) await io.transact(path, () => content);
1106
- else await io.writeText(path, content);
1105
+ await transactIo(io, path, () => content);
1107
1106
  return path;
1108
1107
  }
1109
1108
  async function readUnitJournal(io, home, unitId, scope = "merge") {
@@ -1824,45 +1823,6 @@ function textDiffFacts(before, after, path, maxLines = 40) {
1824
1823
  truncated: oldWindow.cut || newWindow.cut
1825
1824
  };
1826
1825
  }
1827
- /** Characters one generated summary may carry. */
1828
- const VERSION_SUMMARY_MAX_CHARS = 80;
1829
- /**
1830
- * The fixed prompt the optional per-write summarizer runs (registry `skillVersionSummary`).
1831
- *
1832
- * Model-visible, so it is written from the model’s perspective and pinned: the tests assert that it
1833
- * carries the skill name, the character cap and both bodies, because a silent change to a prompt is a
1834
- * silent change to what every recorded version says.
1835
- * @param input - the skill, the action, and the two bodies (null when absent).
1836
- * @returns the prompt text.
1837
- */
1838
- function versionSummaryPrompt(input) {
1839
- return [
1840
- "You are writing ONE line that tells a reader what this single edit to the agent skill",
1841
- "\"" + input.name + "\" changed. The edit action was \"" + input.action + "\".",
1842
- "Rules: at most " + String(80) + " characters; the same language as the body;",
1843
- "name the decision, number or section that moved (for example \"keeps 30 days instead of 90 days\");",
1844
- "never say merely that something changed; no preamble, quotes, markdown or trailing period.",
1845
- "",
1846
- "Body BEFORE the edit:",
1847
- input.before ?? "(the skill did not exist before this edit)",
1848
- "",
1849
- "Body AFTER the edit:",
1850
- input.after ?? "(the skill does not exist after this edit)"
1851
- ].join("\n");
1852
- }
1853
- /**
1854
- * Reduce a model answer to the one line the index stores.
1855
- * @param raw - the model’s answer, whatever shape it came in.
1856
- * @param maxChars - the character cap.
1857
- * @returns the one line, or undefined when there is nothing usable (callers store no summary).
1858
- */
1859
- function normalizeVersionSummary(raw, maxChars = 80) {
1860
- const firstLine = raw.split("\n").map((line) => line.trim()).find((line) => line !== "");
1861
- if (firstLine === void 0) return void 0;
1862
- const stripped = firstLine.replace(/^["'`*•s]+/u, "").replace(/["'`*s]+$/u, "").replace(/[。.]$/u, "").trim();
1863
- if (stripped === "") return void 0;
1864
- return stripped.length > maxChars ? stripped.slice(0, maxChars - 1) + "…" : stripped;
1865
- }
1866
1826
  /**
1867
1827
  * How long ago an ISO timestamp was, as a bucket plus a count — never as a sentence.
1868
1828
  *
@@ -1910,4 +1870,4 @@ function elapsedSince(at, nowMs) {
1910
1870
  };
1911
1871
  }
1912
1872
  //#endregion
1913
- export { writeUnitSnapshot as $, unitJournalPort as A, readUnitEvidence as B, readHistoryIndex as C, versionSummaryPrompt as D, versionActionKind as E, readUnitJournal as F, unitIndexPath as G, readUnitReceipt as H, unitJournalPath as I, unitSnapshotsDir as J, unitReceiptPath as K, unitJournalPhaseRank as L, UNIT_JOURNAL_PHASES as M, UNIT_JOURNAL_SCHEMA_VERSION as N, versionTarget as O, assertUnitJournalTransition as P, writeUnitReceipt as Q, writeUnitJournal as R, partitionVersions as S, textDiffFacts as T, readUnitSnapshot as U, readUnitIndex as V, unitEvidencePath as W, upsertUnitIndex as X, unitStorageKey as Y, writeUnitEvidence as Z, loadVersions as _, RETENTION_FEEDBACK_MIN_CHARS as a, orderVersions as b, VERSION_SUMMARY_MAX_CHARS as c, elapsedSince as d, MutationUnit as et, entryTarget as f, loadVersionContent as g, latestVersionAt as h, RETENTION_FEEDBACK_KEEP_RATIO as i, unitSnapshotPort as j, pruneTreeChangeUnits as k, blobPath as l, historyRoot as m, HISTORY_DIR as n, validateMutationRequest as nt, TEXT_DIFF_MAX_CHARS as o, historyIndexFile as p, unitSnapshotPath as q, HISTORY_INDEX_VERSION as r, WriteKernel as rt, TEXT_DIFF_MAX_LINES as s, BASELINE_ACTION as t, fileMutationLock as tt, contentRetentionFeedback as u, nextHistoryIndex as v, recordVersions as w, parseHistoryIndex as x, normalizeVersionSummary as y, UNIT_STORAGE_SCHEMA_VERSION as z };
1873
+ export { validateMutationRequest as $, UNIT_JOURNAL_SCHEMA_VERSION as A, readUnitSnapshot as B, textDiffFacts as C, unitJournalPort as D, pruneTreeChangeUnits as E, writeUnitJournal as F, unitSnapshotsDir as G, unitIndexPath as H, UNIT_STORAGE_SCHEMA_VERSION as I, writeUnitEvidence as J, unitStorageKey as K, readUnitEvidence as L, readUnitJournal as M, unitJournalPath as N, unitSnapshotPort as O, unitJournalPhaseRank as P, fileMutationLock as Q, readUnitIndex as R, recordVersions as S, versionTarget as T, unitReceiptPath as U, unitEvidencePath as V, unitSnapshotPath as W, writeUnitSnapshot as X, writeUnitReceipt as Y, MutationUnit as Z, nextHistoryIndex as _, RETENTION_FEEDBACK_MIN_CHARS as a, partitionVersions as b, blobPath as c, entryTarget as d, WriteKernel as et, historyIndexFile as f, loadVersions as g, loadVersionContent as h, RETENTION_FEEDBACK_KEEP_RATIO as i, assertUnitJournalTransition as j, UNIT_JOURNAL_PHASES as k, contentRetentionFeedback as l, latestVersionAt as m, HISTORY_DIR as n, TEXT_DIFF_MAX_CHARS as o, historyRoot as p, upsertUnitIndex as q, HISTORY_INDEX_VERSION as r, TEXT_DIFF_MAX_LINES as s, BASELINE_ACTION as t, elapsedSince as u, orderVersions as v, versionActionKind as w, readHistoryIndex as x, parseHistoryIndex as y, readUnitReceipt as z };
package/lib/skills.js CHANGED
@@ -1,10 +1,10 @@
1
- import { C as probeUnknown, S as probeText, _ as probeAbsent, a as nodeEvolutionIo, b as probePresent, f as isAbsent, h as isUnknown, m as isPresent, r as isCommittedWarning, s as transactIo, v as probeList, x as probeReason, y as probeMtime } from "./io-AmUf4lVY.js";
2
- import { l as evolutionRoot, n as mutationLockFrom } from "./mutation-authority-DeJ_Wz14.js";
3
- import { q as resolveCitations } from "./session-projection-EB7mUOlJ.js";
1
+ import { _ as probePresent, a as nodeEvolutionIo, b as probeUnknown, f as isPresent, g as probeMtime, h as probeList, m as probeAbsent, p as isUnknown, r as isCommittedWarning, s as transactIo, u as isAbsent, v as probeReason, y as probeText } from "./io-BCBSr6Ot.js";
2
+ import { l as evolutionRoot, n as mutationLockFrom } from "./mutation-authority-CM6wRgyK.js";
3
+ import { q as resolveCitations } from "./session-projection-BhlDXqws.js";
4
4
  import { X as SKILL_NAME_RE, Z as SUPPORT_DIRS, a as DEFAULT_SKILL_LIMITS, c as policyStageLimits, d as CONTENT_SPLIT_HINT, i as DEFAULT_REFERENCE_REWRITE_POLICY, n as DEFAULT_ARCHIVE_RETENTION_POLICY, o as DEFAULT_SUPPORT_FILE_CHAR_POLICY, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_CITATION_POLICY, s as POLICY_STAGE_DEFAULTS } from "./numeric-DLeLvvGb.js";
5
- import { At as normalizeFrontmatter, Bt as describeReferenceRewrite, D as appendEvolutionEvent, Dt as exceedsContentLimit, Et as ensureSkillFrontmatter, F as RULES, Ft as validateFrontmatter, Gt as isUnreadWrite, Ht as planRehoming, I as countReferenceFiles, It as yamlPlainScalarNeedsQuotes, Kt as sessionReadSkillNames, L as diffFindings, Mt as relatedSkillNames, Nt as shrinksOverLimit, O as eventsFile, Ot as frontmatterBlock, Pt as skillMdOnDisk, R as lintSkill, Rt as supportRefs, S as trimPatternBoundaries, Tt as authoringFeedback, Ut as READ_REQUIRED_ACTIONS, Vt as planReferenceRewrite, Wt as filterUnreadSkillOps, Xt as authorityFrom, a as lintBody, bt as selectSections, ct as loadUsage, gt as usageFile, h as scanContentThreats, i as assessStructureHealth, it as getRecord, jt as parseFrontmatter, kt as frontmatterCatalogInvalid, l as isReviewChannelSession, mt as suppressedFile, n as HEALTH_STAMP_RE, o as currentReviewContext, qt as sessionReadSupportFiles, r as MIN_STAMP_BODY_CHARS, t as DEFAULT_HEALTH_THRESHOLDS, ut as mutateUsage, v as makeSerialQueue, x as fuzzyPatch, yt as projectExtractBodies, zt as applyReferenceRewrite } from "./skill-health-D1pZGk5V.js";
6
- import { i as loadMutations, o as recordMutation, r as contentHash } from "./mutations-DwvbjRHF.js";
7
- import { A as unitJournalPort, C as readHistoryIndex, D as versionSummaryPrompt, E as versionActionKind, O as versionTarget, S as partitionVersions, T as textDiffFacts, _ as loadVersions, a as RETENTION_FEEDBACK_MIN_CHARS, b as orderVersions, c as VERSION_SUMMARY_MAX_CHARS, d as elapsedSince, et as MutationUnit, f as entryTarget, g as loadVersionContent, h as latestVersionAt, i as RETENTION_FEEDBACK_KEEP_RATIO, j as unitSnapshotPort, k as pruneTreeChangeUnits, l as blobPath, m as historyRoot, n as HISTORY_DIR, o as TEXT_DIFF_MAX_CHARS, p as historyIndexFile, r as HISTORY_INDEX_VERSION, s as TEXT_DIFF_MAX_LINES, t as BASELINE_ACTION, tt as fileMutationLock, u as contentRetentionFeedback, v as nextHistoryIndex, w as recordVersions, x as parseHistoryIndex, y as normalizeVersionSummary } from "./skill-history-CjypdYqv.js";
5
+ import { At as relatedSkillNames, Bt as planRehoming, Ct as authoringFeedback, D as appendEvolutionEvent, Dt as frontmatterCatalogInvalid, Et as frontmatterBlock, F as RULES, Gt as sessionReadSupportFiles, Ht as filterUnreadSkillOps, I as diffFindings, It as supportRefs, Jt as authorityFrom, L as lintSkill, Lt as applyReferenceRewrite, Mt as skillMdOnDisk, Nt as validateFrontmatter, O as eventsFile, Ot as normalizeFrontmatter, Pt as yamlPlainScalarNeedsQuotes, Rt as describeReferenceRewrite, S as trimPatternBoundaries, Tt as exceedsContentLimit, Ut as isUnreadWrite, Vt as READ_REQUIRED_ACTIONS, Wt as sessionReadSkillNames, a as lintBody, h as scanContentThreats, ht as usageFile, i as assessStructureHealth, jt as shrinksOverLimit, kt as parseFrontmatter, l as isReviewChannelSession, lt as mutateUsage, n as HEALTH_STAMP_RE, o as currentReviewContext, pt as suppressedFile, r as MIN_STAMP_BODY_CHARS, rt as getRecord, st as loadUsage, t as DEFAULT_HEALTH_THRESHOLDS, v as makeSerialQueue, vt as projectExtractBodies, wt as ensureSkillFrontmatter, x as fuzzyPatch, yt as selectSections, zt as planReferenceRewrite } from "./skill-health-BzkUQDi7.js";
6
+ import { i as loadMutations, o as recordMutation, r as contentHash } from "./mutations-DihgpfgG.js";
7
+ import { C as textDiffFacts, D as unitJournalPort, E as pruneTreeChangeUnits, O as unitSnapshotPort, Q as fileMutationLock, S as recordVersions, T as versionTarget, Z as MutationUnit, _ as nextHistoryIndex, a as RETENTION_FEEDBACK_MIN_CHARS, b as partitionVersions, c as blobPath, d as entryTarget, f as historyIndexFile, g as loadVersions, h as loadVersionContent, i as RETENTION_FEEDBACK_KEEP_RATIO, l as contentRetentionFeedback, m as latestVersionAt, n as HISTORY_DIR, o as TEXT_DIFF_MAX_CHARS, p as historyRoot, r as HISTORY_INDEX_VERSION, s as TEXT_DIFF_MAX_LINES, t as BASELINE_ACTION, u as elapsedSince, v as orderVersions, w as versionActionKind, x as readHistoryIndex, y as parseHistoryIndex } from "./skill-history-RWt1-kbZ.js";
8
8
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
9
9
  //#region lib/types/skill-row-cells.js
10
10
  /**
@@ -4067,4 +4067,4 @@ function newSkillLibrary(options) {
4067
4067
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
4068
4068
  }
4069
4069
  //#endregion
4070
- export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, 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, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, VERSION_SUMMARY_MAX_CHARS, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, contentRetentionFeedback, countReferenceFiles, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, newSkillLibrary, nextHistoryIndex, normalizeFrontmatter, normalizeVersionSummary, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, versionActionKind, versionRowCells, versionSummaryPrompt, versionTarget, yamlPlainScalarNeedsQuotes };
4070
+ export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, 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, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, contentRetentionFeedback, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, newSkillLibrary, nextHistoryIndex, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
@@ -1,11 +1,8 @@
1
- import { h as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-C5Mo1dbB.js";
1
+ import { m as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-CAjLGd9f.js";
2
2
  //#region lib/types/subagent/readiness.js
3
3
  function serviceOf$1(ctx, name) {
4
4
  return ctx.get(name);
5
5
  }
6
- function kindOf(kind) {
7
- return kind === "reviewer" ? "reviewer" : "maintainer";
8
- }
9
6
  /** Pure derivation (no side effects): the doctor reads this, the channel re-probes on every run. */
10
7
  function probeChannelState(ctx, kind) {
11
8
  const subagents = serviceOf$1(ctx, "subagents");
@@ -40,14 +37,11 @@ function probeChannelState(ctx, kind) {
40
37
  kind: "available",
41
38
  provider: "spawn",
42
39
  preset: {
43
- id: restrictedPresetId(kindOf(kind)),
44
- registered: restrictedPresetState(ctx, kindOf(kind))?.kind === "ready"
40
+ id: restrictedPresetId(kind),
41
+ registered: restrictedPresetState(ctx, kind)?.kind === "ready"
45
42
  }
46
43
  };
47
44
  }
48
- function subagentChannelState(ctx, kind) {
49
- return probeChannelState(ctx, kind);
50
- }
51
45
  //#endregion
52
46
  //#region lib/types/subagent/channel.js
53
47
  function serviceOf(ctx, name) {
@@ -423,4 +417,4 @@ function createSubagentChannel(ctx) {
423
417
  };
424
418
  }
425
419
  //#endregion
426
- export { createSubagentChannel, probeChannelState, subagentChannelState };
420
+ export { createSubagentChannel, probeChannelState };
@@ -4,7 +4,6 @@ export declare const REVIEWER_PRESET_ID: "evolution-reviewer-readonly";
4
4
  export declare const MAINTAINER_PRESET_ID: "evolution-maintainer-readonly";
5
5
  export declare const RESTRICTED_TOOLS_ROW_ID: "evolution-restricted-tools";
6
6
  export declare const RESTRICTOR_MODULE: string;
7
- export declare const RESTRICTED_PRESET_DELIVERY: "runtime" | "installer";
8
7
  export interface RestrictedPresetDisplay {
9
8
  readonly name: string;
10
9
  readonly description: string;
@@ -6,7 +6,6 @@ export const REVIEWER_PRESET_ID = 'evolution-reviewer-readonly';
6
6
  export const MAINTAINER_PRESET_ID = 'evolution-maintainer-readonly';
7
7
  export const RESTRICTED_TOOLS_ROW_ID = 'evolution-restricted-tools';
8
8
  export const RESTRICTOR_MODULE = scopedPackageName('dsh-evolution-core/restrictor', import.meta.url);
9
- export const RESTRICTED_PRESET_DELIVERY = 'runtime';
10
9
  export const RESTRICTED_PRESET_DISPLAY = {
11
10
  reviewer: { name: 'evolution reviewer (read-only)', description: 'Internal restricted preset used by the family review channel.', order: 900 },
12
11
  maintainer: { name: 'evolution maintainer (read-only)', description: 'Internal restricted preset used by the family maintenance channel.', order: 901 },
@@ -7,7 +7,6 @@
7
7
  */
8
8
  import type { UsageMap, UsageRecord } from './usage.ts';
9
9
  import { EvolutionGateSet } from './gates.ts';
10
- export { PROTECTED_BUILTIN_SKILLS } from './constants.ts';
11
10
  export interface CuratorConfig {
12
11
  staleAfterDays: number;
13
12
  archiveAfterDays: number;
@@ -8,7 +8,6 @@
8
8
  import { daysSinceIso, idleDays } from "./usage.js";
9
9
  import { createGateSet } from "./gates.js";
10
10
  import { PROTECTED_BUILTIN_SKILLS, SKILL_NAME_RE } from "./constants.js";
11
- export { PROTECTED_BUILTIN_SKILLS } from "./constants.js";
12
11
  export function buildCuratorRunReport(input) {
13
12
  return {
14
13
  schemaVersion: 1,
@@ -41,16 +41,4 @@ export interface H2Section {
41
41
  * @returns one row per H2 heading, with `count` filled in a second pass.
42
42
  */
43
43
  export declare function h2Sections(body: string): H2Section[];
44
- /** One move the panel can hand to `restructure` without the store refusing it. */
45
- export interface RestructureCandidate {
46
- heading: string;
47
- toFile: string;
48
- }
49
- /**
50
- * The sections a restructure proposal may name: heading unique, section non-empty. Derived from
51
- * `h2Sections`, i.e. from the SAME scan the store validates against.
52
- * @param body - the markdown after the frontmatter block.
53
- * @returns move-ready pairs in document order; empty when nothing qualifies.
54
- */
55
- export declare function restructureCandidates(body: string): RestructureCandidate[];
56
44
  //# sourceMappingURL=document-body.d.ts.map
@@ -74,18 +74,4 @@ export function h2Sections(body) {
74
74
  row.count = rows.filter(other => other.title === row.title).length;
75
75
  return rows;
76
76
  }
77
- /**
78
- * The sections a restructure proposal may name: heading unique, section non-empty. Derived from
79
- * `h2Sections`, i.e. from the SAME scan the store validates against.
80
- * @param body - the markdown after the frontmatter block.
81
- * @returns move-ready pairs in document order; empty when nothing qualifies.
82
- */
83
- export function restructureCandidates(body) {
84
- return h2Sections(body)
85
- .filter(section => section.count === 1 && section.end > section.start + 1)
86
- .map(section => ({
87
- heading: section.title,
88
- toFile: 'references/' + section.title.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-').replace(/^-+|-+$/g, '') + '.md',
89
- }));
90
- }
91
77
  //# sourceMappingURL=document-body.js.map
@@ -65,10 +65,6 @@ export declare const HOST_ROUTES: {
65
65
  readonly diagnostics: {
66
66
  readonly view: "/api/dsh-evolution/diagnostics";
67
67
  };
68
- readonly settings: {
69
- readonly describe: "/api/dsh-evolution/settings/describe";
70
- readonly mutate: "/api/dsh-evolution/settings/mutate";
71
- };
72
68
  };
73
69
  export type HostSurface = {
74
70
  readonly available: true;
@@ -79,6 +75,15 @@ export type HostSurface = {
79
75
  readonly reason: 'connection-missing' | 'service-absent';
80
76
  };
81
77
  export declare function hostSurface(ctx: Context): HostSurface;
78
+ /**
79
+ * Register the family host surface on the platform's exact-route carrier.
80
+ *
81
+ * The platform owns admission (Host/Origin hygiene + browserAuth + exact-route owner peer) and the
82
+ * disposer is bound to the CALLING fiber, not the connection service: the connection service can
83
+ * outlive a reloaded family fiber, so the family must release its own registrations on dispose.
84
+ * Routes carry the audit snapshot taken at registration time (deployment-level facts only — the
85
+ * exact-route handler receives a Request, not the peer identity).
86
+ */
82
87
  export declare function registerHostRoutes(owner: Context, build: (audit: DecisionAudit) => readonly ConnectionFetchRouteLike[]): void;
83
88
  export declare function json(status: number, body: unknown): Response;
84
89
  export declare function methodNotAllowed(allowed: readonly HttpMethod[]): Response;
@@ -62,10 +62,6 @@ export const HOST_ROUTES = {
62
62
  diagnostics: {
63
63
  view: '/api/dsh-evolution/diagnostics',
64
64
  },
65
- settings: {
66
- describe: '/api/dsh-evolution/settings/describe',
67
- mutate: '/api/dsh-evolution/settings/mutate',
68
- },
69
65
  };
70
66
  export function hostSurface(ctx) {
71
67
  const connection = ctx.get('connection');
@@ -74,78 +70,15 @@ export function hostSurface(ctx) {
74
70
  const allows = connection.allowsRemoteAuthorities === true;
75
71
  return { available: true, allowsRemoteAuthorities: allows };
76
72
  }
77
- function isLoopback(address) {
78
- const value = address ?? '';
79
- return value === '127.0.0.1' || value === '::1' || value === '::ffff:127.0.0.1';
80
- }
81
- function sameOrigin(origin, host) {
82
- if (origin === undefined)
83
- return true;
84
- try {
85
- const parsed = new URL(origin);
86
- return isLoopback(parsed.hostname) && host !== undefined && parsed.host === host;
87
- }
88
- catch {
89
- return false;
90
- }
91
- }
92
- function nodeRoute(route) {
93
- return {
94
- kind: 'exact',
95
- path: route.path,
96
- handler: async (req, res) => {
97
- if (!isLoopback(req.socket.remoteAddress)) {
98
- res.statusCode = 403;
99
- res.end('forbidden');
100
- return;
101
- }
102
- if (!sameOrigin(req.headers.origin, req.headers.host)) {
103
- res.statusCode = 403;
104
- res.end('forbidden');
105
- return;
106
- }
107
- const fetchSite = req.headers['sec-fetch-site'];
108
- if (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none') {
109
- res.statusCode = 403;
110
- res.end('forbidden');
111
- return;
112
- }
113
- const method = req.method ?? 'GET';
114
- if (method !== 'GET' && method !== 'HEAD' && !(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
115
- res.statusCode = 415;
116
- res.end('json required');
117
- return;
118
- }
119
- try {
120
- const chunks = [];
121
- for await (const chunk of req)
122
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
123
- const headers = new Headers();
124
- for (const [key, value] of Object.entries(req.headers)) {
125
- if (value === undefined)
126
- continue;
127
- headers.set(key, Array.isArray(value) ? value.join(',') : value);
128
- }
129
- const request = new Request(new URL(req.url ?? '/', 'http://127.0.0.1'), {
130
- method,
131
- headers,
132
- ...(method === 'GET' || method === 'HEAD' || chunks.length === 0 ? {} : { body: Buffer.concat(chunks) }),
133
- });
134
- const response = await route.fetch(request);
135
- res.statusCode = response.status;
136
- response.headers.forEach((value, key) => { try {
137
- res.setHeader(key, value);
138
- }
139
- catch { /* ignore forbidden node header */ } });
140
- res.end(Buffer.from(await response.arrayBuffer()));
141
- }
142
- catch (error) {
143
- res.statusCode = 500;
144
- res.end(error instanceof Error ? error.message : String(error));
145
- }
146
- },
147
- };
148
- }
73
+ /**
74
+ * Register the family host surface on the platform's exact-route carrier.
75
+ *
76
+ * The platform owns admission (Host/Origin hygiene + browserAuth + exact-route owner peer) and the
77
+ * disposer is bound to the CALLING fiber, not the connection service: the connection service can
78
+ * outlive a reloaded family fiber, so the family must release its own registrations on dispose.
79
+ * Routes carry the audit snapshot taken at registration time (deployment-level facts only — the
80
+ * exact-route handler receives a Request, not the peer identity).
81
+ */
149
82
  export function registerHostRoutes(owner, build) {
150
83
  const injecting = owner;
151
84
  if (typeof injecting.inject !== 'function')
@@ -166,50 +99,37 @@ export function registerHostRoutes(owner, build) {
166
99
  const effect = scope.effect;
167
100
  if (typeof effect !== 'function')
168
101
  throw new Error('connection scope has no effect() to own the registration');
169
- if (connection?.fetch !== undefined && typeof connection.fetch.register === 'function') {
170
- const register = connection.fetch.register.bind(connection.fetch);
171
- effect.call(scope, () => {
172
- const disposers = [];
173
- try {
174
- for (const route of routes)
175
- disposers.push(register(route));
176
- }
177
- catch (error) {
178
- for (const dispose of disposers) {
179
- try {
180
- void dispose();
181
- }
182
- catch { /* best-effort rollback */ }
102
+ // Phase 0 #3 (W11): 0.2.2-rc.0 is not a published line for @deepseek-ai/dsh; the earliest
103
+ // installable platform (rc.1) always carries connection.fetch. A missing register is an
104
+ // assembly error, not a reason to fall back to a loopback webserver bridge — that bridge was
105
+ // the second admission path the audit found (G4 had already deleted the fence it duplicated).
106
+ if (connection?.fetch === undefined || typeof connection.fetch.register !== 'function') {
107
+ throw new Error('connection.fetch.register() is required to register family host routes (platform >= 0.2.2-rc.1); no fallback admission path exists');
108
+ }
109
+ const register = connection.fetch.register.bind(connection.fetch);
110
+ effect.call(scope, () => {
111
+ const disposers = [];
112
+ try {
113
+ for (const route of routes)
114
+ disposers.push(register(route));
115
+ }
116
+ catch (error) {
117
+ for (const dispose of disposers) {
118
+ try {
119
+ void dispose();
183
120
  }
184
- throw error;
121
+ catch { /* best-effort rollback */ }
185
122
  }
186
- return () => {
187
- for (const dispose of disposers) {
188
- try {
189
- void dispose();
190
- }
191
- catch { /* a failed disposer must not mask the others */ }
123
+ throw error;
124
+ }
125
+ return () => {
126
+ for (const dispose of disposers) {
127
+ try {
128
+ void dispose();
192
129
  }
193
- };
194
- }, 'evolution-host-routes');
195
- return;
196
- }
197
- // Platform 0.2.x moved Host data-plane registration to connection.rpc. The family
198
- // HTTP contract stays exact paths; a loopback-only webserver bridge preserves it
199
- // without exposing these routes to remote authorities.
200
- const web = (scope.get?.('webServer')
201
- ?? owner.get?.('webServer'));
202
- if (web === undefined || typeof web.register !== 'function') {
203
- throw new Error('connection service has no fetch.register(), and webServer is not mounted for the loopback host-route bridge');
204
- }
205
- effect.call(scope, () => {
206
- const disposers = routes.map(route => web.register(nodeRoute(route)));
207
- return () => { for (const dispose of disposers) {
208
- try {
209
- dispose();
130
+ catch { /* a failed disposer must not mask the others */ }
210
131
  }
211
- catch { /* best-effort */ }
212
- } };
132
+ };
213
133
  }, 'evolution-host-routes');
214
134
  });
215
135
  }