@gobing-ai/knowledge-kit 0.1.19 → 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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/board/collect/index.js +1 -0
- package/dist/board/daily-voice/index.js +1315 -264
- package/dist/board/itc/index.js +1 -0
- package/dist/index.js +14674 -8775
- package/package.json +1 -1
- package/plugins/generations/dailynews-gen/dist/index.js +285 -16
- package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
- package/plugins/generations/dailynews-gen/src/index.ts +23 -4
- package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
- package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
- package/plugins/generations/image-gen/README.md +31 -31
- package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
- package/plugins/generations/image-gen/config.example.yaml +3 -0
- package/plugins/generations/image-gen/dist/index.js +154 -14
- package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
- package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
- package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
- package/plugins/generations/image-gen/src/presets.ts +6 -5
- package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
- package/plugins/generations/image-gen/src/providers/types.ts +11 -1
- package/plugins/generations/music-gen/README.md +277 -0
- package/plugins/generations/music-gen/dist/index.js +23544 -0
- package/plugins/generations/music-gen/package.json +24 -0
- package/plugins/generations/music-gen/plugin.json +23 -0
- package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
- package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
- package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
- package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
- package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
- package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
- package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
- package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
- package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
- package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
- package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
- package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
- package/plugins/generations/music-gen/src/artifact.ts +223 -0
- package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
- package/plugins/generations/music-gen/src/audio/master.ts +267 -0
- package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
- package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
- package/plugins/generations/music-gen/src/audio.ts +122 -0
- package/plugins/generations/music-gen/src/brief.ts +191 -0
- package/plugins/generations/music-gen/src/config.ts +451 -0
- package/plugins/generations/music-gen/src/content.ts +199 -0
- package/plugins/generations/music-gen/src/digest.ts +100 -0
- package/plugins/generations/music-gen/src/index.ts +147 -0
- package/plugins/generations/music-gen/src/job.ts +131 -0
- package/plugins/generations/music-gen/src/plugin.ts +371 -0
- package/plugins/generations/music-gen/src/presets.ts +918 -0
- package/plugins/generations/music-gen/src/render.ts +87 -0
- package/plugins/generations/music-gen/src/request.ts +102 -0
- package/plugins/generations/music-gen/src/spend.ts +495 -0
- package/plugins/generations/music-gen/tsconfig.json +8 -0
- package/plugins/kk/config.example.yaml +3 -0
- package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
- package/plugins/kk/plugin.json +1 -1
- package/plugins/kk/publish-presets/daily-ai-voice.json +48 -7
- package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
- package/plugins/kk/scripts/cover-compositor.ts +380 -32
- package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
- package/plugins/kk/scripts/daily-stages.ts +897 -34
- package/plugins/kk/scripts/episode-identity.ts +180 -0
- package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
- package/plugins/kk/scripts/music-stages.ts +624 -0
- package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
- package/plugins/kk/scripts/source-citation.ts +187 -0
- package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
- package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
- package/plugins/kk/skills/content-judge/SKILL.md +11 -6
- package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
- package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
- package/plugins/kk/skills/content-safety/SKILL.md +12 -0
- package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
- package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
- package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
- package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
- package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
- package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
- package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
- package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
- package/plugins/kk/skills/publish/SKILL.md +11 -0
- package/plugins/kk/skills/web-automation/SKILL.md +31 -1
- package/plugins/kk/workflows/kk-collect.yaml +8 -4
- package/plugins/kk/workflows/kk-daily-ai-voice.yaml +10 -9
- package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +11 -9
- package/plugins/kk/workflows/kk-music.yaml +328 -0
- package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
- package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
- package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
- package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/csdn-pub/dist/index.js +11 -1
- package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/infoq-pub/dist/index.js +11 -1
- package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/jike-pub/dist/index.js +11 -1
- package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/juejin-pub/dist/index.js +11 -1
- package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/linkedin-pub/dist/index.js +54 -7
- package/plugins/publishings/linkedin-pub/dist/profile-check.js +43 -6
- package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
- package/plugins/publishings/podcast-pub/dist/index.js +586 -20
- package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
- package/plugins/publishings/podcast-pub/src/index.ts +257 -5
- package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
- package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
- package/plugins/publishings/shipinhao-pub/dist/index.js +437 -32
- package/plugins/publishings/shipinhao-pub/dist/profile-check.js +14 -2
- package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
- package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +492 -0
- package/plugins/publishings/shipinhao-pub/src/flow.ts +227 -12
- package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
- package/plugins/publishings/sspai-pub/dist/index.js +11 -1
- package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/substack-pub/dist/index.js +11 -1
- package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/surfdash-pub/dist/index.js +122 -28
- package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
- package/plugins/publishings/surfdash-pub/src/index.ts +159 -25
- package/plugins/publishings/surfdash-pub/src/topic-claims.ts +37 -4
- package/plugins/publishings/threads-pub/dist/index.js +9206 -296
- package/plugins/publishings/threads-pub/dist/profile-check.js +21149 -0
- package/plugins/publishings/threads-pub/package.json +3 -1
- package/plugins/publishings/threads-pub/plugin.json +6 -1
- package/plugins/publishings/threads-pub/src/index.ts +8 -1
- package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
- package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
- package/plugins/publishings/wechatmp-pub/dist/index.js +18 -1
- package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/wechatmp-pub/src/flow.ts +13 -0
- package/plugins/publishings/weibo-pub/dist/index.js +57 -3
- package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/weibo-pub/src/index.ts +74 -2
- package/plugins/publishings/x-pub/dist/index.js +274 -44
- package/plugins/publishings/x-pub/dist/profile-check.js +14 -2
- package/plugins/publishings/x-pub/src/index.ts +15 -1
- package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
- package/plugins/publishings/xhs-pub/dist/index.js +11 -1
- package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
- package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 0394 R1/R16 — where a rendered citation may legitimately point.
|
|
3
|
+
*
|
|
4
|
+
* The ingest hop writes three independent provenance slots (`horizon-ingest/src/index.ts:125`):
|
|
5
|
+
*
|
|
6
|
+
* `sourceUri` the headline URL the digest linked — the *retrieval* destination.
|
|
7
|
+
* `metadata.source` the collector classification from the digest's source line
|
|
8
|
+
* (`hackernews · user1 · …`), i.e. the transport, not a publisher.
|
|
9
|
+
* `metadata.references` the `<details>References</details>` links — item-specific evidence.
|
|
10
|
+
*
|
|
11
|
+
* The editorial renderer used to print `metadata.source` beside `sourceUri`, so a link that lands
|
|
12
|
+
* on `example.com/alpha` was labelled `hackernews` and an aggregator permalink was labelled as if
|
|
13
|
+
* it were the publisher. This module resolves the pair the renderer may emit, without guessing:
|
|
14
|
+
*
|
|
15
|
+
* 1. A retrieval URL that is a known discussion/aggregator platform page is a *transport*: one
|
|
16
|
+
* off-origin reference then corroborates an original → cite that reference, labelled by its own
|
|
17
|
+
* host (the identity is read from the URL that is actually linked, never inferred). A reference
|
|
18
|
+
* that itself lands on a known aggregator host is another transport page, never an original, so
|
|
19
|
+
* it can never corroborate one.
|
|
20
|
+
* 2. Otherwise cite the retrieval URL. A publisher's own page is already the verifiable origin and
|
|
21
|
+
* stays authoritative — a secondary reference is not allowed to displace it. The label is the
|
|
22
|
+
* collector classification only when that classification corroborates the destination host
|
|
23
|
+
* (existing taxonomy preserved), else the host.
|
|
24
|
+
* 3. A retrieval URL that is a known discussion/aggregator platform page is labelled explicitly
|
|
25
|
+
* (`docs/tasks/0394`, "when an aggregator is the only verifiable source, label it explicitly").
|
|
26
|
+
* 4. No http(s) candidate at all → `null`; the caller renders no link (unchanged behaviour).
|
|
27
|
+
*
|
|
28
|
+
* Deliberately absent: redirect fetching, publisher-name inference, and any URL backfill. An
|
|
29
|
+
* ambiguous reference set declines to pick — two different off-origin origins prove nothing.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** How the resolved link was chosen. Reported by audit tooling; never part of the rendered text. */
|
|
33
|
+
export type CitationKind = 'direct' | 'original' | 'aggregator-fallback';
|
|
34
|
+
|
|
35
|
+
export interface SourceCitation {
|
|
36
|
+
/** The `href` the citation links to: a corroborated original, else the retrieval URL. */
|
|
37
|
+
url: string;
|
|
38
|
+
/** The link text: a host (or a corroborated classification), plus the marker when aggregator. */
|
|
39
|
+
label: string;
|
|
40
|
+
kind: CitationKind;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Marker appended to a link that is known to be a transport/aggregator page rather than the
|
|
45
|
+
* publisher's own page. Mechanical, not editorial wording — the writer skill owns prose.
|
|
46
|
+
*/
|
|
47
|
+
export const AGGREGATOR_MARKER = '(聚合)';
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The platforms whose pages aggregate someone else's article, keyed by the collector classification
|
|
51
|
+
* the digest source line carries (`hackernews · user1 · … · [Discussion](…)`). Only the two transports
|
|
52
|
+
* this corpus actually emits are listed; an unknown classification never makes a host an aggregator,
|
|
53
|
+
* because that would be a guess (0394 design, "no guessed publishers").
|
|
54
|
+
*/
|
|
55
|
+
const AGGREGATOR_HOSTS: Readonly<Record<string, readonly string[]>> = {
|
|
56
|
+
hackernews: ['news.ycombinator.com'],
|
|
57
|
+
reddit: ['reddit.com', 'old.reddit.com', 'redd.it'],
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const HTTP_URL = /^https?:\/\//i;
|
|
61
|
+
|
|
62
|
+
/** A trimmed `http(s)` URL, or `null` — the only scheme a citation may carry. */
|
|
63
|
+
function httpUrl(raw: unknown): URL | null {
|
|
64
|
+
if (typeof raw !== 'string') return null;
|
|
65
|
+
const trimmed = raw.trim();
|
|
66
|
+
if (!HTTP_URL.test(trimmed)) return null;
|
|
67
|
+
try {
|
|
68
|
+
return new URL(trimmed);
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Host identity for a label: lowercased, `www.` stripped — the same normalisation the renderer used. */
|
|
75
|
+
function hostOf(url: URL): string {
|
|
76
|
+
return url.hostname.toLowerCase().replace(/^www\./, '');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `metadata.source` as the collector classification, or `''` when absent/blank/non-string. */
|
|
80
|
+
function classificationOf(doc: Record<string, unknown> | null | undefined): string {
|
|
81
|
+
const meta = doc?.metadata;
|
|
82
|
+
if (meta === null || typeof meta !== 'object') return '';
|
|
83
|
+
const source = (meta as Record<string, unknown>).source;
|
|
84
|
+
return typeof source === 'string' ? source.trim() : '';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `metadata.references`, http(s) only, de-duplicated by URL — the item-specific evidence set. */
|
|
88
|
+
function referenceUrls(doc: Record<string, unknown> | null | undefined): string[] {
|
|
89
|
+
const meta = doc?.metadata;
|
|
90
|
+
if (meta === null || typeof meta !== 'object') return [];
|
|
91
|
+
const raw = (meta as Record<string, unknown>).references;
|
|
92
|
+
if (!Array.isArray(raw)) return [];
|
|
93
|
+
const urls: string[] = [];
|
|
94
|
+
for (const entry of raw) {
|
|
95
|
+
const url = httpUrl(entry);
|
|
96
|
+
if (url !== null && !urls.includes(url.toString())) urls.push(url.toString());
|
|
97
|
+
}
|
|
98
|
+
return urls;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Does the collector classification describe this destination? (`openai.com` ~ `openai.com`). */
|
|
102
|
+
function corroborates(classification: string, host: string): boolean {
|
|
103
|
+
if (classification === '') return false;
|
|
104
|
+
const normalized = classification
|
|
105
|
+
.toLowerCase()
|
|
106
|
+
.replace(HTTP_URL, '')
|
|
107
|
+
.replace(/^www\./, '')
|
|
108
|
+
.replace(/\/.*$/, '');
|
|
109
|
+
return normalized !== '' && (host === normalized || host.endsWith(`.${normalized}`));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Does `host` sit under one of these platform domains? */
|
|
113
|
+
function matchesAggregatorHost(hosts: readonly string[], host: string): boolean {
|
|
114
|
+
return hosts.some((aggregator) => host === aggregator || host.endsWith(`.${aggregator}`));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Is this host the transport platform the classification names (a page about someone else's item)? */
|
|
118
|
+
function isAggregator(classification: string, host: string): boolean {
|
|
119
|
+
const hosts = AGGREGATOR_HOSTS[classification.toLowerCase()];
|
|
120
|
+
return hosts !== undefined && matchesAggregatorHost(hosts, host);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Is this host *any* platform in the aggregator table, whatever the classification says? The
|
|
125
|
+
* classification only decides the marker (rule 3); for corroboration the host alone says "transport",
|
|
126
|
+
* because an unclassified permalink on a known aggregator is still not an original.
|
|
127
|
+
*/
|
|
128
|
+
function isKnownAggregatorHost(host: string): boolean {
|
|
129
|
+
return Object.values(AGGREGATOR_HOSTS).some((hosts) => matchesAggregatorHost(hosts, host));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Cite the retrieval URL: corroborated classification, else the verified host; aggregator marked. */
|
|
133
|
+
function citeRetrieval(url: URL, classification: string): SourceCitation {
|
|
134
|
+
const host = hostOf(url);
|
|
135
|
+
if (isAggregator(classification, host)) {
|
|
136
|
+
return { url: url.toString(), label: `${host}${AGGREGATOR_MARKER}`, kind: 'aggregator-fallback' };
|
|
137
|
+
}
|
|
138
|
+
return { url: url.toString(), label: corroborates(classification, host) ? classification : host, kind: 'direct' };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Resolve the one citation a rendered item may carry. `null` means "no verifiable link" — the
|
|
143
|
+
* caller emits no source line, exactly as before this change.
|
|
144
|
+
*/
|
|
145
|
+
export function resolveSourceCitation(
|
|
146
|
+
doc: Record<string, unknown> | null | undefined,
|
|
147
|
+
sourceUri: unknown,
|
|
148
|
+
): SourceCitation | null {
|
|
149
|
+
const classification = classificationOf(doc);
|
|
150
|
+
const retrieval = httpUrl(sourceUri);
|
|
151
|
+
if (retrieval === null) {
|
|
152
|
+
// No retrieval URL: a usable reference is still evidence, and its host is its identity — but a
|
|
153
|
+
// reference that is itself a transport page keeps the aggregator marker (never a bare original).
|
|
154
|
+
const references = referenceUrls(doc)
|
|
155
|
+
.map((raw) => httpUrl(raw))
|
|
156
|
+
.filter((url): url is URL => url !== null);
|
|
157
|
+
const original = references.find((url) => !isKnownAggregatorHost(hostOf(url)));
|
|
158
|
+
if (original !== undefined) {
|
|
159
|
+
return { url: original.toString(), label: hostOf(original), kind: 'original' };
|
|
160
|
+
}
|
|
161
|
+
const [transport] = references;
|
|
162
|
+
if (transport === undefined) return null;
|
|
163
|
+
const host = hostOf(transport);
|
|
164
|
+
return {
|
|
165
|
+
url: transport.toString(),
|
|
166
|
+
label: `${host}${AGGREGATOR_MARKER}`,
|
|
167
|
+
kind: 'aggregator-fallback',
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const origins = new Map<string, URL>();
|
|
171
|
+
for (const raw of referenceUrls(doc)) {
|
|
172
|
+
const url = httpUrl(raw);
|
|
173
|
+
if (url === null || url.origin === retrieval.origin) continue;
|
|
174
|
+
// A reference on a known aggregator host is someone else's transport page, not this item's
|
|
175
|
+
// publisher: excluding it keeps an aggregator from being cited as a bare `original`.
|
|
176
|
+
if (isKnownAggregatorHost(hostOf(url))) continue;
|
|
177
|
+
if (!origins.has(url.origin)) origins.set(url.origin, url);
|
|
178
|
+
}
|
|
179
|
+
// Only a transport page is displaced: when the retrieval URL is already the publisher's own page,
|
|
180
|
+
// that page is the verifiable origin and an off-origin reference must not replace it. Exactly one
|
|
181
|
+
// off-origin origin corroborates; two or more prove nothing about which is the item's publisher.
|
|
182
|
+
if (origins.size === 1 && isKnownAggregatorHost(hostOf(retrieval))) {
|
|
183
|
+
const [url] = [...origins.values()] as [URL];
|
|
184
|
+
return { url: url.toString(), label: hostOf(url), kind: 'original' };
|
|
185
|
+
}
|
|
186
|
+
return citeRetrieval(retrieval, classification);
|
|
187
|
+
}
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The versioned per-attempt selection-counts artifact (task 0392 R1/R2).
|
|
3
|
+
*
|
|
4
|
+
* Before 0392 the QC/curation path recorded exclusion evidence only when a rule actually hit
|
|
5
|
+
* (`${run_date}_04_quality-control-content_exclusions.json`), so a day that kept everything and a day
|
|
6
|
+
* whose boundary never ran produced the same files: nothing. The report could therefore only say
|
|
7
|
+
* "QC admitted zero" without saying how the pool shrank, and a retry overwrote the previous
|
|
8
|
+
* attempt's numbers instead of reconciling against them.
|
|
9
|
+
*
|
|
10
|
+
* This module owns the deterministic half: one artifact, `21-plan/topic-selection-attempts.json`,
|
|
11
|
+
* `version`-stamped, holding an append-only list of attempts. Each attempt captures
|
|
12
|
+
* - one record per selection stage that actually ran, `{stage, input, kept, dropped[]}`, so each
|
|
13
|
+
* stage is provable on its own (`input === kept + dropped.length`) instead of being inferred
|
|
14
|
+
* from a single cross-stage sum,
|
|
15
|
+
* - per-rule hit counts (rule hits are NOT unique IDs: one doc can be counted under several rules
|
|
16
|
+
* across attempts, and the UI/report must not add the two numbers together),
|
|
17
|
+
* - the editorial (curation) exclusions with the agent's own reason, kept apart from mechanical
|
|
18
|
+
* rule hits because they answer a different question,
|
|
19
|
+
* - the channel-admission decisions per target, which are an outcome of the run and never change
|
|
20
|
+
* the candidate totals,
|
|
21
|
+
* - which stages have observed evidence, so a stage that never ran stays `unknown` instead of
|
|
22
|
+
* being inferred as zero.
|
|
23
|
+
*
|
|
24
|
+
* A retry appends rather than replaces. The reconciliation block always describes the LATEST
|
|
25
|
+
* attempt (a retry must not inherit a stale reason from the attempt it supersedes) while the earlier
|
|
26
|
+
* attempts stay inspectable, marked `superseded`.
|
|
27
|
+
*
|
|
28
|
+
* Node/Bun builtins plus the sibling boundary engine only — the stage runner imports this file.
|
|
29
|
+
*/
|
|
30
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
31
|
+
import { dirname, join } from 'node:path';
|
|
32
|
+
import type { TopicBoundaryExclusion, TopicBoundarySpec } from './kk-workflow-stages.ts';
|
|
33
|
+
|
|
34
|
+
/** Bump when the attempt/reconciliation shape changes; readers must tolerate older versions. */
|
|
35
|
+
export const SELECTION_ATTEMPTS_VERSION = 2;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Selection stages in pipeline order.
|
|
39
|
+
*
|
|
40
|
+
* `qc` is the raw pool entering the QC filter and its output; `topicBoundary` → `dedup` → `floor`
|
|
41
|
+
* run inside `daily-qc-content`; `curation` → `plan` are the agent's curated split (written by
|
|
42
|
+
* `daily-curate-check`); `channelAdmission` is the content-safety gate's per-target decision.
|
|
43
|
+
*/
|
|
44
|
+
export const SELECTION_STAGES = [
|
|
45
|
+
'qc',
|
|
46
|
+
'topicBoundary',
|
|
47
|
+
'dedup',
|
|
48
|
+
'floor',
|
|
49
|
+
'curation',
|
|
50
|
+
'plan',
|
|
51
|
+
'channelAdmission',
|
|
52
|
+
] as const;
|
|
53
|
+
|
|
54
|
+
export type SelectionStage = (typeof SELECTION_STAGES)[number];
|
|
55
|
+
|
|
56
|
+
/** Stages that move candidates, and so carry `input = kept + dropped`. */
|
|
57
|
+
export const COUNT_STAGES = ['qc', 'topicBoundary', 'dedup', 'floor', 'curation', 'plan'] as const;
|
|
58
|
+
|
|
59
|
+
export type CountStage = (typeof COUNT_STAGES)[number];
|
|
60
|
+
|
|
61
|
+
/** One stage's observed arithmetic. `dropped` holds distinct candidate IDs, never rule hits. */
|
|
62
|
+
export interface SelectionStageCount {
|
|
63
|
+
stage: CountStage;
|
|
64
|
+
/** Candidates entering the stage. */
|
|
65
|
+
input: number;
|
|
66
|
+
/** Candidates the stage kept. */
|
|
67
|
+
kept: number;
|
|
68
|
+
/** Distinct candidate IDs the stage dropped. */
|
|
69
|
+
dropped: string[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Counts the report totals use. Kept for shape compatibility with the v1 artifact; every field is
|
|
74
|
+
* derived from `stages[]` (`null` when the stage that produces it left no evidence).
|
|
75
|
+
*/
|
|
76
|
+
export interface SelectionStageCounts {
|
|
77
|
+
/** Raw pool entering QC (`qc` stage input). */
|
|
78
|
+
preFilter: number | null;
|
|
79
|
+
/** Final kept count — the curated plan when curation ran, else the post-dedup survivors. */
|
|
80
|
+
kept: number | null;
|
|
81
|
+
/** Distinct candidate IDs dropped by a mechanical boundary rule. */
|
|
82
|
+
uniqueExcluded: number | null;
|
|
83
|
+
/** Near-duplicate drops (`null` = the dedup stage left no evidence). */
|
|
84
|
+
deduped: number | null;
|
|
85
|
+
/** Curated plan item count (`null` = curation left no evidence). */
|
|
86
|
+
planned: number | null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `observed` only when a stage wrote evidence for this attempt. */
|
|
90
|
+
export type StageEvidence = Record<SelectionStage, 'observed' | 'unknown'>;
|
|
91
|
+
|
|
92
|
+
export interface SelectionExclusionRecord {
|
|
93
|
+
/** Candidate id. */
|
|
94
|
+
id: string;
|
|
95
|
+
/** Rule that excluded it in this attempt. */
|
|
96
|
+
rule: string;
|
|
97
|
+
/** The keyword/text the rule matched. */
|
|
98
|
+
matched: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** An editorial (curation) exclusion: the agent's own reason, not a mechanical rule id. */
|
|
102
|
+
export interface CurationExclusionRecord {
|
|
103
|
+
id: string;
|
|
104
|
+
reason: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Per-target channel decision. A target outcome, never a candidate count. */
|
|
108
|
+
export interface ChannelAdmissionRecord {
|
|
109
|
+
/** Scope the review ran over (`drafts`, `variants`). */
|
|
110
|
+
scope: string;
|
|
111
|
+
/** Target platform → decision (`OK` | `RISK` | `BLOCK`), plus the gate's own status. */
|
|
112
|
+
targets: { target: string; decision: string }[];
|
|
113
|
+
/** The gate's classification for this scope (`pass` | `revise` | `exclude` | `escalate` | `block`). */
|
|
114
|
+
status: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SelectionAttempt {
|
|
118
|
+
/** 1-based ordinal within the run day; a retry is attempt 2, 3, … */
|
|
119
|
+
attempt: number;
|
|
120
|
+
/** Run id + ordinal, so evidence binds to an attempt even when the work dir is reused. */
|
|
121
|
+
attemptId: string;
|
|
122
|
+
recordedAt: string;
|
|
123
|
+
/** `topic-boundary.json` version in force for this attempt. */
|
|
124
|
+
specVersion: number;
|
|
125
|
+
counts: SelectionStageCounts;
|
|
126
|
+
/** One record per stage that ran, in pipeline order. */
|
|
127
|
+
stages: SelectionStageCount[];
|
|
128
|
+
/** Rule id → number of hits in this attempt (a hit count, not a unique-ID count). */
|
|
129
|
+
perRuleHits: Record<string, number>;
|
|
130
|
+
/** The unique excluded candidate IDs this attempt recorded, with their rule. */
|
|
131
|
+
exclusions: SelectionExclusionRecord[];
|
|
132
|
+
/** Editorial exclusions with the agent's own reason. */
|
|
133
|
+
curationExcluded: CurationExclusionRecord[];
|
|
134
|
+
/** Candidate IDs excluded under more than one distinct rule across the run day's attempts. */
|
|
135
|
+
multipleHitIds: string[];
|
|
136
|
+
/** Kept candidate IDs (the decisions, so a loss is attributable, not just counted). */
|
|
137
|
+
keptIds: string[];
|
|
138
|
+
/** Channel-admission outcomes; `null` until the safety gate recorded a decision. */
|
|
139
|
+
channelAdmission: ChannelAdmissionRecord[];
|
|
140
|
+
stageEvidence: StageEvidence;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface SelectionReconciliation {
|
|
144
|
+
/**
|
|
145
|
+
* Every observed count stage satisfies `input === kept + dropped.length`, and consecutive
|
|
146
|
+
* observed stages chain (`next.input === previous.kept`). A stage with no evidence leaves the
|
|
147
|
+
* reconciliation unproven (reported through `skippedStages`), never violated.
|
|
148
|
+
*/
|
|
149
|
+
reconciled: boolean;
|
|
150
|
+
/** Unique excluded IDs in the latest attempt — count distinct candidates, not rule hits. */
|
|
151
|
+
uniqueIds: number | null;
|
|
152
|
+
/** Sum of the latest attempt's per-rule hits. May exceed `uniqueIds`. */
|
|
153
|
+
ruleHits: number;
|
|
154
|
+
/** Candidate IDs the day excluded under ≥2 distinct rules. */
|
|
155
|
+
multipleHits: number;
|
|
156
|
+
/** A `kept === 0` day is a valid outcome, reported as such (never as a failure). */
|
|
157
|
+
zeroKept: boolean;
|
|
158
|
+
/** Stages with no evidence in the latest attempt — the report prints these as unknown. */
|
|
159
|
+
skippedStages: SelectionStage[];
|
|
160
|
+
/** Attempts whose numbers a later attempt supersedes (kept for history, never inherited). */
|
|
161
|
+
supersededAttempts: number[];
|
|
162
|
+
/** Human-readable contradictions found while reconciling. */
|
|
163
|
+
issues: string[];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface SelectionAttemptsArtifact {
|
|
167
|
+
version: number;
|
|
168
|
+
runDate: string;
|
|
169
|
+
specVersion: number;
|
|
170
|
+
attempts: SelectionAttempt[];
|
|
171
|
+
reconciliation: SelectionReconciliation;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export interface SelectionAttemptInput {
|
|
175
|
+
runDate: string;
|
|
176
|
+
attemptId: string;
|
|
177
|
+
recordedAt?: string;
|
|
178
|
+
spec: Pick<TopicBoundarySpec, 'version'>;
|
|
179
|
+
/** Stage observations this invocation made, in pipeline order. */
|
|
180
|
+
stages: SelectionStageCount[];
|
|
181
|
+
/** Mechanical boundary exclusions (rule-level records). */
|
|
182
|
+
excluded: TopicBoundaryExclusion[];
|
|
183
|
+
/** Candidate IDs kept by the last stage in `stages`. */
|
|
184
|
+
keptIds: string[];
|
|
185
|
+
/** Editorial exclusions, when this invocation produced them (curation). */
|
|
186
|
+
curationExcluded?: CurationExclusionRecord[];
|
|
187
|
+
/** Channel decisions, when this invocation produced them (the safety gate). */
|
|
188
|
+
channelAdmission?: ChannelAdmissionRecord[];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** A later stage's evidence attached to the attempt already on disk. */
|
|
192
|
+
export interface SelectionAttemptPatch {
|
|
193
|
+
/** Stage observations to merge; an existing record for the same stage is replaced. */
|
|
194
|
+
stages?: SelectionStageCount[];
|
|
195
|
+
curationExcluded?: CurationExclusionRecord[];
|
|
196
|
+
channelAdmission?: ChannelAdmissionRecord[];
|
|
197
|
+
/** Overrides the attempt identity — a curation pass after a QC retry belongs to that retry. */
|
|
198
|
+
attemptId?: string;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Rule id → hit count. A hit is an (item, rule) event; the same item can hit one rule per attempt. */
|
|
202
|
+
export function countRuleHits(excluded: TopicBoundaryExclusion[]): Record<string, number> {
|
|
203
|
+
const hits: Record<string, number> = {};
|
|
204
|
+
for (const entry of excluded) hits[entry.rule] = (hits[entry.rule] ?? 0) + 1;
|
|
205
|
+
return hits;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Candidate IDs this run day excluded under more than one DISTINCT rule (retries included). */
|
|
209
|
+
export function multipleHitIds(attempts: SelectionAttempt[]): string[] {
|
|
210
|
+
const rulesById = new Map<string, Set<string>>();
|
|
211
|
+
for (const attempt of attempts) {
|
|
212
|
+
for (const entry of attempt.exclusions) {
|
|
213
|
+
const rules = rulesById.get(entry.id) ?? new Set<string>();
|
|
214
|
+
rules.add(entry.rule);
|
|
215
|
+
rulesById.set(entry.id, rules);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return [...rulesById.entries()].filter(([, rules]) => rules.size > 1).map(([id]) => id);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function stageMap(stages: SelectionStageCount[]): Map<CountStage, SelectionStageCount> {
|
|
222
|
+
return new Map(stages.map((entry) => [entry.stage, entry]));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Sort by pipeline order and drop duplicates, so `stages[]` is always canonical. */
|
|
226
|
+
function orderStages(stages: SelectionStageCount[]): SelectionStageCount[] {
|
|
227
|
+
const byStage = stageMap(stages);
|
|
228
|
+
return COUNT_STAGES.filter((stage) => byStage.has(stage)).map((stage) => byStage.get(stage) as SelectionStageCount);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function evidenceFor(attempt: Pick<SelectionAttempt, 'stages' | 'channelAdmission'>): StageEvidence {
|
|
232
|
+
const evidence = {} as StageEvidence;
|
|
233
|
+
const observed = new Set<string>(attempt.stages.map((entry) => entry.stage));
|
|
234
|
+
if (attempt.channelAdmission.length > 0) observed.add('channelAdmission');
|
|
235
|
+
for (const stage of SELECTION_STAGES) evidence[stage] = observed.has(stage) ? 'observed' : 'unknown';
|
|
236
|
+
return evidence;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Project `stages[]` onto the report totals. `kept` is the LAST count stage's kept value (the
|
|
241
|
+
* curated plan once curation ran), so the headline number never regresses to a pre-curation count.
|
|
242
|
+
*/
|
|
243
|
+
function countsFor(stages: SelectionStageCount[], uniqueExcluded: number): SelectionStageCounts {
|
|
244
|
+
const byStage = stageMap(stages);
|
|
245
|
+
const last = stages[stages.length - 1];
|
|
246
|
+
const dedup = byStage.get('dedup');
|
|
247
|
+
const plan = byStage.get('plan');
|
|
248
|
+
return {
|
|
249
|
+
preFilter: byStage.get('qc')?.input ?? null,
|
|
250
|
+
kept: last === undefined ? null : last.kept,
|
|
251
|
+
uniqueExcluded,
|
|
252
|
+
deduped: dedup === undefined ? null : dedup.dropped.length,
|
|
253
|
+
planned: plan === undefined ? null : plan.kept,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Turn one stage invocation into an attempt record. Pure: no IO, no clock unless asked to stamp one. */
|
|
258
|
+
export function buildSelectionAttempt(input: SelectionAttemptInput, attempt = 1): SelectionAttempt {
|
|
259
|
+
const stages = orderStages(input.stages);
|
|
260
|
+
return {
|
|
261
|
+
attempt,
|
|
262
|
+
attemptId: input.attemptId,
|
|
263
|
+
recordedAt: input.recordedAt ?? new Date().toISOString(),
|
|
264
|
+
specVersion: input.spec.version,
|
|
265
|
+
counts: countsFor(stages, input.excluded.length),
|
|
266
|
+
stages,
|
|
267
|
+
perRuleHits: countRuleHits(input.excluded),
|
|
268
|
+
exclusions: input.excluded.map((entry) => ({ id: entry.id, rule: entry.rule, matched: entry.matched })),
|
|
269
|
+
curationExcluded: input.curationExcluded ?? [],
|
|
270
|
+
multipleHitIds: [],
|
|
271
|
+
keptIds: [...input.keptIds],
|
|
272
|
+
channelAdmission: input.channelAdmission ?? [],
|
|
273
|
+
stageEvidence: evidenceFor({ stages, channelAdmission: input.channelAdmission ?? [] }),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Reconcile one run day's attempts. The latest attempt owns every number; earlier attempts are
|
|
279
|
+
* history only (a retry must never inherit a stale reason), and its missing stages stay unknown.
|
|
280
|
+
*/
|
|
281
|
+
export function reconcileSelectionAttempts(attempts: SelectionAttempt[]): SelectionReconciliation {
|
|
282
|
+
const latest = attempts[attempts.length - 1];
|
|
283
|
+
const issues: string[] = [];
|
|
284
|
+
if (latest === undefined) {
|
|
285
|
+
return {
|
|
286
|
+
reconciled: false,
|
|
287
|
+
uniqueIds: null,
|
|
288
|
+
ruleHits: 0,
|
|
289
|
+
multipleHits: 0,
|
|
290
|
+
zeroKept: false,
|
|
291
|
+
skippedStages: [...SELECTION_STAGES],
|
|
292
|
+
supersededAttempts: [],
|
|
293
|
+
issues: ['no selection attempt was recorded for this run day'],
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
// Per-stage arithmetic first: a stage that reports more or fewer drops than it actually moved
|
|
297
|
+
// candidates is the failure mode this artifact exists to catch.
|
|
298
|
+
for (const entry of latest.stages) {
|
|
299
|
+
const sum = entry.kept + entry.dropped.length;
|
|
300
|
+
if (entry.input !== sum) {
|
|
301
|
+
issues.push(`${entry.stage}: input ${entry.input} ≠ kept ${entry.kept} + dropped ${entry.dropped.length}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Then the chain: a stage that starts from a count the previous stage did not hand over means
|
|
305
|
+
// the numbers were recorded across different inputs (a retry mid-pipeline, or a stale artifact).
|
|
306
|
+
for (let index = 1; index < latest.stages.length; index += 1) {
|
|
307
|
+
const previous = latest.stages[index - 1] as SelectionStageCount;
|
|
308
|
+
const current = latest.stages[index] as SelectionStageCount;
|
|
309
|
+
if (current.input !== previous.kept) {
|
|
310
|
+
issues.push(
|
|
311
|
+
`${previous.stage} → ${current.stage}: previous kept ${previous.kept} ≠ next input ${current.input}`,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const kept = latest.counts.kept;
|
|
316
|
+
const ruleHits = Object.values(latest.perRuleHits).reduce((total, hits) => total + hits, 0);
|
|
317
|
+
return {
|
|
318
|
+
reconciled: issues.length === 0 && latest.stages.length > 0,
|
|
319
|
+
uniqueIds: latest.counts.uniqueExcluded,
|
|
320
|
+
ruleHits,
|
|
321
|
+
multipleHits: multipleHitIds(attempts).length,
|
|
322
|
+
zeroKept: kept === 0,
|
|
323
|
+
skippedStages: SELECTION_STAGES.filter((stage) => latest.stageEvidence[stage] === 'unknown'),
|
|
324
|
+
supersededAttempts: attempts.slice(0, -1).map((attempt) => attempt.attempt),
|
|
325
|
+
issues,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function artifactFor(input: {
|
|
330
|
+
runDate: string;
|
|
331
|
+
specVersion: number;
|
|
332
|
+
attempts: SelectionAttempt[];
|
|
333
|
+
}): SelectionAttemptsArtifact {
|
|
334
|
+
const attempts = [...input.attempts];
|
|
335
|
+
const latest = attempts[attempts.length - 1] as SelectionAttempt;
|
|
336
|
+
attempts[attempts.length - 1] = { ...latest, multipleHitIds: multipleHitIds(attempts) };
|
|
337
|
+
return {
|
|
338
|
+
version: SELECTION_ATTEMPTS_VERSION,
|
|
339
|
+
runDate: input.runDate,
|
|
340
|
+
specVersion: input.specVersion,
|
|
341
|
+
attempts,
|
|
342
|
+
reconciliation: reconcileSelectionAttempts(attempts),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Append an attempt to the run day's artifact (a retry appends; nothing is overwritten). */
|
|
347
|
+
export function appendSelectionAttempt(
|
|
348
|
+
previous: SelectionArtifact | null,
|
|
349
|
+
input: SelectionAttemptInput,
|
|
350
|
+
): SelectionArtifact {
|
|
351
|
+
const history = previous !== null && previous.runDate === input.runDate ? previous.attempts : [];
|
|
352
|
+
const attempt = buildSelectionAttempt(input, history.length + 1);
|
|
353
|
+
return artifactFor({
|
|
354
|
+
runDate: input.runDate,
|
|
355
|
+
specVersion: attempt.specVersion,
|
|
356
|
+
attempts: [...history, attempt],
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Attach a later stage's evidence to the attempt already recorded for the run day.
|
|
362
|
+
*
|
|
363
|
+
* The pipeline is staged: QC writes the attempt, curation and the safety gate only run afterwards.
|
|
364
|
+
* Amending keeps ONE attempt per invocation (a retry is a new attempt), which is why the identity
|
|
365
|
+
* comes from the attempt already on disk rather than from a fresh `attemptId`. Returns `null` when
|
|
366
|
+
* there is no attempt to amend — the caller then leaves the stage unknown instead of inventing one.
|
|
367
|
+
*/
|
|
368
|
+
export function amendSelectionAttempt(
|
|
369
|
+
previous: SelectionArtifact | null,
|
|
370
|
+
runDate: string,
|
|
371
|
+
patch: SelectionAttemptPatch,
|
|
372
|
+
): SelectionArtifact | null {
|
|
373
|
+
if (previous === null || previous.runDate !== runDate) return null;
|
|
374
|
+
const attempts = [...previous.attempts];
|
|
375
|
+
const latest = attempts[attempts.length - 1];
|
|
376
|
+
if (latest === undefined) return null;
|
|
377
|
+
const merged: SelectionAttempt = {
|
|
378
|
+
...latest,
|
|
379
|
+
attemptId: patch.attemptId ?? latest.attemptId,
|
|
380
|
+
stages: orderStages([...latest.stages, ...(patch.stages ?? [])]),
|
|
381
|
+
curationExcluded: [...latest.curationExcluded, ...(patch.curationExcluded ?? [])],
|
|
382
|
+
channelAdmission: mergeChannelAdmission(latest.channelAdmission, patch.channelAdmission ?? []),
|
|
383
|
+
};
|
|
384
|
+
// The boundary exclusion records live on the attempt; re-project from them so a curation
|
|
385
|
+
// amendment cannot discard the rule counts the QC stage recorded.
|
|
386
|
+
merged.counts = countsFor(merged.stages, merged.exclusions.length);
|
|
387
|
+
merged.stageEvidence = evidenceFor(merged);
|
|
388
|
+
attempts[attempts.length - 1] = merged;
|
|
389
|
+
return artifactFor({ runDate: previous.runDate, specVersion: merged.specVersion, attempts });
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** A re-run of the same scope replaces that scope's decisions; a new scope appends. */
|
|
393
|
+
function mergeChannelAdmission(
|
|
394
|
+
existing: ChannelAdmissionRecord[],
|
|
395
|
+
incoming: ChannelAdmissionRecord[],
|
|
396
|
+
): ChannelAdmissionRecord[] {
|
|
397
|
+
const merged = [...existing];
|
|
398
|
+
for (const entry of incoming) {
|
|
399
|
+
const index = merged.findIndex((current) => current.scope === entry.scope);
|
|
400
|
+
if (index === -1) merged.push(entry);
|
|
401
|
+
else merged[index] = entry;
|
|
402
|
+
}
|
|
403
|
+
return merged;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** `21-plan/topic-selection-attempts.json` — one artifact per run day, shared by both report paths. */
|
|
407
|
+
export function selectionAttemptsPath(workDir: string): string {
|
|
408
|
+
return join(workDir, '21-plan', 'topic-selection-attempts.json');
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Tolerant read: an absent, unparsable or older artifact is `null`, never a thrown stage. */
|
|
412
|
+
export function readSelectionAttempts(workDir: string): SelectionArtifact | null {
|
|
413
|
+
try {
|
|
414
|
+
const parsed = JSON.parse(readFileSync(selectionAttemptsPath(workDir), 'utf-8')) as unknown;
|
|
415
|
+
if (parsed === null || typeof parsed !== 'object') return null;
|
|
416
|
+
const artifact = parsed as SelectionArtifact;
|
|
417
|
+
return Array.isArray(artifact.attempts) ? artifact : null;
|
|
418
|
+
} catch {
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function persist(workDir: string, artifact: SelectionAttemptsArtifact): SelectionAttemptsArtifact {
|
|
424
|
+
const path = selectionAttemptsPath(workDir);
|
|
425
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
426
|
+
writeFileSync(path, `${JSON.stringify(artifact, null, 2)}\n`);
|
|
427
|
+
return artifact;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Record one selection attempt for the run day. Returns the artifact it wrote; an unwritable work
|
|
432
|
+
* dir throws (the caller stages it through `sted`, so the write is visible in step timing).
|
|
433
|
+
*/
|
|
434
|
+
export function recordSelectionAttempt(workDir: string, input: SelectionAttemptInput): SelectionArtifact {
|
|
435
|
+
return persist(workDir, appendSelectionAttempt(readSelectionAttempts(workDir), input));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Record a later stage's evidence onto the run day's current attempt; `null` when there is none. */
|
|
439
|
+
export function recordSelectionStage(
|
|
440
|
+
workDir: string,
|
|
441
|
+
runDate: string,
|
|
442
|
+
patch: SelectionAttemptPatch,
|
|
443
|
+
): SelectionArtifact | null {
|
|
444
|
+
const amended = amendSelectionAttempt(readSelectionAttempts(workDir), runDate, patch);
|
|
445
|
+
return amended === null ? null : persist(workDir, amended);
|
|
446
|
+
}
|