@gobing-ai/knowledge-kit 0.1.20 → 0.1.22

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 (115) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +1 -0
  3. package/dist/board/daily-voice/index.js +1279 -261
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +13893 -8995
  6. package/package.json +1 -1
  7. package/plugins/generations/dailynews-gen/dist/index.js +285 -16
  8. package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -4
  10. package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
  11. package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
  12. package/plugins/generations/music-gen/README.md +277 -0
  13. package/plugins/generations/music-gen/dist/index.js +23544 -0
  14. package/plugins/generations/music-gen/package.json +24 -0
  15. package/plugins/generations/music-gen/plugin.json +23 -0
  16. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  17. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  18. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  19. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
  21. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  22. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  23. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  24. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
  26. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  27. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  28. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  29. package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
  30. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  31. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  32. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  33. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  34. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  35. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  36. package/plugins/generations/music-gen/src/audio.ts +122 -0
  37. package/plugins/generations/music-gen/src/brief.ts +191 -0
  38. package/plugins/generations/music-gen/src/config.ts +451 -0
  39. package/plugins/generations/music-gen/src/content.ts +199 -0
  40. package/plugins/generations/music-gen/src/digest.ts +100 -0
  41. package/plugins/generations/music-gen/src/index.ts +147 -0
  42. package/plugins/generations/music-gen/src/job.ts +131 -0
  43. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  44. package/plugins/generations/music-gen/src/presets.ts +918 -0
  45. package/plugins/generations/music-gen/src/render.ts +87 -0
  46. package/plugins/generations/music-gen/src/request.ts +102 -0
  47. package/plugins/generations/music-gen/src/spend.ts +495 -0
  48. package/plugins/generations/music-gen/tsconfig.json +8 -0
  49. package/plugins/kk/plugin.json +1 -1
  50. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
  51. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  52. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  53. package/plugins/kk/scripts/daily-stages.ts +659 -20
  54. package/plugins/kk/scripts/episode-identity.ts +180 -0
  55. package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
  56. package/plugins/kk/scripts/music-stages.ts +624 -0
  57. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  58. package/plugins/kk/scripts/source-citation.ts +187 -0
  59. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  60. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  61. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  62. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  63. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  64. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  65. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  66. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  67. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  68. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  69. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  70. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +8 -8
  71. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +7 -7
  72. package/plugins/kk/workflows/kk-music.yaml +328 -0
  73. package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
  74. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  75. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  76. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  77. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  78. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  79. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  80. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  81. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  82. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  83. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  84. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  85. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  86. package/plugins/publishings/linkedin-pub/dist/index.js +11 -1
  87. package/plugins/publishings/linkedin-pub/dist/profile-check.js +11 -1
  88. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  89. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  90. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  91. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  92. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  93. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  94. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  95. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  96. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  97. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  98. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  99. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  100. package/plugins/publishings/surfdash-pub/dist/index.js +72 -20
  101. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  102. package/plugins/publishings/surfdash-pub/src/index.ts +100 -17
  103. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  104. package/plugins/publishings/threads-pub/dist/index.js +11 -1
  105. package/plugins/publishings/threads-pub/dist/profile-check.js +11 -1
  106. package/plugins/publishings/wechatmp-pub/dist/index.js +11 -1
  107. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  108. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  110. package/plugins/publishings/x-pub/dist/index.js +11 -1
  111. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  112. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  115. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,906 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * The daily editorial judgment ledger (`<works_dir>/kk-news-generate/conclusion.md`) — ADR-054,
4
+ * task 0384 (L3 R4/R10).
5
+ *
6
+ * The news-editorial skill authors a *proposal* (mode `align`, see the skill's SKILL.md); this
7
+ * module is the deterministic half: validate → reconcile → atomic commit → immutable run snapshot.
8
+ * Nothing here trusts the model: every proposal entry is checked against the IDs 0393's selection
9
+ * provenance produced, judged against the ledger already on disk, and only then written.
10
+ *
11
+ * The three protections R10 asks for, in the order they run:
12
+ *
13
+ * 1. **Serialization** — commits take the existing `kk lock` claim named
14
+ * `kk-news-editorial-ledger` (the store's single-flight DAO, TTL-owned by the run) so two runs
15
+ * on the same ledger never interleave. The port is injected: the workflow node acquires the
16
+ * claim (`kk lock acquire --name kk-news-editorial-ledger --run <run_id>`) and hands the stage
17
+ * an owner; `NULL_LOCK` is the documented no-lock default for tests and offline replay.
18
+ * 2. **Compare-and-swap** — the ledger text is hashed when it is read and re-hashed after the lock
19
+ * is held. A mismatch means someone committed in between: the loser writes nothing and reports
20
+ * `conflict`, so a stale proposal can never overwrite a confirmed judgment.
21
+ * 3. **No-op replay** — a proposal whose content digest is already in the ledger appends nothing
22
+ * and reuses the legal run snapshot; re-running the same day is free.
23
+ *
24
+ * Unavailable or corrupt historical state is an explicit `stop`: the ledger is never rebuilt from a
25
+ * proposal (that would erase the superseded records), the backup path is reported, and the caller
26
+ * fails the run instead of drafting against an invented history.
27
+ *
28
+ * Same-directory temp file + `rename` gives the atomic replacement (one filesystem, one inode
29
+ * swap) and the previous text is copied to `<ledger>.bak-<stamp>` first, so a restore is a `cp`.
30
+ *
31
+ * Node/Bun builtins only — the plugin ships this file beside the other stage bodies.
32
+ */
33
+ import { createHash } from 'node:crypto';
34
+ import {
35
+ copyFileSync,
36
+ existsSync,
37
+ mkdirSync,
38
+ readFileSync,
39
+ renameSync,
40
+ rmSync,
41
+ statSync,
42
+ writeFileSync,
43
+ } from 'node:fs';
44
+ import { dirname } from 'node:path';
45
+
46
+ /** Machine block delimiters — the only part of `conclusion.md` this module reads or writes. */
47
+ export const LEDGER_BEGIN = '<!-- kk:judgment-ledger:begin -->';
48
+ export const LEDGER_END = '<!-- kk:judgment-ledger:end -->';
49
+
50
+ /** The lock name every judgment commit claims (ADR-054; the kk store single-flight DAO). */
51
+ export const LEDGER_LOCK_NAME = 'kk-news-editorial-ledger';
52
+
53
+ /** A judgment's lifecycle position. `aired` is only ever set by a later evidence step, never here. */
54
+ export type JudgmentStatus = 'pending' | 'aired' | 'superseded';
55
+
56
+ /** Where a judgment came from: the selected item, the evidence URL and when it was checked. */
57
+ export interface JudgmentEvidence {
58
+ url: string;
59
+ checkedAt: string;
60
+ }
61
+
62
+ /** One durable editorial judgment, identified by a stable ID. */
63
+ export interface Judgment {
64
+ id: string;
65
+ selectedId: string;
66
+ storyKey?: string;
67
+ date: string;
68
+ fact: string;
69
+ attribution: string;
70
+ comment: string;
71
+ evidence: JudgmentEvidence;
72
+ supersedes: string | null;
73
+ status: JudgmentStatus;
74
+ /** Filled when a later judgment supersedes this one; the record itself is never rewritten. */
75
+ supersededBy?: string | null;
76
+ contentDigest: string;
77
+ }
78
+
79
+ /** The committed ledger: judgments plus the superseded records they displaced. */
80
+ export interface JudgmentLedger {
81
+ version: 1;
82
+ updatedAt: string;
83
+ judgments: Judgment[];
84
+ }
85
+
86
+ /** One proposed judgment from the agent's alignment pass. */
87
+ export interface ProposalEntry {
88
+ id: string;
89
+ selectedId: string;
90
+ storyKey?: string;
91
+ date: string;
92
+ fact: string;
93
+ attribution: string;
94
+ comment: string;
95
+ evidence: JudgmentEvidence;
96
+ supersedes?: string | null;
97
+ }
98
+
99
+ /** The agent's `align` output. An empty `judgments` array is legal and means "nothing new". */
100
+ export interface AlignmentProposal {
101
+ version: 1;
102
+ judgments: ProposalEntry[];
103
+ /** Optional editorial preamble (the correction wording the draft must carry). */
104
+ preamble?: string;
105
+ }
106
+
107
+ /**
108
+ * A retired judgment as it was committed — carried into the snapshot so a consumer told to read only
109
+ * the snapshot (0385/0396) can still name *what* was wrong: old id, date, fact, comment, and the id
110
+ * that displaced it. The ledger stays the authority; this is a read-only projection of it.
111
+ */
112
+ export interface SupersededRecord {
113
+ id: string;
114
+ date: string;
115
+ fact: string;
116
+ attribution: string;
117
+ comment: string;
118
+ supersededBy: string;
119
+ }
120
+
121
+ /** One correction the draft owes the listener: which judgment was wrong and what replaces it. */
122
+ export interface Correction {
123
+ correctionId: string;
124
+ supersedes: string;
125
+ judgmentId: string;
126
+ selectedId: string;
127
+ /** The superseding judgment's comment — the replacement wording the draft speaks. */
128
+ wording: string;
129
+ /** Render-able correction sentence (old claim + replacement), so no consumer re-invents it. */
130
+ text: string;
131
+ /** The retired judgment verbatim: the evidence 0396 names, without re-reading the ledger. */
132
+ retired: SupersededRecord;
133
+ evidence: JudgmentEvidence;
134
+ }
135
+
136
+ /** The immutable, run-scoped snapshot the draft reads (0385) and the correction list (0396). */
137
+ export interface JudgmentSnapshot {
138
+ version: 1;
139
+ runDate: string;
140
+ frozenAt: string;
141
+ ledgerDigest: string;
142
+ proposalDigest: string;
143
+ judgments: Judgment[];
144
+ /** Every retired record the ledger holds (never rewritten here) — the correction's subject. */
145
+ superseded: SupersededRecord[];
146
+ corrections: Correction[];
147
+ /** The `## 本期更正说明` block: the acknowledgment the draft owes, frozen with the records. */
148
+ preamble: string | null;
149
+ }
150
+
151
+ /** What a commit did. `applied` wrote, `no-op` was already there, `conflict` lost the CAS, `stop` refuses. */
152
+ export type CommitStatus = 'applied' | 'no-op' | 'conflict' | 'stop';
153
+
154
+ /** The lock seam: the existing kk store single-flight claim, injected so tests stay offline. */
155
+ export interface LockPort {
156
+ acquire(name: string, run: string): Promise<boolean>;
157
+ release(name: string, run: string): Promise<void>;
158
+ }
159
+
160
+ /** No-lock default; the receipt records `lock: "none"` so a skipped claim is visible evidence. */
161
+ export const NULL_LOCK: LockPort = {
162
+ acquire: async () => true,
163
+ release: async () => {},
164
+ };
165
+
166
+ /** The commit receipt — the recovery evidence the design asks for. */
167
+ export interface CommitReceipt {
168
+ version: 1;
169
+ status: CommitStatus;
170
+ reason: string;
171
+ lock: 'held' | 'none' | 'contended';
172
+ ledgerPath: string;
173
+ snapshotPath: string;
174
+ backupPath: string | null;
175
+ ledgerDigestBefore: string | null;
176
+ ledgerDigestAfter: string | null;
177
+ proposalDigest: string;
178
+ initialized: boolean;
179
+ snapshotReused: boolean;
180
+ appended: string[];
181
+ superseded: string[];
182
+ correctionIds: string[];
183
+ /**
184
+ * Judgments the *stage* dropped before the commit because the settled plan no longer carries the
185
+ * id they cite (the proposal is authored in `curate`, the plan is settled afterwards). Recorded as
186
+ * `<judgmentId>=> <selectedId>` — the drop is never silent.
187
+ */
188
+ droppedByReselection: string[];
189
+ /** Populated on `stop`/`conflict`: the two paths an operator restores from. */
190
+ recovery: { ledgerPath: string; backupPath: string | null; action: string } | null;
191
+ errors: string[];
192
+ committedAt: string;
193
+ }
194
+
195
+ /** Result of one reconcile pass over an in-memory ledger. */
196
+ export interface ReconcileResult {
197
+ status: 'applied' | 'no-op' | 'conflict';
198
+ reason: string;
199
+ ledger: JudgmentLedger;
200
+ appended: string[];
201
+ superseded: string[];
202
+ corrections: Correction[];
203
+ errors: string[];
204
+ }
205
+
206
+ /** Options for {@link commitAlignment}. */
207
+ export interface CommitOptions {
208
+ ledgerPath: string;
209
+ snapshotPath: string;
210
+ receiptPath: string;
211
+ proposal: AlignmentProposal;
212
+ selectedIds: Set<string>;
213
+ runDate: string;
214
+ runId: string;
215
+ now: string;
216
+ lock?: LockPort;
217
+ /**
218
+ * Ids the caller already dropped as reselected away. The ledger API itself still refuses an
219
+ * unknown id (that refusal is honest); it only surfaces the caller's drop in the receipt.
220
+ */
221
+ droppedByReselection?: string[];
222
+ }
223
+
224
+ /** Stable JSON (sorted keys) so a digest never depends on key order. */
225
+ function stableJson(value: unknown): string {
226
+ if (value === null || typeof value !== 'object') {
227
+ return JSON.stringify(value ?? null);
228
+ }
229
+ if (Array.isArray(value)) {
230
+ return `[${value.map((entry) => stableJson(entry)).join(',')}]`;
231
+ }
232
+ const record = value as Record<string, unknown>;
233
+ const keys = Object.keys(record).sort();
234
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`).join(',')}}`;
235
+ }
236
+
237
+ /** sha256 of the stable JSON form — the digest every comparison uses. */
238
+ export function digestOf(value: unknown): string {
239
+ return createHash('sha256').update(stableJson(value)).digest('hex');
240
+ }
241
+
242
+ /** The evidence-and-comment digest of one judgment; a changed value is a conflicting rewrite. */
243
+ export function judgmentDigest(entry: {
244
+ selectedId: string;
245
+ date: string;
246
+ fact: string;
247
+ attribution: string;
248
+ comment: string;
249
+ evidence: JudgmentEvidence;
250
+ storyKey?: string;
251
+ }): string {
252
+ return digestOf({
253
+ selectedId: entry.selectedId,
254
+ storyKey: entry.storyKey ?? '',
255
+ date: entry.date,
256
+ fact: entry.fact,
257
+ attribution: entry.attribution,
258
+ comment: entry.comment,
259
+ evidence: { url: entry.evidence.url, checkedAt: entry.evidence.checkedAt },
260
+ });
261
+ }
262
+
263
+ /** An empty ledger for a run that has never committed (first initialization, R10 "首次初始化"). */
264
+ export function emptyLedger(now: string): JudgmentLedger {
265
+ return { version: 1, updatedAt: now, judgments: [] };
266
+ }
267
+
268
+ /** Parse the machine block. `error` is set for anything that is present but unreadable. */
269
+ export function parseConclusion(text: string): { ledger: JudgmentLedger | null; error: string | null } {
270
+ // `lastIndexOf`: the render preamble quotes both markers in prose, the block is the last one.
271
+ const begin = text.lastIndexOf(LEDGER_BEGIN);
272
+ const end = text.lastIndexOf(LEDGER_END);
273
+ if (begin < 0 && end < 0) {
274
+ return { ledger: null, error: null };
275
+ }
276
+ if (begin < 0 || end < begin) {
277
+ return { ledger: null, error: 'judgment ledger block markers are unbalanced' };
278
+ }
279
+ const body = text.slice(begin + LEDGER_BEGIN.length, end).trim();
280
+ const fenced = body.match(/```json\n([\s\S]*?)\n```/);
281
+ if (!fenced) {
282
+ return { ledger: null, error: 'judgment ledger block carries no ```json fence' };
283
+ }
284
+ try {
285
+ const parsed = JSON.parse(fenced[1]) as JudgmentLedger;
286
+ if (!parsed || !Array.isArray(parsed.judgments)) {
287
+ return { ledger: null, error: 'judgment ledger block has no judgments array' };
288
+ }
289
+ return { ledger: parsed, error: null };
290
+ } catch (error) {
291
+ return { ledger: null, error: `judgment ledger block is not valid JSON: ${String(error)}` };
292
+ }
293
+ }
294
+
295
+ /** Render the human-readable records plus the machine block the next run parses. */
296
+ export function renderConclusion(ledger: JudgmentLedger, preamble?: string): string {
297
+ const active = ledger.judgments.filter((entry) => entry.status !== 'superseded');
298
+ const retired = ledger.judgments.filter((entry) => entry.status === 'superseded');
299
+ const lines: string[] = [
300
+ '# 每日判断账本 · conclusion',
301
+ '',
302
+ '本文件是《每日AI乱炖》唯一的可写判断账本(ADR-054)。人工可读部分由确定性步骤生成,',
303
+ `机器块(${LEDGER_BEGIN} … ${LEDGER_END})请勿手改;更正记录一经提交不再改写。`,
304
+ '',
305
+ ];
306
+ if (preamble?.trim()) {
307
+ lines.push('## 本期更正说明', '', preamble.trim(), '');
308
+ }
309
+ lines.push(`## 现行判断(${active.length})`, '');
310
+ for (const entry of active) {
311
+ lines.push(`### ${entry.id} · ${entry.date}`, '');
312
+ lines.push(`- 事实:${entry.fact}`);
313
+ lines.push(`- 归因:${entry.attribution}`);
314
+ lines.push(`- 评论:${entry.comment}`);
315
+ lines.push(`- 证据:${entry.evidence.url}(核查于 ${entry.evidence.checkedAt})`);
316
+ lines.push(`- 关联选题:${entry.selectedId}${entry.storyKey ? ` · ${entry.storyKey}` : ''}`);
317
+ lines.push(`- 状态:${entry.status}`);
318
+ lines.push('');
319
+ }
320
+ lines.push(`## 被取代记录(${retired.length},保留不改写)`, '');
321
+ for (const entry of retired) {
322
+ lines.push(`- ${entry.id}(${entry.date})→ 由 ${entry.supersededBy ?? '未记录'} 取代:${entry.fact}`);
323
+ }
324
+ if (retired.length === 0) {
325
+ lines.push('- 无');
326
+ }
327
+ lines.push('');
328
+ lines.push('<!-- 机器块:确定性步骤写入 -->');
329
+ lines.push(LEDGER_BEGIN);
330
+ lines.push('```json');
331
+ lines.push(JSON.stringify(ledger, null, 2));
332
+ lines.push('```');
333
+ lines.push(LEDGER_END);
334
+ lines.push('');
335
+ return lines.join('\n');
336
+ }
337
+
338
+ /** Validate a proposal against the selection provenance and its own evidence. */
339
+ export function validateProposal(proposal: AlignmentProposal, selectedIds: Set<string>): { errors: string[] } {
340
+ const errors: string[] = [];
341
+ if (!proposal || !Array.isArray(proposal.judgments)) {
342
+ return { errors: ['proposal has no judgments array'] };
343
+ }
344
+ const seen = new Set<string>();
345
+ for (const entry of proposal.judgments) {
346
+ const label = entry?.id ? entry.id : '<missing id>';
347
+ if (!entry?.id || typeof entry.id !== 'string') {
348
+ errors.push(`${label}: judgment is missing a stable id`);
349
+ } else if (seen.has(entry.id)) {
350
+ errors.push(`${label}: duplicate judgment id in one proposal`);
351
+ }
352
+ if (entry?.id) {
353
+ seen.add(entry.id);
354
+ }
355
+ if (!entry.selectedId || !selectedIds.has(entry.selectedId)) {
356
+ errors.push(`${label}: selected id '${entry.selectedId}' is not in this run's selection`);
357
+ }
358
+ if (!entry.evidence?.url || !/^https?:\/\//.test(entry.evidence.url)) {
359
+ errors.push(`${label}: evidence needs an http(s) url`);
360
+ }
361
+ if (!entry.evidence?.checkedAt || Number.isNaN(Date.parse(entry.evidence.checkedAt))) {
362
+ errors.push(`${label}: evidence needs an ISO checkedAt`);
363
+ }
364
+ for (const field of ['fact', 'attribution', 'comment', 'date'] as const) {
365
+ if (!entry[field] || typeof entry[field] !== 'string') {
366
+ errors.push(`${label}: missing ${field}`);
367
+ }
368
+ }
369
+ }
370
+ return { errors };
371
+ }
372
+
373
+ /** A correction ID bound to its superseded judgment — stable, so 0396 can dedupe deliveries. */
374
+ export function correctionIdFor(supersedes: string, judgmentId: string): string {
375
+ return `corr-${digestOf({ supersedes, judgmentId }).slice(0, 16)}`;
376
+ }
377
+
378
+ /**
379
+ * Reconcile a proposal against the committed ledger.
380
+ *
381
+ * Same id + same digest → replay (no append). Same id + different digest → `conflict`: a confirmed
382
+ * judgment is never overwritten. Superseded records stay in place with `supersededBy` set.
383
+ */
384
+ export function reconcileLedger(
385
+ ledger: JudgmentLedger,
386
+ proposal: AlignmentProposal,
387
+ selectedIds: Set<string>,
388
+ now: string,
389
+ ): ReconcileResult {
390
+ const validation = validateProposal(proposal, selectedIds);
391
+ const result: ReconcileResult = {
392
+ status: 'no-op',
393
+ reason: 'no new judgments',
394
+ ledger: { ...ledger, judgments: [...ledger.judgments] },
395
+ appended: [],
396
+ superseded: [],
397
+ corrections: [],
398
+ errors: validation.errors,
399
+ };
400
+ if (validation.errors.length > 0) {
401
+ result.status = 'stop' as ReconcileResult['status'];
402
+ result.reason = 'proposal failed validation — nothing committed';
403
+ return result;
404
+ }
405
+
406
+ const byId = new Map(ledger.judgments.map((entry) => [entry.id, entry]));
407
+ const next: Judgment[] = [...ledger.judgments];
408
+
409
+ for (const entry of proposal.judgments) {
410
+ const digest = judgmentDigest(entry);
411
+ const existing = byId.get(entry.id);
412
+ if (existing) {
413
+ if (existing.contentDigest === digest) {
414
+ continue; // replay: identical judgment already committed
415
+ }
416
+ result.status = 'conflict';
417
+ result.reason = `judgment '${entry.id}' already exists with different content`;
418
+ result.errors.push(`${entry.id}: conflict with the committed judgment`);
419
+ return result;
420
+ }
421
+ const target = entry.supersedes ? byId.get(entry.supersedes) : null;
422
+ if (entry.supersedes && !target) {
423
+ result.status = 'conflict';
424
+ result.reason = `supersedes target '${entry.supersedes}' is not in the ledger`;
425
+ result.errors.push(`${entry.id}: unknown supersedes target '${entry.supersedes}'`);
426
+ return result;
427
+ }
428
+ if (target && target.status === 'superseded') {
429
+ result.status = 'conflict';
430
+ result.reason = `supersedes target '${entry.supersedes}' was already superseded`;
431
+ result.errors.push(`${entry.id}: '${entry.supersedes}' is already superseded`);
432
+ return result;
433
+ }
434
+ next.push({
435
+ id: entry.id,
436
+ selectedId: entry.selectedId,
437
+ ...(entry.storyKey ? { storyKey: entry.storyKey } : {}),
438
+ date: entry.date,
439
+ fact: entry.fact,
440
+ attribution: entry.attribution,
441
+ comment: entry.comment,
442
+ evidence: { url: entry.evidence.url, checkedAt: entry.evidence.checkedAt },
443
+ supersedes: entry.supersedes ?? null,
444
+ status: 'pending',
445
+ supersededBy: null,
446
+ contentDigest: digest,
447
+ });
448
+ result.appended.push(entry.id);
449
+ if (target) {
450
+ result.superseded.push(target.id);
451
+ result.corrections.push({
452
+ correctionId: correctionIdFor(target.id, entry.id),
453
+ supersedes: target.id,
454
+ judgmentId: entry.id,
455
+ selectedId: entry.selectedId,
456
+ wording: entry.comment,
457
+ evidence: { url: entry.evidence.url, checkedAt: entry.evidence.checkedAt },
458
+ });
459
+ }
460
+ }
461
+
462
+ if (result.appended.length > 0) {
463
+ result.status = 'applied';
464
+ result.reason = `appended ${result.appended.length} judgment(s)`;
465
+ const supersededSet = new Set(result.superseded);
466
+ result.ledger = {
467
+ version: 1,
468
+ updatedAt: now,
469
+ judgments: next.map((entry) => {
470
+ if (!supersededSet.has(entry.id)) {
471
+ return entry;
472
+ }
473
+ const replacement = result.corrections.find((correction) => correction.supersedes === entry.id);
474
+ return {
475
+ ...entry,
476
+ status: 'superseded' as JudgmentStatus,
477
+ supersededBy: replacement?.judgmentId ?? null,
478
+ };
479
+ }),
480
+ };
481
+ }
482
+ return result;
483
+ }
484
+
485
+ /** Same-directory temp file + rename: a reader never sees a partial ledger. */
486
+ export function writeAtomic(destPath: string, text: string): void {
487
+ const parent = dirname(destPath);
488
+ if (!existsSync(parent)) {
489
+ mkdirSync(parent, { recursive: true });
490
+ }
491
+ const tmpPath = `${destPath}.tmp.${process.pid}.${Date.now()}`;
492
+ const mode = existsSync(destPath) ? statSync(destPath).mode & 0o777 : 0o644;
493
+ try {
494
+ writeFileSync(tmpPath, text, { encoding: 'utf-8', mode });
495
+ renameSync(tmpPath, destPath);
496
+ } catch (error) {
497
+ rmSync(tmpPath, { force: true });
498
+ throw error;
499
+ }
500
+ }
501
+
502
+ /** Read the snapshot the draft consumes; `null` when absent. */
503
+ export function readSnapshot(snapshotPath: string): JudgmentSnapshot | null {
504
+ if (!existsSync(snapshotPath)) {
505
+ return null;
506
+ }
507
+ try {
508
+ return JSON.parse(readFileSync(snapshotPath, 'utf-8')) as JudgmentSnapshot;
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Commit one alignment proposal.
516
+ *
517
+ * Order matters and is the whole contract: read → validate → lock → CAS → backup → atomic write →
518
+ * snapshot → receipt. Every early return writes a receipt too, so a stop or a lost CAS leaves the
519
+ * same auditable artifact as a success.
520
+ */
521
+ export async function commitAlignment(options: CommitOptions): Promise<CommitReceipt> {
522
+ const { ledgerPath, snapshotPath, receiptPath, proposal, selectedIds, runDate, runId, now } = options;
523
+ const lock = options.lock ?? NULL_LOCK;
524
+ const proposalDigest = digestOf(proposal.judgments ?? []);
525
+ const receipt = (filled?: Partial<CommitReceipt>): CommitReceipt => ({
526
+ version: 1,
527
+ status: 'stop',
528
+ reason: '',
529
+ lock: 'none',
530
+ ledgerPath,
531
+ snapshotPath,
532
+ backupPath: null,
533
+ ledgerDigestBefore: null,
534
+ ledgerDigestAfter: null,
535
+ proposalDigest,
536
+ initialized: false,
537
+ snapshotReused: false,
538
+ appended: [],
539
+ superseded: [],
540
+ correctionIds: [],
541
+ droppedByReselection: options.droppedByReselection ?? [],
542
+ recovery: null,
543
+ errors: [],
544
+ committedAt: now,
545
+ ...filled,
546
+ });
547
+
548
+ // 1. Read the historical state. Unavailable or corrupt is a STOP, never a rebuild.
549
+ let before: string | null = null;
550
+ let ledger: JudgmentLedger;
551
+ let initialized = false;
552
+ if (existsSync(ledgerPath)) {
553
+ try {
554
+ before = readFileSync(ledgerPath, 'utf-8');
555
+ } catch (error) {
556
+ const stopped = receipt({
557
+ reason: `judgment ledger is unreadable: ${String(error)}`,
558
+ backupPath: `${ledgerPath}.bak`,
559
+ recovery: { ledgerPath, backupPath: `${ledgerPath}.bak`, action: 'restore the ledger, then re-run' },
560
+ errors: ['ledger-unreadable'],
561
+ });
562
+ persistReceipt(receiptPath, stopped);
563
+ return stopped;
564
+ }
565
+ const parsed = parseConclusion(before);
566
+ if (parsed.error) {
567
+ const stopped = receipt({
568
+ status: 'stop',
569
+ reason: `judgment ledger is corrupt: ${parsed.error}`,
570
+ ledgerDigestBefore: digestOf(before),
571
+ backupPath: `${ledgerPath}.corrupt`,
572
+ recovery: {
573
+ ledgerPath,
574
+ backupPath: `${ledgerPath}.corrupt`,
575
+ action: 'inspect the machine block; restore a backup; do not regenerate the ledger from a proposal',
576
+ },
577
+ errors: [parsed.error],
578
+ });
579
+ // Keep the corrupt text so the operator can diff it, and never overwrite it.
580
+ safeCopy(ledgerPath, `${ledgerPath}.corrupt`);
581
+ persistReceipt(receiptPath, stopped);
582
+ return stopped;
583
+ }
584
+ ledger = parsed.ledger ?? emptyLedger(now);
585
+ } else {
586
+ ledger = emptyLedger(now);
587
+ initialized = true;
588
+ }
589
+ const beforeDigest = before === null ? null : digestOf(before);
590
+
591
+ // 2. Serialize on the existing kk lock (scoped to the ledger), then CAS against the re-read.
592
+ let lockState: CommitReceipt['lock'] = 'none';
593
+ let acquired = true;
594
+ if (options.lock) {
595
+ acquired = await lock.acquire(LEDGER_LOCK_NAME, runId);
596
+ lockState = acquired ? 'held' : 'contended';
597
+ }
598
+ if (!acquired) {
599
+ const stopped = receipt({
600
+ status: 'conflict',
601
+ reason: 'another run holds the judgment ledger lock',
602
+ lock: lockState,
603
+ ledgerDigestBefore: beforeDigest,
604
+ recovery: { ledgerPath, backupPath: null, action: 're-run after the holder releases the claim' },
605
+ });
606
+ persistReceipt(receiptPath, stopped);
607
+ return stopped;
608
+ }
609
+
610
+ try {
611
+ const reRead = existsSync(ledgerPath) ? readFileSync(ledgerPath, 'utf-8') : null;
612
+ const reReadDigest = reRead === null ? null : digestOf(reRead);
613
+ if (reReadDigest !== beforeDigest) {
614
+ const stopped = receipt({
615
+ status: 'conflict',
616
+ reason: 'judgment ledger changed while the proposal was being prepared (CAS mismatch)',
617
+ lock: lockState,
618
+ ledgerDigestBefore: beforeDigest,
619
+ recovery: { ledgerPath, backupPath: null, action: 're-align against the newest ledger' },
620
+ });
621
+ persistReceipt(receiptPath, stopped);
622
+ return stopped;
623
+ }
624
+
625
+ const reconciled = reconcileLedger(ledger, proposal, selectedIds, now);
626
+ if (reconciled.status === 'stop') {
627
+ const stopped = receipt({
628
+ status: 'stop',
629
+ reason: reconciled.reason,
630
+ lock: lockState,
631
+ ledgerDigestBefore: beforeDigest,
632
+ recovery: { ledgerPath, backupPath: null, action: 'fix the proposal and re-align' },
633
+ errors: reconciled.errors,
634
+ });
635
+ persistReceipt(receiptPath, stopped);
636
+ return stopped;
637
+ }
638
+ if (reconciled.status === 'conflict') {
639
+ const stopped = receipt({
640
+ status: 'conflict',
641
+ reason: reconciled.reason,
642
+ lock: lockState,
643
+ ledgerDigestBefore: beforeDigest,
644
+ recovery: {
645
+ ledgerPath,
646
+ backupPath: null,
647
+ action: 'a confirmed judgment differs; publish a superseding judgment instead',
648
+ },
649
+ errors: reconciled.errors,
650
+ });
651
+ persistReceipt(receiptPath, stopped);
652
+ return stopped;
653
+ }
654
+
655
+ // 3. Snapshot: reuse the legal one when there is nothing new; a changed digest on the same
656
+ // run date is a conflict (the snapshot is immutable evidence for the draft).
657
+ const existingSnapshot = readSnapshot(snapshotPath);
658
+ if (reconciled.status === 'no-op') {
659
+ const reusable =
660
+ existingSnapshot !== null &&
661
+ existingSnapshot.runDate === runDate &&
662
+ (beforeDigest === null || existingSnapshot.ledgerDigest === beforeDigest);
663
+ if (reusable) {
664
+ const noop = receipt({
665
+ status: 'no-op',
666
+ reason: 'replayed proposal — ledger and snapshot already carry these judgments',
667
+ lock: lockState,
668
+ ledgerDigestBefore: beforeDigest,
669
+ ledgerDigestAfter: beforeDigest,
670
+ initialized: false,
671
+ snapshotReused: true,
672
+ correctionIds: existingSnapshot.corrections.map((entry) => entry.correctionId),
673
+ });
674
+ persistReceipt(receiptPath, noop);
675
+ return noop;
676
+ }
677
+ // No new judgment but no legal snapshot yet: freeze one from the committed ledger.
678
+ const afterText = before ?? renderConclusion(reconciled.ledger);
679
+ const afterDigest = digestOf(afterText);
680
+ const snapshot = buildSnapshot(
681
+ reconciled.ledger,
682
+ runDate,
683
+ now,
684
+ afterDigest,
685
+ proposalDigest,
686
+ resolvePreamble(proposal, before),
687
+ );
688
+ writeAtomic(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`);
689
+ const noop = receipt({
690
+ status: 'no-op',
691
+ reason: 'no new judgment — the committed ledger is the snapshot for this run',
692
+ lock: lockState,
693
+ ledgerDigestBefore: beforeDigest,
694
+ ledgerDigestAfter: afterDigest,
695
+ initialized: false,
696
+ snapshotReused: false,
697
+ correctionIds: snapshot.corrections.map((entry) => entry.correctionId),
698
+ });
699
+ persistReceipt(receiptPath, noop);
700
+ return noop;
701
+ }
702
+
703
+ if (
704
+ existingSnapshot !== null &&
705
+ existingSnapshot.runDate === runDate &&
706
+ existingSnapshot.ledgerDigest !== (beforeDigest ?? '')
707
+ ) {
708
+ // The run already froze a different history: adopting the new one would rewrite evidence.
709
+ const stopped = receipt({
710
+ status: 'conflict',
711
+ reason: 'this run already froze a snapshot from a different ledger revision',
712
+ lock: lockState,
713
+ ledgerDigestBefore: beforeDigest,
714
+ backupPath: null,
715
+ recovery: { ledgerPath, backupPath: null, action: 'start a new run directory for the new judgments' },
716
+ });
717
+ persistReceipt(receiptPath, stopped);
718
+ return stopped;
719
+ }
720
+
721
+ const preamble = resolvePreamble(proposal, before);
722
+ const text = renderConclusion(reconciled.ledger, preamble);
723
+ if (before !== null) {
724
+ const backupPath = `${ledgerPath}.bak-${now.replace(/[:.]/g, '')}`;
725
+ copyFileSync(ledgerPath, backupPath);
726
+ writeAtomic(ledgerPath, text);
727
+ const afterDigest = digestOf(readFileSync(ledgerPath, 'utf-8'));
728
+ const snapshot = buildSnapshot(
729
+ reconciled.ledger,
730
+ runDate,
731
+ now,
732
+ afterDigest,
733
+ proposalDigest,
734
+ resolvePreamble(proposal, before),
735
+ );
736
+ writeAtomic(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`);
737
+ const applied = receipt({
738
+ status: 'applied',
739
+ reason: reconciled.reason,
740
+ lock: lockState,
741
+ ledgerDigestBefore: beforeDigest,
742
+ ledgerDigestAfter: afterDigest,
743
+ backupPath,
744
+ snapshotReused: false,
745
+ appended: reconciled.appended,
746
+ superseded: reconciled.superseded,
747
+ correctionIds: snapshot.corrections.map((entry) => entry.correctionId),
748
+ });
749
+ persistReceipt(receiptPath, applied);
750
+ return applied;
751
+ }
752
+
753
+ writeAtomic(ledgerPath, text);
754
+ const afterDigest = digestOf(readFileSync(ledgerPath, 'utf-8'));
755
+ const snapshot = buildSnapshot(
756
+ reconciled.ledger,
757
+ runDate,
758
+ now,
759
+ afterDigest,
760
+ proposalDigest,
761
+ resolvePreamble(proposal, before),
762
+ );
763
+ writeAtomic(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`);
764
+ const applied = receipt({
765
+ status: 'applied',
766
+ reason: `${reconciled.reason} (first initialization)`,
767
+ lock: lockState,
768
+ ledgerDigestBefore: null,
769
+ ledgerDigestAfter: afterDigest,
770
+ backupPath: null,
771
+ initialized,
772
+ snapshotReused: false,
773
+ appended: reconciled.appended,
774
+ superseded: reconciled.superseded,
775
+ correctionIds: snapshot.corrections.map((entry) => entry.correctionId),
776
+ });
777
+ persistReceipt(receiptPath, applied);
778
+ return applied;
779
+ } finally {
780
+ if (options.lock) {
781
+ await lock.release(LEDGER_LOCK_NAME, runId);
782
+ }
783
+ }
784
+ }
785
+
786
+ /** Keep an existing `## 本期更正说明` block when the ledger is rewritten. */
787
+ export function readPreamble(text: string | null): string | undefined {
788
+ if (!text) {
789
+ return undefined;
790
+ }
791
+ const match = text.match(/## 本期更正说明\n\n([\s\S]*?)\n\n## /);
792
+ return match ? match[1].trim() : undefined;
793
+ }
794
+
795
+ /** The retired part of a judgment record, projected without the lifecycle fields. */
796
+ function retiredRecord(entry: Judgment): SupersededRecord {
797
+ return {
798
+ id: entry.id,
799
+ date: entry.date,
800
+ fact: entry.fact,
801
+ attribution: entry.attribution,
802
+ comment: entry.comment,
803
+ supersededBy: entry.supersededBy as string,
804
+ };
805
+ }
806
+
807
+ /** The correction sentence: what was said, and what replaces it — renderable, no invention needed. */
808
+ function correctionSentence(retired: SupersededRecord, replacement: Judgment | undefined): string {
809
+ const corrected = replacement?.comment?.trim() || '(新判断)';
810
+ return `${retired.date} 的判断「${retired.fact}」经核验有误,现更正为:${corrected}`;
811
+ }
812
+
813
+ /** The preamble the draft must carry: this proposal's wording wins, the committed one is the fallback. */
814
+ export function resolvePreamble(proposal: AlignmentProposal, ledgerText: string | null): string | undefined {
815
+ const proposed = proposal.preamble?.trim();
816
+ return proposed ? proposed : readPreamble(ledgerText);
817
+ }
818
+
819
+ /**
820
+ * Freeze the run-scoped snapshot the draft (0385) and corrections (0396) consume.
821
+ *
822
+ * The snapshot is a *projection*, not a second ledger: retired records are excluded from
823
+ * `judgments` (they may not be drafted from) but carried verbatim in `superseded` and inside each
824
+ * `correction.retired`, so "what was wrong" is answerable from the snapshot alone.
825
+ */
826
+ export function buildSnapshot(
827
+ ledger: JudgmentLedger,
828
+ runDate: string,
829
+ now: string,
830
+ ledgerDigest: string,
831
+ proposalDigest: string,
832
+ preamble?: string | null,
833
+ ): JudgmentSnapshot {
834
+ const retired = ledger.judgments.filter((entry) => entry.status === 'superseded' && entry.supersededBy);
835
+ const superseded = retired.map((entry) => retiredRecord(entry));
836
+ const corrections: Correction[] = retired.map((entry) => {
837
+ const replacement = ledger.judgments.find((candidate) => candidate.id === entry.supersededBy);
838
+ const record = retiredRecord(entry);
839
+ return {
840
+ correctionId: correctionIdFor(entry.id, entry.supersededBy as string),
841
+ supersedes: entry.id,
842
+ judgmentId: entry.supersededBy as string,
843
+ selectedId: replacement?.selectedId ?? entry.selectedId,
844
+ wording: replacement?.comment ?? '',
845
+ text: correctionSentence(record, replacement),
846
+ retired: record,
847
+ evidence: replacement?.evidence ?? entry.evidence,
848
+ };
849
+ });
850
+ return {
851
+ version: 1,
852
+ runDate,
853
+ frozenAt: now,
854
+ ledgerDigest,
855
+ proposalDigest,
856
+ judgments: ledger.judgments.filter((entry) => entry.status !== 'superseded'),
857
+ superseded,
858
+ corrections,
859
+ preamble: preamble?.trim() || null,
860
+ };
861
+ }
862
+
863
+ /**
864
+ * Reselect tolerance for the *stage*, not the ledger (0384 P3 follow-up).
865
+ *
866
+ * The `align` proposal is authored inside the `curate` node; `curate-check`, `curate-fix` and the
867
+ * `--final` fallback settle the plan afterwards, so a proposal can legitimately cite a selected id
868
+ * the settled plan no longer carries. {@link validateProposal} refuses that id — correctly, an
869
+ * unknown id must never be committed — so the stage drops those judgments *before* the commit and
870
+ * records the ids in the receipt: the surviving judgments still commit, and a proposal with nothing
871
+ * committable left behaves exactly like the documented empty proposal (reuse this run's snapshot).
872
+ */
873
+ export function dropReselectedJudgments(
874
+ proposal: AlignmentProposal,
875
+ selectedIds: Set<string>,
876
+ ): { proposal: AlignmentProposal; dropped: string[]; droppedIds: string[] } {
877
+ const keep: ProposalEntry[] = [];
878
+ const dropped: string[] = [];
879
+ const droppedIds: string[] = [];
880
+ for (const entry of proposal.judgments ?? []) {
881
+ const cited = typeof entry?.selectedId === 'string' ? entry.selectedId.trim() : '';
882
+ if (cited !== '' && !selectedIds.has(cited)) {
883
+ dropped.push(`${entry.id || '<missing id>'}=> ${cited}`);
884
+ droppedIds.push(entry.id || '<missing id>');
885
+ continue;
886
+ }
887
+ keep.push(entry);
888
+ }
889
+ return {
890
+ proposal: dropped.length === 0 ? proposal : { ...proposal, judgments: keep },
891
+ dropped,
892
+ droppedIds,
893
+ };
894
+ }
895
+
896
+ function persistReceipt(receiptPath: string, receipt: CommitReceipt): void {
897
+ writeAtomic(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
898
+ }
899
+
900
+ function safeCopy(from: string, to: string): void {
901
+ try {
902
+ copyFileSync(from, to);
903
+ } catch {
904
+ // best-effort: the receipt still names the path
905
+ }
906
+ }