@lmzhen/dsh-evolution-core 0.50.0 → 0.51.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.
@@ -41,7 +41,7 @@ import type { EvolutionIoLike } from './io.ts';
41
41
  import type { RunOutcome } from './contract.ts';
42
42
  export type { RunOutcome } from './contract.ts';
43
43
  /** The kinds of long-running work the registry tracks. */
44
- export type RunKind = 'maintain' | 'merge';
44
+ export type RunKind = 'maintain' | 'merge' | 'governance';
45
45
  /** Which merge command opened a run. `kind` stays the work family; this is the command. */
46
46
  export type RunCommand = 'scan' | 'pair' | 'approve' | 'resume';
47
47
  /** Coarse, user-visible stage of a run. */
@@ -116,6 +116,7 @@ export interface RunRegistry {
116
116
  command?: RunCommand;
117
117
  total?: number;
118
118
  parentRunId?: string;
119
+ exclusive?: boolean;
119
120
  }): Promise<RunHandle>;
120
121
  /** Record a run's terminal state (first writer wins). */
121
122
  settle(id: string, outcome: RunOutcome): Promise<void>;
@@ -320,12 +320,19 @@ export function newRunRegistry(options) {
320
320
  return true;
321
321
  },
322
322
  async begin(kind, seed) {
323
+ // Ask-then-begin has a window; a kind that must be single-flight is
324
+ // checked again at the mutation point, before this process owns a row.
325
+ if (seed?.exclusive === true) {
326
+ for (const record of owned.values()) {
327
+ if (record.kind === kind && record.state === 'running')
328
+ throw new Error(`run-kind-active:${kind}`);
329
+ }
330
+ }
323
331
  const id = randomUUID();
324
332
  const startedAt = now();
325
333
  const controller = new AbortController();
326
334
  controllers.set(id, controller);
327
- // The pid is what lets ANOTHER process tell this live run from an orphan.
328
- owned.set(id, {
335
+ const record = {
329
336
  id,
330
337
  kind,
331
338
  state: 'running',
@@ -334,11 +341,34 @@ export function newRunRegistry(options) {
334
341
  ...(seed?.command !== undefined ? { command: seed.command } : {}),
335
342
  ...(seed?.parentRunId !== undefined ? { parentRunId: seed.parentRunId } : {}),
336
343
  ...(seed?.total !== undefined ? { progress: { done: 0, total: seed.total } } : {}),
337
- });
338
- // Write-through (0.19.1, review P2): answering "started" promises a run another
339
- // plane can read, so the row reaches the index before this resolves. `persist()`
340
- // warns instead of throwing, so an unwritable home cannot withhold the handle.
341
- await persist();
344
+ };
345
+ if (seed?.exclusive === true) {
346
+ // Cross-process single-flight: the shared index is read INSIDE the
347
+ // transaction that writes the new row. A live owner of the same kind
348
+ // (including another plane) refuses; a dead owner is an orphan and
349
+ // does not block. Ask-then-begin alone could not see the other plane.
350
+ try {
351
+ await writeIndex((current) => {
352
+ const onDisk = parseIndex(current);
353
+ const busy = [...onDisk.records, ...owned.values()].some(row => row.kind === kind && row.state === 'running' && !ownerIsGone(row));
354
+ if (busy)
355
+ throw new Error(`run-kind-active:${kind}`);
356
+ return serializeIndex([...onDisk.records, record], onDisk.foreign);
357
+ });
358
+ }
359
+ catch (error) {
360
+ controllers.delete(id);
361
+ throw error;
362
+ }
363
+ owned.set(id, record);
364
+ }
365
+ else {
366
+ // Write-through (0.19.1, review P2): answering "started" promises a run another
367
+ // plane can read, so the row reaches the index before this resolves. `persist()`
368
+ // warns instead of throwing, so an unwritable home cannot withhold the handle.
369
+ owned.set(id, record);
370
+ await persist();
371
+ }
342
372
  return {
343
373
  id,
344
374
  kind,
@@ -35,6 +35,11 @@ export function selectSections(body, requests) {
35
35
  if (!partial) {
36
36
  if (section.end === section.start + 1)
37
37
  return { ok: false, code: 'heading-empty', message: 'heading "## ' + wanted + '" has an empty section' };
38
+ // A whole-section move must not swallow an already selected sub-block
39
+ // (the reverse order was already caught by the partial overlap check).
40
+ if (selected.some(entry => section.start < entry.end && section.end > entry.start)) {
41
+ return { ok: false, code: 'part-anchor-overlaps', message: 'heading "## ' + wanted + '" selection overlaps another selected block' };
42
+ }
38
43
  selected.push({ heading: wanted, start: section.start, end: section.end, text: lines.slice(section.start, section.end).join(LF), requestIndex });
39
44
  continue;
40
45
  }
@@ -34,6 +34,28 @@ export declare const HISTORY_INDEX_VERSION = 1;
34
34
  /** The action label for a predecessor the index had never seen (content found on disk before this
35
35
  * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
36
36
  export declare const BASELINE_ACTION = "baseline";
37
+ /** Where a one-line change summary came from. */
38
+ export type SummarySource = 'model' | 'host' | 'fallback';
39
+ /** One user-facing change summary, separate from the machine label in the mutation ledger. */
40
+ export interface ChangeSummary {
41
+ text: string;
42
+ source: SummarySource;
43
+ }
44
+ /** Default hard cap for a change summary, counted in Unicode code points. */
45
+ export declare const DEFAULT_SKILL_WRITE_SUMMARY_CHARS = 50;
46
+ /** Count a summary the same way the write gate does (code points, not UTF-16 units). */
47
+ export declare function summaryChars(text: string): number;
48
+ /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
49
+ export declare function normalizeChangeSummary(value: unknown, cap?: number): {
50
+ ok: true;
51
+ text: string;
52
+ } | {
53
+ ok: false;
54
+ reason: 'missing' | 'multiline' | 'length';
55
+ length: number;
56
+ };
57
+ /** Clip a host-generated summary to the same hard cap; host facts are not rejected. */
58
+ export declare function clipChangeSummary(text: string, cap?: number): string;
37
59
  /** G3b: one unit's head. Exactly one of the two forms is present (they never coexist). */
38
60
  export interface UnitHead {
39
61
  /** The merge run this unit belongs to, when the writer recorded one. */
@@ -75,10 +97,12 @@ export interface SkillVersion {
75
97
  beforeHash?: string;
76
98
  /** True on the synthetic entry that records a REMOVAL; its hash is the removed bytes. */
77
99
  removed?: boolean;
78
- /** One line saying what this write changed, when the deployment turned the summarizer on
79
- * (registry `skillVersionSummary`). Absent is a first-class state: the faces say so instead of
80
- * inventing a sentence, and a version recorded before the feature existed simply has none. */
100
+ /** One line saying what this write changed, when the writer supplied one. Absent is a first-class
101
+ * state: the faces say so instead of inventing a sentence, and a version recorded before the
102
+ * feature existed simply has none. */
81
103
  summary?: string;
104
+ /** Where {@link summary} came from; absent on legacy entries. */
105
+ summarySource?: SummarySource;
82
106
  /**
83
107
  * Which support file these bytes came from, RELATIVE to the skill directory (`references/foo.md`),
84
108
  * when this entry records a support-file write or remove. Absent is a first-class state: content
@@ -98,6 +122,8 @@ export interface VersionRecordInput {
98
122
  at: string;
99
123
  /** The one-line summary of THIS write, or undefined when the deployment does not summarize. */
100
124
  summary?: string;
125
+ /** Where {@link summary} came from. */
126
+ summarySource?: SummarySource;
101
127
  /** The support file this write touched, relative to the skill directory; undefined for content. */
102
128
  path?: string;
103
129
  /** G3a: the unit this write belongs to — one tree change writes N paths under ONE id. */
@@ -37,6 +37,30 @@ export const HISTORY_INDEX_VERSION = 1;
37
37
  /** The action label for a predecessor the index had never seen (content found on disk before this
38
38
  * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
39
39
  export const BASELINE_ACTION = 'baseline';
40
+ /** Default hard cap for a change summary, counted in Unicode code points. */
41
+ export const DEFAULT_SKILL_WRITE_SUMMARY_CHARS = 50;
42
+ /** Count a summary the same way the write gate does (code points, not UTF-16 units). */
43
+ export function summaryChars(text) {
44
+ return [...text].length;
45
+ }
46
+ /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
47
+ export function normalizeChangeSummary(value, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
48
+ if (typeof value !== 'string')
49
+ return { ok: false, reason: 'missing', length: 0 };
50
+ const text = value.replace(/\s+/g, ' ').trim();
51
+ if (text === '')
52
+ return { ok: false, reason: 'missing', length: 0 };
53
+ if (value.includes('\n') || value.includes('\r'))
54
+ return { ok: false, reason: 'multiline', length: summaryChars(text) };
55
+ const length = summaryChars(text);
56
+ return length <= cap ? { ok: true, text } : { ok: false, reason: 'length', length };
57
+ }
58
+ /** Clip a host-generated summary to the same hard cap; host facts are not rejected. */
59
+ export function clipChangeSummary(text, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
60
+ const line = text.replace(/\s+/g, ' ').trim();
61
+ const chars = [...line];
62
+ return chars.length <= cap ? line : chars.slice(0, Math.max(1, cap - 1)).join('') + '…';
63
+ }
40
64
  /** The root-level history directory. */
41
65
  export function historyRoot(root) {
42
66
  return join(root, HISTORY_DIR);
@@ -211,6 +235,9 @@ function readVersionEntry(entry) {
211
235
  // only by the chain link, so a field added here cannot be forgotten by one of them (a field this
212
236
  // reader drops is dropped for good on the next write).
213
237
  const summary = typeof candidate.summary === 'string' && candidate.summary !== '' ? candidate.summary : undefined;
238
+ const summarySource = candidate.summarySource === 'model' || candidate.summarySource === 'host' || candidate.summarySource === 'fallback'
239
+ ? candidate.summarySource
240
+ : undefined;
214
241
  const path = typeof candidate.path === 'string' && candidate.path !== '' ? candidate.path : undefined;
215
242
  const unitId = typeof candidate.unitId === 'string' && candidate.unitId !== '' ? candidate.unitId : undefined;
216
243
  const removed = candidate.removed === true ? true : undefined;
@@ -223,6 +250,7 @@ function readVersionEntry(entry) {
223
250
  hash: candidate.hash,
224
251
  chars: candidate.chars,
225
252
  ...summary === undefined ? {} : { summary },
253
+ ...summarySource === undefined ? {} : { summarySource },
226
254
  ...path === undefined ? {} : { path },
227
255
  ...unitId === undefined ? {} : { unitId },
228
256
  ...removed === undefined ? {} : { removed },
@@ -337,6 +365,7 @@ export function nextHistoryIndex(versions, input, keep) {
337
365
  // The summary describes THIS write, so it rides the after-entry only: the baseline minted
338
366
  // above is the state BEFORE it and has nothing to summarize.
339
367
  ...input.summary === undefined ? {} : { summary: input.summary },
368
+ ...input.summarySource === undefined ? {} : { summarySource: input.summarySource },
340
369
  // The authoritative predecessor link: what THIS write replaced, read under the write lock.
341
370
  ...beforeHash === null ? {} : { beforeHash },
342
371
  });
@@ -362,6 +391,7 @@ export function nextHistoryIndex(versions, input, keep) {
362
391
  // otherwise a pure-deletion representative would leave the unit headless.
363
392
  ...input.unitHead === undefined ? {} : { unitHead: input.unitHead },
364
393
  ...input.summary === undefined ? {} : { summary: input.summary },
394
+ ...input.summarySource === undefined ? {} : { summarySource: input.summarySource },
365
395
  });
366
396
  }
367
397
  }
@@ -41,7 +41,7 @@ import { SkillModel } from './skill-model.ts';
41
41
  import { type ExtractPlanDraft } from './extract-plan.ts';
42
42
  import { type MutationRecord } from './mutations.ts';
43
43
  import { type RevisionAnchor, type RevisionFile } from './skill-revision.ts';
44
- import { type UnitHead, type HistoryFence, type SkillVersion } from './skill-history.ts';
44
+ import { type ChangeSummary, type UnitHead, type HistoryFence, type SkillVersion } from './skill-history.ts';
45
45
  import { type SkillHealthAssessment, type SkillHealthThresholds } from './skill-health.ts';
46
46
  import type { EvolutionSkillMutatedEvent } from './events.ts';
47
47
  export interface SkillSummary {
@@ -129,11 +129,24 @@ export interface SkillActionResult {
129
129
  export interface SkillRestructureMove {
130
130
  /** The `##` heading title, matched as an exact line (leading `##` + spaces); no fuzzy matching. */
131
131
  heading: string;
132
+ /** Optional inclusive content anchors inside the heading; both must be provided together. */
133
+ start?: string;
134
+ end?: string;
132
135
  /** Destination support file: `references/<topic>.md` (references/ only — moved content is log/detail, never a template or script). */
133
136
  toFile: string;
134
137
  }
135
138
  /** Upper bound of moves per restructure proposal (validator and core agree). */
136
139
  export declare const MAX_RESTRUCTURE_MOVES = 5;
140
+ /** One incremental section edit: replace a whole H2 content area or an exact sub-block. */
141
+ export interface SkillSectionEdit {
142
+ /** Exact `##` heading title (without the leading `## `). */
143
+ heading: string;
144
+ /** Optional inclusive content anchors; both must be provided together. */
145
+ start?: string;
146
+ end?: string;
147
+ /** Replacement content (without the `##` heading line for a whole-section edit). */
148
+ content: string;
149
+ }
137
150
  /** Restructure targets are plain markdown files under references/ — no
138
151
  * subdirectories, no other support kind. V8-10 (0.3.47): the regex-level
139
152
  * `(?!.*\.\.)` keeps the restructure-created set EXACTLY the set
@@ -550,6 +563,8 @@ export declare class SkillLibrary {
550
563
  }): Promise<SkillHealthAssessment | null>;
551
564
  /** S2: mechanical hard-cap event; failure must not change the refusal. */
552
565
  private recordHardCapHit;
566
+ /** Host fallback for the user-facing change summary when the writer did not supply one. */
567
+ private hostChangeSummary;
553
568
  /** Best-effort audit trail entry; never blocks the mutation.
554
569
  *
555
570
  * Two independent best-effort writes run here, because either one failing must not cost the
@@ -603,6 +618,19 @@ export declare class SkillLibrary {
603
618
  update(rawName: string, content: string, origin?: WriteOrigin, anchor?: WriteAnchor): Promise<SkillActionResult>;
604
619
  private updateCore;
605
620
  patch(rawName: string, oldString: string, newString: string, filePath?: string, replaceAll?: boolean, origin?: WriteOrigin): Promise<SkillActionResult>;
621
+ /**
622
+ * Replace ONE section's content (or one exact sub-block) in place. Keeps the
623
+ * H2 heading line for whole-section edits, so a model can compress one
624
+ * section at a time without re-sending the body. No content-conservation
625
+ * gate: the version history is the rollback, and existing structural
626
+ * validation still applies through {@link update}.
627
+ * @param rawName - skill name.
628
+ * @param edit - section selector plus replacement text.
629
+ * @param origin - write face.
630
+ * @returns the normalized result, with before/after body sizes.
631
+ */
632
+ patchSection(rawName: string, edit: SkillSectionEdit, origin?: WriteOrigin): Promise<SkillActionResult>;
633
+ private patchSectionCore;
606
634
  private patchCore;
607
635
  /**
608
636
  * P2-9 (v15): the destructive directory move shared by archive and
@@ -631,7 +659,7 @@ export declare class SkillLibrary {
631
659
  private safeSnapshotEntryName;
632
660
  /** Mark merge-absorbed sources archived in the usage sidecar (FR-DATA-07). */
633
661
  private foldArchivedUsage;
634
- archive(rawName: string, options?: ArchiveOptions, origin?: WriteOrigin): Promise<SkillActionResult>;
662
+ archive(rawName: string, options?: ArchiveOptions, origin?: WriteOrigin, change?: ChangeSummary): Promise<SkillActionResult>;
635
663
  private archiveCore;
636
664
  /**
637
665
  * Commit one merge plan as a single multi-skill transaction.
@@ -699,7 +727,7 @@ export declare class SkillLibrary {
699
727
  * support-directory links is refused (those links' files stay behind in the
700
728
  * same package; the moved text belongs in references/ beside them).
701
729
  */
702
- restructure(rawName: string, moves: SkillRestructureMove[], origin?: WriteOrigin): Promise<SkillActionResult>;
730
+ restructure(rawName: string, moves: SkillRestructureMove[], origin?: WriteOrigin, change?: ChangeSummary): Promise<SkillActionResult>;
703
731
  private restructureCore;
704
732
  /**
705
733
  * Unified tree-change commit point (009 kernel): owns validation order,
@@ -716,7 +744,7 @@ export declare class SkillLibrary {
716
744
  * @param origin - write face recorded in the audit ledger.
717
745
  * @returns the kernel result; a refusal writes nothing.
718
746
  */
719
- extract(plan: ExtractPlanDraft, origin?: WriteOrigin): Promise<SkillActionResult>;
747
+ extract(plan: ExtractPlanDraft, origin?: WriteOrigin, change?: ChangeSummary): Promise<SkillActionResult>;
720
748
  private applyTreeChange;
721
749
  /**
722
750
  * Restore one skill from `.archive/` back to the active root. Hermes-style
@@ -57,7 +57,7 @@ import { projectExtractBodies } from "./extract-plan.js";
57
57
  import { diffFindings } from "./skill-lint.js";
58
58
  import { contentHash, loadMutations, recordMutation } from "./mutations.js";
59
59
  import { revisionFingerprint, revisionSupportDigest } from "./skill-revision.js";
60
- import { contentRetentionFeedback, HISTORY_DIR, loadVersionContent, loadVersions, recordVersions } from "./skill-history.js";
60
+ import { clipChangeSummary, contentRetentionFeedback, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, HISTORY_DIR, loadVersionContent, loadVersions, normalizeChangeSummary, recordVersions } from "./skill-history.js";
61
61
  import { getRecord, loadUsage, mutateUsage, suppressedFile, usageFile } from "./usage.js";
62
62
  import { assessStructureHealth, DEFAULT_HEALTH_THRESHOLDS, lintBody } from "./skill-health.js";
63
63
  import { CONTENT_SPLIT_HINT, DEFAULT_SKILL_VERSION_KEEP, PROTECTED_BUILTIN_SKILLS, SKILL_NAME_RE, SUPPORT_DIRS } from "./constants.js";
@@ -398,7 +398,11 @@ function planRestructureSections(body, moves) {
398
398
  // One scan (h2Sections) and one selection rule; extract reuses the same
399
399
  // selector for start/end sub-blocks, so restructure and extract cannot drift
400
400
  // on heading ambiguity, empty sections or duplicate moves.
401
- const selection = selectSections(body, moves.map(move => ({ heading: move.heading })));
401
+ const selection = selectSections(body, moves.map(move => ({
402
+ heading: move.heading,
403
+ ...(move.start === undefined ? {} : { start: move.start }),
404
+ ...(move.end === undefined ? {} : { end: move.end }),
405
+ })));
402
406
  if (!selection.ok)
403
407
  return { error: selection.message };
404
408
  const lines = body.split('\n');
@@ -535,7 +539,8 @@ export class SkillLibrary {
535
539
  ...(provenance.get(op.target) === undefined ? {} : { provenance: provenance.get(op.target) }),
536
540
  });
537
541
  }
538
- return { moves, sources: roots.map(skill => ({ skill })) };
542
+ const runId = currentReviewContext()?.runId;
543
+ return { ...(runId === undefined ? {} : { runId }), moves, sources: roots.map(skill => ({ skill })) };
539
544
  }
540
545
  async withMutationLock(task) {
541
546
  // Fail closed: a missing authority/lock is an assembly error, not a reason to run
@@ -1218,6 +1223,18 @@ export class SkillLibrary {
1218
1223
  console.warn('skill-store: hard-cap event not recorded for "' + name + '": ' + (error instanceof Error ? error.message : String(error)));
1219
1224
  }
1220
1225
  }
1226
+ /** Host fallback for the user-facing change summary when the writer did not supply one. */
1227
+ hostChangeSummary(action, before, after, path, machine) {
1228
+ const target = path ?? 'SKILL.md';
1229
+ let text = machine;
1230
+ if (action === 'update' || action === 'edit')
1231
+ text = `updated ${target} (${before?.length ?? 0} → ${after?.length ?? 0})`;
1232
+ else if (action === 'create')
1233
+ text = `created ${target} (${after?.length ?? 0})`;
1234
+ else if (action === 'patch')
1235
+ text = machine.trim() === '' || machine === 'patched' ? `patched ${target}` : machine;
1236
+ return { text: clipChangeSummary(text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS), source: 'host' };
1237
+ }
1221
1238
  /** Best-effort audit trail entry; never blocks the mutation.
1222
1239
  *
1223
1240
  * Two independent best-effort writes run here, because either one failing must not cost the
@@ -1233,11 +1250,17 @@ export class SkillLibrary {
1233
1250
  // migration step). Optional so existing callers keep their behaviour; the ledger stores it when
1234
1251
  // given, and old records without it stay readable.
1235
1252
  // G3a: one tree change writes N paths under ONE unit id; the entries it writes share it.
1236
- unitId, unitHead, origin, fenceHeld = false) {
1253
+ unitId, unitHead, origin, fenceHeld = false, change) {
1237
1254
  // A committed hook or outer tree operation already holds the home fence.
1238
1255
  // Keep per-file transactions, but do not queue behind our own lease.
1239
1256
  const fence = fenceHeld ? undefined : this.fence;
1240
1257
  const at = new Date().toISOString();
1258
+ const finalSummary = change === undefined
1259
+ ? this.hostChangeSummary(action, before, after, path, summary)
1260
+ : (() => {
1261
+ const normalized = normalizeChangeSummary(change.text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1262
+ return normalized.ok ? { text: normalized.text, source: change.source } : this.hostChangeSummary(action, before, after, path, summary);
1263
+ })();
1241
1264
  let versions = null;
1242
1265
  try {
1243
1266
  const keep = this.limits.versionKeep ?? DEFAULT_SKILL_VERSION_KEEP;
@@ -1251,6 +1274,8 @@ export class SkillLibrary {
1251
1274
  ...path === undefined ? {} : { path },
1252
1275
  ...unitId === undefined ? {} : { unitId },
1253
1276
  ...unitHead === undefined ? {} : { unitHead },
1277
+ summary: finalSummary.text,
1278
+ summarySource: finalSummary.source,
1254
1279
  };
1255
1280
  versions = await recordVersions(this.root, this.io, input, keep, fence);
1256
1281
  }
@@ -1732,6 +1757,69 @@ export class SkillLibrary {
1732
1757
  // queue so two concurrent patches on one skill never interleave.
1733
1758
  return await this.serial(() => this.patchCore(name, oldString, newString, filePath, replaceAll, origin));
1734
1759
  }
1760
+ /**
1761
+ * Replace ONE section's content (or one exact sub-block) in place. Keeps the
1762
+ * H2 heading line for whole-section edits, so a model can compress one
1763
+ * section at a time without re-sending the body. No content-conservation
1764
+ * gate: the version history is the rollback, and existing structural
1765
+ * validation still applies through {@link update}.
1766
+ * @param rawName - skill name.
1767
+ * @param edit - section selector plus replacement text.
1768
+ * @param origin - write face.
1769
+ * @returns the normalized result, with before/after body sizes.
1770
+ */
1771
+ async patchSection(rawName, edit, origin = this.authority.origin) {
1772
+ await this.ensureRecovered();
1773
+ return await this.patchSectionCore(rawName.trim(), edit, origin);
1774
+ }
1775
+ async patchSectionCore(name, edit, origin) {
1776
+ const badName = this.badName(name);
1777
+ if (badName)
1778
+ return { ok: false, message: badName };
1779
+ if (typeof edit.heading !== 'string' || edit.heading.trim() === '')
1780
+ return { ok: false, message: '章节改写需要非空 heading。' };
1781
+ const dir = this.dirOf(name);
1782
+ const path = join(dir, 'SKILL.md');
1783
+ let md;
1784
+ try {
1785
+ md = await this.io.readText(path);
1786
+ }
1787
+ catch (error) {
1788
+ return unreadableTarget(name, error);
1789
+ }
1790
+ if (md === null)
1791
+ return { ok: false, message: `技能「${name}」不存在。` };
1792
+ const block = frontmatterBlock(md);
1793
+ if (!block)
1794
+ return { ok: false, message: 'SKILL.md 没有有效的 frontmatter;拒绝章节改写。' };
1795
+ const header = block.lines.slice(0, block.end + 1).join('\n');
1796
+ const body = md.slice(header.length).replace(/\r\n/g, '\n');
1797
+ const selection = selectSections(body, [{
1798
+ heading: edit.heading,
1799
+ ...edit.start === undefined ? {} : { start: edit.start },
1800
+ ...edit.end === undefined ? {} : { end: edit.end },
1801
+ }]);
1802
+ if (!selection.ok)
1803
+ return { ok: false, message: `章节改写被拒绝:${selection.message}` };
1804
+ const section = selection.sections[0];
1805
+ if (section === undefined)
1806
+ return { ok: false, message: '章节改写被拒绝:没有匹配的章节。' };
1807
+ const lines = body.split('\n');
1808
+ // Whole-section: keep the heading itself and replace only the content
1809
+ // after it. Sub-block: replace the selected inclusive lines.
1810
+ const start = section.anchorStart === undefined ? section.start + 1 : section.start;
1811
+ const end = section.end;
1812
+ const replacement = edit.content === '' ? [] : edit.content.replace(/\r\n/g, '\n').split('\n');
1813
+ const nextBody = [...lines.slice(0, start), ...replacement, ...lines.slice(end)].join('\n');
1814
+ const next = `${header}${nextBody}`;
1815
+ const finalMd = block.nl === '\r\n' ? next.replace(/\n/g, '\r\n') : next;
1816
+ if (finalMd.trimEnd() === md.trimEnd())
1817
+ return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir };
1818
+ const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
1819
+ if (!result.ok)
1820
+ return result;
1821
+ return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
1822
+ }
1735
1823
  async patchCore(name, oldString, newString, filePath, replaceAll, origin) {
1736
1824
  // P1-1 (v14): patch was the ONE path-building mutator without the name
1737
1825
  // guard — `name = '../outside'` plus a `file_path` escaped the skills root
@@ -1987,10 +2075,10 @@ export class SkillLibrary {
1987
2075
  }
1988
2076
  catch { /* lifecycle telemetry is best-effort; the archive already landed */ }
1989
2077
  }
1990
- async archive(rawName, options = {}, origin = this.authority.origin) {
1991
- return await this.archiveCore(rawName, options, origin, false);
2078
+ async archive(rawName, options = {}, origin = this.authority.origin, change) {
2079
+ return await this.archiveCore(rawName, options, origin, false, change);
1992
2080
  }
1993
- async archiveCore(rawName, options, origin, fenceHeld) {
2081
+ async archiveCore(rawName, options, origin, fenceHeld, change) {
1994
2082
  // One trim per entry: paths (dirOf), validation and messages all see the same name.
1995
2083
  const name = rawName.trim();
1996
2084
  const badName = this.badName(name, { allowReserved: true });
@@ -2104,7 +2192,7 @@ export class SkillLibrary {
2104
2192
  catch {
2105
2193
  // Same posture as .archive-reason: metadata only, never abort the archive.
2106
2194
  }
2107
- await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin, fenceHeld);
2195
+ await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin, fenceHeld, change);
2108
2196
  this.notifyMutation({ action: 'archive', name, archivedPath: dest });
2109
2197
  return { ok: true, message: `技能「${name}」已归档到 .archive。`, path: dest };
2110
2198
  }
@@ -2788,14 +2876,14 @@ export class SkillLibrary {
2788
2876
  * support-directory links is refused (those links' files stay behind in the
2789
2877
  * same package; the moved text belongs in references/ beside them).
2790
2878
  */
2791
- async restructure(rawName, moves, origin = this.authority.origin) {
2879
+ async restructure(rawName, moves, origin = this.authority.origin, change) {
2792
2880
  const name = rawName.trim();
2793
2881
  await this.ensureRecovered();
2794
2882
  // F-208: the whole read→plan→write runs under the in-process serialize
2795
2883
  // queue so two concurrent restructures on one skill never interleave.
2796
- return await this.restructureCore(name, moves, origin);
2884
+ return await this.restructureCore(name, moves, origin, change);
2797
2885
  }
2798
- async restructureCore(name, moves, origin) {
2886
+ async restructureCore(name, moves, origin, change) {
2799
2887
  const badName = this.badName(name);
2800
2888
  if (badName)
2801
2889
  return { ok: false, message: badName };
@@ -2816,6 +2904,12 @@ export class SkillLibrary {
2816
2904
  if (typeof move.heading !== 'string' || !move.heading.trim()) {
2817
2905
  return { ok: false, message: '每次重构搬移都需要非空的 heading。' };
2818
2906
  }
2907
+ if ((move.start === undefined) !== (move.end === undefined)) {
2908
+ return { ok: false, message: '子块搬移必须同时提供 start 和 end。' };
2909
+ }
2910
+ if (move.start !== undefined && (typeof move.start !== 'string' || typeof move.end !== 'string' || !move.start.trim() || !move.end.trim())) {
2911
+ return { ok: false, message: '子块搬移的 start/end 必须是匹配行的非空文本。' };
2912
+ }
2819
2913
  // A1-6 (v18): reuse the single validator (regex + Windows device stems)
2820
2914
  // so restructure cannot mint a target the support-file layer refuses.
2821
2915
  const targetIssue = validateRestructureTarget(move.toFile);
@@ -2914,7 +3008,7 @@ export class SkillLibrary {
2914
3008
  let headPlaced = false;
2915
3009
  for (const op of event.ops) {
2916
3010
  const rel = relative(dir, op.target).split(String.fromCharCode(92)).join('/');
2917
- await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin, true);
3011
+ await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin, true, change);
2918
3012
  headPlaced = true;
2919
3013
  }
2920
3014
  this.notifyMutation({ action: 'restructure', name, skillDir: dir });
@@ -2939,7 +3033,7 @@ export class SkillLibrary {
2939
3033
  });
2940
3034
  if (!result.ok)
2941
3035
  return { ok: false, message: result.errors.map(error => error.message).join(';') };
2942
- return { ok: true, message: `已重构「${name}」:把 ${plan.sections.length} 个章节搬到 references/。`, path: dir };
3036
+ return { ok: true, message: `已重构「${name}」:把 ${plan.sections.length} 个章节搬到 references/(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
2943
3037
  }
2944
3038
  /**
2945
3039
  * Unified tree-change commit point (009 kernel): owns validation order,
@@ -2956,7 +3050,7 @@ export class SkillLibrary {
2956
3050
  * @param origin - write face recorded in the audit ledger.
2957
3051
  * @returns the kernel result; a refusal writes nothing.
2958
3052
  */
2959
- async extract(plan, origin = this.authority.origin) {
3053
+ async extract(plan, origin = this.authority.origin, change) {
2960
3054
  await this.ensureRecovered();
2961
3055
  if (plan.outcome === 'owner-gap' || plan.owner.mode !== 'covered')
2962
3056
  return { ok: false, message: '提取被拒绝:owner-gap 不是写操作。' };
@@ -3042,7 +3136,7 @@ export class SkillLibrary {
3042
3136
  if (op.skill === undefined)
3043
3137
  continue;
3044
3138
  const rel = relative(this.dirOf(op.skill), op.target).split(String.fromCharCode(92)).join('/');
3045
- await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin, true);
3139
+ await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin, true, change);
3046
3140
  headPlaced = true;
3047
3141
  }
3048
3142
  for (const name of roots)
@@ -3,7 +3,7 @@ import type { SessionId } from '../platform/index.ts';
3
3
  import type { SubagentStopReason } from '../platform/index.ts';
4
4
  import type { ObjectJsonSchema } from '../platform/index.ts';
5
5
  export type ChannelCode = 'E-323' | 'E-324';
6
- export type ChannelKind = 'reviewer' | 'maintainer';
6
+ export type ChannelKind = 'reviewer' | 'maintainer' | 'governance';
7
7
  export interface PresetStatus {
8
8
  readonly id: string;
9
9
  readonly registered: boolean;
@@ -160,7 +160,17 @@ const MISSING_ARGS = {
160
160
  const required = action === undefined || !Object.hasOwn(SKILL_ACTION_REQUIRED_FIELDS, action)
161
161
  ? []
162
162
  : SKILL_ACTION_REQUIRED_FIELDS[action] ?? [];
163
- const missing = required.filter(field => view.scalars[field] === undefined || view.scalars[field] === null);
163
+ // A section patch replaces the old/new pair with one in-place edit.
164
+ const section = view.scalars['section'];
165
+ const sectionPatch = action === 'patch'
166
+ && typeof section === 'object' && section !== null
167
+ && typeof section.heading === 'string'
168
+ && typeof section.content === 'string';
169
+ const missing = required.filter(field => {
170
+ if (sectionPatch && (field === 'old_string' || field === 'new_string'))
171
+ return false;
172
+ return view.scalars[field] === undefined || view.scalars[field] === null;
173
+ });
164
174
  if (missing.length === 0)
165
175
  return null;
166
176
  return `skill_manage ${action} requires ${missing.join(', ')}; the tool description lists the arguments per action.`;
@@ -823,6 +823,11 @@ function selectSections(body, requests) {
823
823
  code: "heading-empty",
824
824
  message: "heading \"## " + wanted + "\" has an empty section"
825
825
  };
826
+ if (selected.some((entry) => section.start < entry.end && section.end > entry.start)) return {
827
+ ok: false,
828
+ code: "part-anchor-overlaps",
829
+ message: "heading \"## " + wanted + "\" selection overlaps another selected block"
830
+ };
826
831
  selected.push({
827
832
  heading: wanted,
828
833
  start: section.start,
package/lib/write.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { r as contentHash } from "./mutations-DQXddSJd.js";
2
- import { $ as validateMutationRequest, A as UNIT_JOURNAL_SCHEMA_VERSION, B as readUnitSnapshot, D as unitJournalPort, E as pruneTreeChangeUnits, F as writeUnitJournal, G as unitSnapshotsDir, H as unitIndexPath, I as UNIT_STORAGE_SCHEMA_VERSION, J as writeUnitEvidence, K as unitStorageKey, L as readUnitEvidence, M as readUnitJournal, N as unitJournalPath, O as unitSnapshotPort, P as unitJournalPhaseRank, Q as fileMutationLock, R as readUnitIndex, U as unitReceiptPath, V as unitEvidencePath, W as unitSnapshotPath, X as writeUnitSnapshot, Y as writeUnitReceipt, Z as MutationUnit, d as entryTarget, et as WriteKernel, j as assertUnitJournalTransition, k as UNIT_JOURNAL_PHASES, q as upsertUnitIndex, z as readUnitReceipt } from "./skill-history-CxrDE3Rb.js";
2
+ import { $ as writeUnitReceipt, A as pruneTreeChangeUnits, B as UNIT_STORAGE_SCHEMA_VERSION, F as assertUnitJournalTransition, G as unitEvidencePath, H as readUnitIndex, I as readUnitJournal, J as unitSnapshotPath, K as unitIndexPath, L as unitJournalPath, M as unitSnapshotPort, N as UNIT_JOURNAL_PHASES, P as UNIT_JOURNAL_SCHEMA_VERSION, Q as writeUnitEvidence, R as unitJournalPhaseRank, U as readUnitReceipt, V as readUnitEvidence, W as readUnitSnapshot, X as unitStorageKey, Y as unitSnapshotsDir, Z as upsertUnitIndex, et as writeUnitSnapshot, it as WriteKernel, j as unitJournalPort, nt as fileMutationLock, p as entryTarget, q as unitReceiptPath, rt as validateMutationRequest, tt as MutationUnit, z as writeUnitJournal } from "./skill-history-CZp8vhyL.js";
3
3
  //#region lib/types/unit-undo.js
4
4
  /**
5
5
  * Cross-skill unit undo executor.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-core",
3
3
  "description": "Shared stores, prompts, signals and lifecycle logic for the dsh-evolution plugin family (community build)",
4
- "version": "0.50.0",
4
+ "version": "0.51.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },