@lmzhen/dsh-evolution-core 0.48.0 → 0.50.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 (97) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-Cqjbho0t.js → composition-DA8XPfMc.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-Bx4ksgJk.js} +15 -5
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-Bru3c9ec.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +41 -822
  12. package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
  13. package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
  14. package/lib/numeric-Dc53KQoe.js +43 -0
  15. package/lib/platform/index.js +4 -3
  16. package/lib/platform-DyHnHUmQ.js +251 -0
  17. package/lib/policy.js +3 -2
  18. package/lib/quality-WAU6YatF.js +554 -0
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +33 -0
  21. package/lib/runtime/plugin.js +97 -43
  22. package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
  23. package/lib/skill-health-Bl-MdXZ4.js +1409 -0
  24. package/lib/skills.js +7 -4
  25. package/lib/state-store-Jpa-iYIZ.js +54 -0
  26. package/lib/subagent/index.js +214 -176
  27. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  28. package/lib/types/composition/ensure.js +21 -7
  29. package/lib/types/extract-plan.d.ts +2 -0
  30. package/lib/types/extract.d.ts +12 -0
  31. package/lib/types/extract.js +12 -0
  32. package/lib/types/http-routes.js +32 -9
  33. package/lib/types/index.d.ts +0 -3
  34. package/lib/types/index.js +0 -3
  35. package/lib/types/long-runs.d.ts +0 -5
  36. package/lib/types/long-runs.js +0 -7
  37. package/lib/types/opt-in.js +4 -3
  38. package/lib/types/params.js +2 -1
  39. package/lib/types/platform/agents.d.ts +32 -0
  40. package/lib/types/platform/agents.js +26 -0
  41. package/lib/types/platform/commands.d.ts +14 -0
  42. package/lib/types/platform/commands.js +9 -0
  43. package/lib/types/platform/connection.d.ts +26 -0
  44. package/lib/types/platform/connection.js +27 -0
  45. package/lib/types/platform/index.d.ts +26 -0
  46. package/lib/types/platform/index.js +13 -0
  47. package/lib/types/platform/llm.d.ts +3 -1
  48. package/lib/types/platform/llm.js +1 -0
  49. package/lib/types/platform/platformView.d.ts +21 -0
  50. package/lib/types/platform/platformView.js +29 -0
  51. package/lib/types/platform/profileContext.d.ts +16 -0
  52. package/lib/types/platform/profileContext.js +14 -0
  53. package/lib/types/platform/sessionQuery.d.ts +14 -0
  54. package/lib/types/platform/sessionQuery.js +9 -0
  55. package/lib/types/platform/settings.d.ts +22 -0
  56. package/lib/types/platform/settings.js +14 -0
  57. package/lib/types/platform/skills.d.ts +16 -0
  58. package/lib/types/platform/skills.js +9 -0
  59. package/lib/types/platform/storageDomain.d.ts +13 -0
  60. package/lib/types/platform/storageDomain.js +9 -0
  61. package/lib/types/platform/subagents.d.ts +25 -0
  62. package/lib/types/platform/subagents.js +17 -0
  63. package/lib/types/platform/systemPrompt.d.ts +16 -0
  64. package/lib/types/platform/systemPrompt.js +13 -0
  65. package/lib/types/platform/tools.d.ts +4 -0
  66. package/lib/types/platform/tools.js +2 -0
  67. package/lib/types/platform/userQuestions.d.ts +33 -0
  68. package/lib/types/platform/userQuestions.js +9 -0
  69. package/lib/types/platform/workingDirectory.d.ts +14 -0
  70. package/lib/types/platform/workingDirectory.js +9 -0
  71. package/lib/types/platform-line.generated.d.ts +5 -5
  72. package/lib/types/platform-line.generated.js +5 -5
  73. package/lib/types/platform-services.js +3 -0
  74. package/lib/types/result.d.ts +35 -0
  75. package/lib/types/result.js +25 -0
  76. package/lib/types/runtime/llm.d.ts +2 -2
  77. package/lib/types/runtime/llm.js +5 -8
  78. package/lib/types/runtime/platform.d.ts +37 -4
  79. package/lib/types/runtime/platform.js +40 -5
  80. package/lib/types/runtime/projections.d.ts +9 -4
  81. package/lib/types/runtime/projections.js +64 -28
  82. package/lib/types/subagent/channel.d.ts +1 -3
  83. package/lib/types/subagent/channel.js +2 -332
  84. package/lib/types/subagent/index.d.ts +2 -0
  85. package/lib/types/subagent/index.js +2 -0
  86. package/lib/types/subagent/kernel.d.ts +4 -0
  87. package/lib/types/subagent/kernel.js +234 -0
  88. package/lib/types/subagent/readiness.js +5 -7
  89. package/lib/types/subagent/run.d.ts +53 -0
  90. package/lib/types/subagent/run.js +125 -0
  91. package/lib/types/subagent/types.d.ts +2 -2
  92. package/lib/types/write-inventory.d.ts +0 -11
  93. package/lib/types/write-inventory.js +0 -16
  94. package/lib/usage-DdjIBAkm.js +1252 -0
  95. package/package.json +37 -25
  96. package/lib/platform-Cc9cNt5j.js +0 -111
  97. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -1,4 +1,5 @@
1
- import { c as evolutionHome, t as MutationAuthority } from "./mutation-authority-l57R626O.js";
1
+ import { t as MutationAuthority } from "./mutation-authority-DQfpXs1O.js";
2
+ import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
2
3
  //#region lib/types/authority-plugin.js
3
4
  const name = "evolution-authority";
4
5
  const inject = ["evolutionIo"];
@@ -0,0 +1,198 @@
1
+ //#region lib/types/citations.js
2
+ /**
3
+ * Citation resolution for skill bodies and support files (design §5.2).
4
+ *
5
+ * WHY this exists beside `supportRefs` (skill-store.ts): that scanner answers
6
+ * "does this text contain a path-shaped token", which is the right question
7
+ * when a package is being ARCHIVED — every such path may dangle — and the wrong
8
+ * one when a section is only being MOVED, where nothing leaves and the only
9
+ * thing that changes is the directory a citation is read from. Measured false
10
+ * positives of the token scan: a URL tail (`https://host/references/x.md`), a
11
+ * category path the original Hermes documents as legitimate
12
+ * (`skills/scripts/foo.py`), and a prose command line
13
+ * (`npm run scripts/build.mjs`).
14
+ *
15
+ * CONTRACT: a token whose path STARTS WITH a support directory is a citation of
16
+ * this skill and is resolved from the SKILL ROOT, in whichever file it is
17
+ * written. A token that merely contains a support directory further along its
18
+ * path belongs to something else: it is reported as `foreign` and never
19
+ * resolved.
20
+ *
21
+ * PURE: existence is decided against the caller's file list, so identical
22
+ * inputs always answer the same report.
23
+ */
24
+ /** Support directories that make a path a citation of the owning skill. */
25
+ const CITATION_SUPPORT_DIRS = [
26
+ "references",
27
+ "templates",
28
+ "scripts",
29
+ "assets"
30
+ ];
31
+ /** Scan budget: bounded so a pathological body cannot stall a maintenance run. */
32
+ const DEFAULT_CITATION_REF_BUDGET = 500;
33
+ /** Words that introduce an executable command rather than a citation. */
34
+ const PROSE_COMMAND_PREFIXES = [
35
+ "npm",
36
+ "pnpm",
37
+ "yarn",
38
+ "npx",
39
+ "node",
40
+ "python",
41
+ "python3",
42
+ "bash",
43
+ "sh",
44
+ "git",
45
+ "gh",
46
+ "run"
47
+ ];
48
+ const TOKEN_RE = /(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g;
49
+ const TOKEN_CHAR_RE = /[A-Za-z0-9._/-]/;
50
+ const FENCE_RE = /^\s*(`{3,}|~{3,})/;
51
+ const TRAILING_PUNCT_RE = /[.,;:]+$/;
52
+ /** A citation's final segment must look like \u0060name.ext\u0060: a bare \u0060.\u0060 or a dotless
53
+ * segment is a directory mention, not a file. */
54
+ const FILE_SEGMENT_RE = /^[^.].*\.[^.]+$/;
55
+ const FRAGMENT_RE = /^#([A-Za-z0-9._-]+)/;
56
+ /** Whether the token starting at `start` is the argument of a shell command. */
57
+ function isProseCommand(line, start) {
58
+ const head = line.slice(0, start).trimEnd();
59
+ if (head === "") return false;
60
+ const word = head.split(/\s+/).pop() ?? "";
61
+ return PROSE_COMMAND_PREFIXES.includes(word);
62
+ }
63
+ /** The token's final path segment (`references/a/b.md` -> `b.md`). */
64
+ function lastSegmentOf(target) {
65
+ return target.slice(target.lastIndexOf("/") + 1);
66
+ }
67
+ /** The token's parent directory within the skill (`references/a/b.md` -> `references/a`). */
68
+ function parentDirOf(target) {
69
+ const cut = target.lastIndexOf("/");
70
+ return cut <= 0 ? "" : target.slice(0, cut);
71
+ }
72
+ /** Classify one token by its first path segment. */
73
+ function classifyToken(token) {
74
+ const head = token.split("/")[0] ?? "";
75
+ return CITATION_SUPPORT_DIRS.includes(head) ? "citation" : "foreign";
76
+ }
77
+ /**
78
+ * Resolve every path-shaped token in `content`.
79
+ * @param input - content, the skill-root-relative path of its owner, the skill's
80
+ * file list, and an optional scan budget.
81
+ * @returns the refs plus the dangling and foreign subsets; `truncated` marks a
82
+ * report that stopped at the budget.
83
+ */
84
+ function resolveCitations(input) {
85
+ const budget = input.budget ?? 500;
86
+ const files = new Set(input.files.map((path) => path.replace(/\\/g, "/")));
87
+ const refs = [];
88
+ const seen = /* @__PURE__ */ new Set();
89
+ let truncated = false;
90
+ let fence = null;
91
+ const lines = input.content.split("\n");
92
+ for (let index = 0; index < lines.length && !truncated; index += 1) {
93
+ const rawLine = lines[index] ?? "";
94
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
95
+ const fenceMark = FENCE_RE.exec(line);
96
+ if (fenceMark) {
97
+ const marker = fenceMark[1] ?? "";
98
+ fence = fence === null ? marker.slice(0, 1) : null;
99
+ continue;
100
+ }
101
+ for (const match of line.matchAll(TOKEN_RE)) {
102
+ const matched = match[0];
103
+ const matchedAt = match.index;
104
+ let start = matchedAt;
105
+ while (start > 0 && TOKEN_CHAR_RE.test(line[start - 1] ?? "")) start -= 1;
106
+ const prefix = line.slice(0, start);
107
+ const tail = line.slice(matchedAt + matched.length);
108
+ const fragment = FRAGMENT_RE.exec(tail)?.[1];
109
+ const token = matched.replace(TRAILING_PUNCT_RE, "");
110
+ const scanned = line.slice(start, matchedAt + matched.length);
111
+ const classified = fence !== null ? "fence" : prefix.endsWith(":") && line.slice(start, start + 2) === "//" ? "url" : isProseCommand(line, start) ? "prose" : classifyToken(scanned);
112
+ const namesFile = !scanned.split("/").includes("..") && (FILE_SEGMENT_RE.test(lastSegmentOf(scanned)) || files.has(token));
113
+ const kind = classified === "citation" && !namesFile ? "prose" : classified;
114
+ const target = kind === "citation" ? token : null;
115
+ const key = `${index}|${kind}|${target ?? token}`;
116
+ if (seen.has(key)) continue;
117
+ seen.add(key);
118
+ refs.push({
119
+ raw: token,
120
+ line: index + 1,
121
+ target,
122
+ base: "root",
123
+ kind,
124
+ exists: target !== null && files.has(target),
125
+ ...fragment === void 0 ? {} : { fragment }
126
+ });
127
+ if (refs.length >= budget) {
128
+ truncated = true;
129
+ break;
130
+ }
131
+ }
132
+ }
133
+ const citations = refs.filter((ref) => ref.kind === "citation");
134
+ const undecidable = (ref) => {
135
+ const target = ref.target;
136
+ return target !== null && !ref.exists && files.has(parentDirOf(target));
137
+ };
138
+ return {
139
+ refs,
140
+ dangling: citations.filter((ref) => !ref.exists && !undecidable(ref)),
141
+ unverified: citations.filter(undecidable),
142
+ foreign: refs.filter((ref) => ref.kind !== "citation"),
143
+ truncated
144
+ };
145
+ }
146
+ /** The sanctioned body hook (design §5.6): a list item whose payload is
147
+ * exactly one support-file path, so the file stays discoverable in the body. */
148
+ const HOOK_LINE_RE = /^- [^\n]{1,60} → ((?:references|templates|scripts|assets)\/[a-z0-9][a-z0-9._/-]*)$/;
149
+ /** The retirement escape hatch (design §5.6): a standalone body comment that
150
+ * names the support file it exempts and the reason it must survive. The path
151
+ * is part of the marker because the proposal list is per FILE, and a reason is
152
+ * required — an unexplained exemption is what this hook exists to prevent. */
153
+ const KEEP_LINE_RE = /^<!--\s*keep:\s*((?:references|templates|scripts|assets)\/[a-z0-9][a-z0-9._/-]*)\s+(\S[^>]*?)\s*-->$/;
154
+ /** Whether a skill-relative path names a FILE rather than a directory: the same
155
+ * rule the scanner applies to a token's final segment (`name.ext`). The support
156
+ * listing is one level deep and includes directory entries (a real library has
157
+ * `references/archive`), which no pointer or retirement list may treat as a file.
158
+ * @param path - a skill-root-relative support path.
159
+ * @returns true when the final segment is file-shaped.
160
+ */
161
+ function isFileShapedPath(path) {
162
+ return FILE_SEGMENT_RE.test(path.slice(path.lastIndexOf("/") + 1));
163
+ }
164
+ /**
165
+ * Scan a body for sanctioned hooks and `keep` markers.
166
+ * @param content - the SKILL.md body (frontmatter included).
167
+ * @returns hook targets plus the `keep` reasons keyed by target.
168
+ */
169
+ function scanBodyHooks(content) {
170
+ const targets = [];
171
+ const seen = /* @__PURE__ */ new Set();
172
+ const kept = /* @__PURE__ */ new Map();
173
+ let fence = null;
174
+ for (const rawLine of content.split("\n")) {
175
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
176
+ const fenceMark = FENCE_RE.exec(line);
177
+ if (fenceMark) {
178
+ fence = fence === null ? (fenceMark[1] ?? "").slice(0, 1) : null;
179
+ continue;
180
+ }
181
+ if (fence !== null) continue;
182
+ const keep = KEEP_LINE_RE.exec(line);
183
+ if (keep?.[1] !== void 0) {
184
+ kept.set(keep[1], (keep[2] ?? "").trim());
185
+ continue;
186
+ }
187
+ const target = HOOK_LINE_RE.exec(line)?.[1];
188
+ if (target === void 0 || seen.has(target)) continue;
189
+ seen.add(target);
190
+ targets.push(target);
191
+ }
192
+ return {
193
+ targets,
194
+ kept
195
+ };
196
+ }
197
+ //#endregion
198
+ export { isFileShapedPath as a, KEEP_LINE_RE as i, DEFAULT_CITATION_REF_BUDGET as n, resolveCitations as o, HOOK_LINE_RE as r, scanBodyHooks as s, CITATION_SUPPORT_DIRS as t };
@@ -1,3 +1,3 @@
1
- import { a as entryListSchema, c as MAINTAINER_PRESET_ID, d as RESTRICTOR_MODULE, f as REVIEWER_PRESET_ID, i as composeRestrictedPresetDefinition, l as RESTRICTED_PRESET_DISPLAY, m as restrictedPresetId, n as ensureRestrictedPreset, o as parsePresetRows, p as normalizeAllow, r as restrictedPresetState, s as EVOLUTION_PRESET_IDS, t as disposeRestrictedPreset, u as RESTRICTED_TOOLS_ROW_ID } from "../ensure-CAjLGd9f.js";
2
- import { C as trimTrailingBlankLines, S as rowSiblingEnd, _ as presetRowId, a as composePresetComposition, b as resolveBasePresetPatch, c as composePresetRow, d as listDirectories, f as loadRowOverrides, g as presetRowBody, h as presetRowBlock, i as basePresetPlugins, l as compositionRowIds, m as presetPatchText, n as AGENT_PRESET_ROOT_HINT, o as composePresetEntry, p as mergePresetRow, r as EMPTY_PATCH_SEED, s as composePresetInsert, t as AGENT_PRESET_PACKAGE, u as denseBlockSequence, v as probeDesktopScope, x as rowBlockSpan, y as removePresetRow } from "../composition-Cqjbho0t.js";
1
+ import { a as entryListSchema, c as MAINTAINER_PRESET_ID, d as RESTRICTOR_MODULE, f as REVIEWER_PRESET_ID, i as composeRestrictedPresetDefinition, l as RESTRICTED_PRESET_DISPLAY, m as restrictedPresetId, n as ensureRestrictedPreset, o as parsePresetRows, p as normalizeAllow, r as restrictedPresetState, s as EVOLUTION_PRESET_IDS, t as disposeRestrictedPreset, u as RESTRICTED_TOOLS_ROW_ID } from "../ensure-Bx4ksgJk.js";
2
+ import { C as trimTrailingBlankLines, S as rowSiblingEnd, _ as presetRowId, a as composePresetComposition, b as resolveBasePresetPatch, c as composePresetRow, d as listDirectories, f as loadRowOverrides, g as presetRowBody, h as presetRowBlock, i as basePresetPlugins, l as compositionRowIds, m as presetPatchText, n as AGENT_PRESET_ROOT_HINT, o as composePresetEntry, p as mergePresetRow, r as EMPTY_PATCH_SEED, s as composePresetInsert, t as AGENT_PRESET_PACKAGE, u as denseBlockSequence, v as probeDesktopScope, x as rowBlockSpan, y as removePresetRow } from "../composition-DA8XPfMc.js";
3
3
  export { AGENT_PRESET_PACKAGE, AGENT_PRESET_ROOT_HINT, EMPTY_PATCH_SEED, EVOLUTION_PRESET_IDS, MAINTAINER_PRESET_ID, RESTRICTED_PRESET_DISPLAY, RESTRICTED_TOOLS_ROW_ID, RESTRICTOR_MODULE, REVIEWER_PRESET_ID, basePresetPlugins, composePresetComposition, composePresetEntry, composePresetInsert, composePresetRow, composeRestrictedPresetDefinition, compositionRowIds, denseBlockSequence, disposeRestrictedPreset, ensureRestrictedPreset, entryListSchema, listDirectories, loadRowOverrides, mergePresetRow, normalizeAllow, parsePresetRows, presetPatchText, presetRowBlock, presetRowBody, presetRowId, probeDesktopScope, removePresetRow, resolveBasePresetPatch, restrictedPresetId, restrictedPresetState, rowBlockSpan, rowSiblingEnd, trimTrailingBlankLines };
@@ -1,4 +1,4 @@
1
- import { g as scopedPackageName } from "./ensure-CAjLGd9f.js";
1
+ import { g as scopedPackageName } from "./ensure-Bx4ksgJk.js";
2
2
  import { dirname, join } from "node:path";
3
3
  import { existsSync, readFileSync, readdirSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
@@ -0,0 +1,28 @@
1
+ import { err, ok } from "./result.js";
2
+ //#region lib/types/platform/connection.js
3
+ const REGISTER_REQUIRED = "connection.fetch.register() is required to register family host routes (platform >= 0.2.2-rc.1); no fallback admission path exists";
4
+ /** Resolve the connection port; undefined means the host has no connection service. */
5
+ function connectionPort(ctx) {
6
+ const connection = ctx.get("connection");
7
+ if (connection === void 0) return void 0;
8
+ const register = (route) => {
9
+ if (connection.fetch === void 0 || typeof connection.fetch.register !== "function") throw new Error(REGISTER_REQUIRED);
10
+ return connection.fetch.register.call(connection.fetch, route);
11
+ };
12
+ return {
13
+ allowsRemoteAuthorities: connection.allowsRemoteAuthorities === true,
14
+ register,
15
+ tryRegister: (route) => {
16
+ try {
17
+ return ok(register(route));
18
+ } catch (error) {
19
+ return err({
20
+ code: "E-325",
21
+ message: error instanceof Error ? error.message : String(error)
22
+ });
23
+ }
24
+ }
25
+ };
26
+ }
27
+ //#endregion
28
+ export { connectionPort as t };
@@ -149,9 +149,14 @@ async function ensureRestrictedPreset(ctx, req) {
149
149
  const allow = normalizeAllow(req.allow);
150
150
  const key = req.parentPresetId + "\n" + allow.join("\n");
151
151
  const slot = slotFor(ctx, req.kind);
152
- if (slot.readyKey === key && slot.state !== void 0 && slot.state.kind === "ready") return slot.state;
153
- if (slot.inflight !== void 0) return slot.inflight;
154
- slot.inflight = (async () => {
152
+ for (;;) {
153
+ if (slot.readyKey === key && slot.state !== void 0 && slot.state.kind === "ready") return slot.state;
154
+ const inflight = slot.inflight;
155
+ if (inflight === void 0) break;
156
+ if (slot.inflightKey === key) return inflight;
157
+ await inflight.catch(() => void 0);
158
+ }
159
+ const pending = (async () => {
155
160
  await releaseRestrictedPreset(ctx, req.kind, slot);
156
161
  if (allow.length === 0) {
157
162
  slot.state = {
@@ -196,10 +201,15 @@ async function ensureRestrictedPreset(ctx, req) {
196
201
  return slot.state;
197
202
  }
198
203
  })();
204
+ slot.inflight = pending;
205
+ slot.inflightKey = key;
199
206
  try {
200
- return await slot.inflight;
207
+ return await pending;
201
208
  } finally {
202
- slot.inflight = void 0;
209
+ if (slot.inflight === pending) {
210
+ slot.inflight = void 0;
211
+ slot.inflightKey = void 0;
212
+ }
203
213
  }
204
214
  }
205
215
  /** Read-only view of the current registration (doctor runtime row). */
package/lib/errors.js ADDED
@@ -0,0 +1,2 @@
1
+ import { i as HOST_LOCALES, n as errorText, r as errorTextIn, t as EVOLUTION_ERRORS } from "./errors-BxzLTVbS.js";
2
+ export { EVOLUTION_ERRORS, HOST_LOCALES, errorText, errorTextIn };
@@ -0,0 +1,271 @@
1
+ import { E as selectSections, H as externalRefs, K as planReferenceRewrite, N as frontmatterBlock, U as supportRefs, W as applyReferenceRewrite, q as planRehoming } from "./usage-DdjIBAkm.js";
2
+ import { createHash } from "node:crypto";
3
+ //#region lib/types/extract-plan.js
4
+ const LF = String.fromCharCode(10);
5
+ function sha256(text) {
6
+ return createHash("sha256").update(text).digest("hex");
7
+ }
8
+ function unique(values) {
9
+ return [...new Set(values)];
10
+ }
11
+ function computeSupport(parts, residual, sourceName, sourceFiles, targetFiles, externalFiles) {
12
+ const selectedText = parts.map((part) => part.sourceText).join("\n\n");
13
+ const selectedRefs = unique(supportRefs(selectedText));
14
+ const residualRefs = new Set(supportRefs(residual));
15
+ const unresolved = selectedRefs.filter((ref) => !sourceFiles.includes(ref));
16
+ if (unresolved.length > 0) return { error: "support-unresolved: " + unresolved.join(", ") };
17
+ const candidates = selectedRefs.filter((ref) => sourceFiles.includes(ref));
18
+ const moves = planRehoming(candidates, targetFiles, sourceName).moves;
19
+ const byFrom = new Map(moves.map((move) => [move.from, move.to]));
20
+ const exclusive = [];
21
+ const shared = [];
22
+ for (const from of candidates) {
23
+ const to = byFrom.get(from);
24
+ if (to === void 0) continue;
25
+ if (residualRefs.has(from)) shared.push({
26
+ from,
27
+ to,
28
+ provenance: sourceName + ":" + from
29
+ });
30
+ else exclusive.push({
31
+ from,
32
+ to
33
+ });
34
+ }
35
+ const targetFilesWithMoves = unique([...targetFiles, ...moves.map((move) => move.to)]);
36
+ const external = unique(externalRefs(selectedText));
37
+ const suppliedRefs = new Set(externalFiles.map((file) => file.ref));
38
+ const missingExternal = external.filter((ref) => !suppliedRefs.has(ref));
39
+ const warnings = [];
40
+ if (missingExternal.length > 0) warnings.push("external-support-not-copied: " + missingExternal.join(", "));
41
+ const externalClosure = [];
42
+ for (const file of externalFiles) {
43
+ if (!external.includes(file.ref)) return { error: "external-ref-not-selected: " + file.ref };
44
+ if (file.targetPath.startsWith("/") || file.targetPath.includes("..") || !/^(?:references|templates|scripts|assets)\//.test(file.targetPath)) return { error: "external-target-unsafe: " + file.targetPath };
45
+ if (targetFilesWithMoves.includes(file.targetPath)) return { error: "external-collision: " + file.targetPath };
46
+ externalClosure.push({
47
+ from: file.ref,
48
+ to: file.targetPath,
49
+ provenance: file.provenance,
50
+ originalPath: file.originalPath,
51
+ content: file.content,
52
+ sha256: file.sha256
53
+ });
54
+ }
55
+ const rewritten = /* @__PURE__ */ new Map();
56
+ for (const part of parts) {
57
+ const partRefs = supportRefs(part.sourceText);
58
+ const rewrite = planReferenceRewrite({
59
+ content: part.sourceText,
60
+ files: sourceFiles,
61
+ moves: moves.filter((move) => partRefs.includes(move.from)),
62
+ targetFiles: targetFilesWithMoves
63
+ });
64
+ rewritten.set(part.heading, applyReferenceRewrite(part.sourceText, rewrite.edits));
65
+ warnings.push(...rewrite.unresolved.map((ref) => "support-unresolved: " + ref));
66
+ warnings.push(...rewrite.residualDangling.map((ref) => "support-dangling: " + ref));
67
+ }
68
+ for (const part of parts) {
69
+ let text = rewritten.get(part.heading) ?? part.sourceText;
70
+ for (const file of externalClosure) text = text.split(file.from).join(file.to);
71
+ part.movedText = text;
72
+ }
73
+ const exclusiveSet = new Set(exclusive.map((entry) => entry.from));
74
+ const parentExclusive = supportRefs(residual).filter((ref) => exclusiveSet.has(ref));
75
+ if (parentExclusive.length > 0) return { error: "support-exclusive-referenced-by-parent: " + parentExclusive.join(", ") };
76
+ const dangling = unique(warnings.filter((item) => item.startsWith("support-dangling: ")).map((item) => item.slice(18)));
77
+ return {
78
+ support: {
79
+ exclusive,
80
+ shared,
81
+ external: externalClosure,
82
+ unresolved: warnings.filter((item) => item.startsWith("support-unresolved: ")),
83
+ dangling
84
+ },
85
+ warnings
86
+ };
87
+ }
88
+ /**
89
+ * Build a pure extract plan. No IO, no writes: selection, residual, support
90
+ * closure and the moved text are computed from the supplied bodies/file lists.
91
+ * @param input - source body, target identity, owner decision and support lists.
92
+ * @returns a plan, or a refusal with a stable code.
93
+ */
94
+ function planExtract(input) {
95
+ if (input.outcome === "owner-gap") {
96
+ if (input.owner.mode !== "owner-gap") return {
97
+ ok: false,
98
+ code: "owner-gap-mismatch",
99
+ message: "outcome owner-gap requires an owner-gap decision"
100
+ };
101
+ if (input.owner.neededOwner === void 0 || input.owner.neededOwner.trim() === "") return {
102
+ ok: false,
103
+ code: "owner-gap-needed-owner",
104
+ message: "owner-gap requires neededOwner"
105
+ };
106
+ } else {
107
+ if (input.owner.mode !== "covered" || !input.owner.triggerCovers || !input.owner.outcomeCovers) return {
108
+ ok: false,
109
+ code: "owner-not-covered",
110
+ message: "extract/mixed requires a covering owner"
111
+ };
112
+ if (!input.targetExists) return {
113
+ ok: false,
114
+ code: "target-missing",
115
+ message: "covered owner target does not exist"
116
+ };
117
+ }
118
+ const selection = selectSections(input.body, input.requests);
119
+ if (!selection.ok) return {
120
+ ok: false,
121
+ code: selection.code,
122
+ message: selection.message
123
+ };
124
+ if (selection.sections.length === 0) return {
125
+ ok: false,
126
+ code: "part-empty",
127
+ message: "at least one part is required"
128
+ };
129
+ const externalRewrites = new Map((input.external ?? []).map((file) => [file.ref, file.targetPath]));
130
+ const parts = selection.sections.map((section) => {
131
+ let movedText = section.text;
132
+ for (const [from, to] of externalRewrites) movedText = movedText.split(from).join(to);
133
+ return {
134
+ heading: section.heading,
135
+ anchor: {
136
+ heading: section.heading,
137
+ ...section.anchorStart === void 0 ? {} : { start: section.anchorStart },
138
+ ...section.anchorEnd === void 0 ? {} : { end: section.anchorEnd }
139
+ },
140
+ sourceText: section.text,
141
+ movedText,
142
+ bytes: Buffer.byteLength(movedText, "utf8"),
143
+ sha256: sha256(movedText)
144
+ };
145
+ });
146
+ const pointer = "This capability now lives in " + (input.owner.mode === "covered" ? input.owner.name ?? input.targetName : input.owner.neededOwner ?? input.targetName) + "; project-specific facts stay here.";
147
+ const ordered = [...selection.sections].sort((a, b) => a.start - b.start);
148
+ const first = ordered[0];
149
+ if (first === void 0) return {
150
+ ok: false,
151
+ code: "part-empty",
152
+ message: "at least one part is required"
153
+ };
154
+ const byStart = new Map(ordered.map((section) => [section.start, section]));
155
+ const lines = input.body.split(LF);
156
+ const rebuilt = [];
157
+ for (let index = 0; index < lines.length; index += 1) {
158
+ const section = byStart.get(index);
159
+ if (section !== void 0) {
160
+ if (index === first.start) rebuilt.push(pointer);
161
+ index = section.end - 1;
162
+ } else rebuilt.push(lines[index] ?? "");
163
+ }
164
+ const residual = rebuilt.join(LF);
165
+ if (residual.trim().length === 0) return {
166
+ ok: false,
167
+ code: "parent-empty",
168
+ message: "parent residual is empty"
169
+ };
170
+ if (residual.split(LF).filter((line) => line.trim() !== "" && line !== pointer && !line.trimStart().startsWith("#")).length === 0) return {
171
+ ok: false,
172
+ code: "parent-hollow-heading",
173
+ message: "parent residual has no substantive content"
174
+ };
175
+ if (input.outcome === "owner-gap") return {
176
+ ok: true,
177
+ plan: {
178
+ source: input.sourceName,
179
+ target: {
180
+ name: input.targetName,
181
+ exists: input.targetExists
182
+ },
183
+ outcome: input.outcome,
184
+ parts,
185
+ residual,
186
+ pointer,
187
+ owner: input.owner,
188
+ support: {
189
+ exclusive: [],
190
+ shared: [],
191
+ external: [],
192
+ unresolved: [],
193
+ dangling: []
194
+ },
195
+ warnings: [],
196
+ ...input.anchors === void 0 ? {} : { anchors: input.anchors }
197
+ }
198
+ };
199
+ const supportResult = computeSupport(parts, residual, input.sourceName, input.sourceFiles, input.targetFiles, input.external ?? []);
200
+ if ("error" in supportResult) return {
201
+ ok: false,
202
+ code: supportResult.error.split(":")[0] ?? "support-invalid",
203
+ message: supportResult.error
204
+ };
205
+ if (supportResult.support.dangling.length > 0) return {
206
+ ok: false,
207
+ code: "support-dangling",
208
+ message: "support-dangling: " + supportResult.support.dangling.join(", ")
209
+ };
210
+ return {
211
+ ok: true,
212
+ plan: {
213
+ source: input.sourceName,
214
+ target: {
215
+ name: input.targetName,
216
+ exists: input.targetExists
217
+ },
218
+ outcome: input.outcome,
219
+ parts,
220
+ residual,
221
+ pointer,
222
+ owner: input.owner,
223
+ support: supportResult.support,
224
+ warnings: unique(supportResult.warnings),
225
+ ...input.anchors === void 0 ? {} : { anchors: input.anchors }
226
+ }
227
+ };
228
+ }
229
+ /**
230
+ * Project one plan onto the current source/target SKILL.md bytes.
231
+ *
232
+ * This is the one place that composes frontmatter + residual + target additions;
233
+ * preview and the write adapter both call it so they cannot advertise different
234
+ * bytes. Pure: no IO.
235
+ * @param plan - plan from planExtract.
236
+ * @param sourceMd - current source SKILL.md.
237
+ * @param targetMd - current target SKILL.md.
238
+ * @returns both next documents, or the refusal that makes projection impossible.
239
+ */
240
+ function projectExtractBodies(plan, sourceMd, targetMd) {
241
+ const sourceBlock = frontmatterBlock(sourceMd);
242
+ const targetBlock = frontmatterBlock(targetMd);
243
+ if (!sourceBlock) return {
244
+ ok: false,
245
+ message: "source 没有有效 frontmatter"
246
+ };
247
+ if (!targetBlock) return {
248
+ ok: false,
249
+ message: "target 没有有效 frontmatter"
250
+ };
251
+ const sourceHeader = sourceBlock.lines.slice(0, sourceBlock.end + 1).join(LF);
252
+ const targetNormalized = targetMd.replace(/\r\n/g, LF);
253
+ const targetLines = targetNormalized.split(LF);
254
+ for (const part of plan.parts) if (targetLines.some((line) => line.trim() === "## " + part.heading)) return {
255
+ ok: false,
256
+ message: "target 已有同名 heading「" + part.heading + "」。"
257
+ };
258
+ const additions = plan.parts.map((part) => part.movedText).join("\n\n");
259
+ const targetRaw = targetNormalized.trimEnd() + "\n\n" + additions + LF;
260
+ const targetAfter = targetBlock.nl === "\r\n" ? targetRaw.replace(/\n/g, "\r\n") : targetRaw;
261
+ const sourceRaw = (sourceHeader + plan.residual).replace(/\r\n/g, LF);
262
+ return {
263
+ ok: true,
264
+ projection: {
265
+ sourceAfter: sourceBlock.nl === "\r\n" ? sourceRaw.replace(/\n/g, "\r\n") : sourceRaw,
266
+ targetAfter
267
+ }
268
+ };
269
+ }
270
+ //#endregion
271
+ export { projectExtractBodies as n, planExtract as t };