@skillre/dsh-plugin-work-dashboard 0.9.0 → 0.10.1

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/lib/form.d.ts CHANGED
@@ -40,11 +40,26 @@ import type { PocRecord } from './types.js';
40
40
  export declare const G0_FIELDS: readonly ["why_customer", "why_us", "decision_chain", "post_poc_decision"];
41
41
  /** One plan criterion, as the form edits it. */
42
42
  export interface FormCriterion {
43
+ /** `cri-NN`; carried through so a returned form never renumbers the plan. */
44
+ id: string;
43
45
  name: string;
44
46
  metric: string;
45
47
  baseline: string;
46
48
  target: string;
47
49
  }
50
+ /**
51
+ * One plan scenario.
52
+ *
53
+ * v3.1 made this an object with a stable id, because evidence attaches by id:
54
+ * a form that renumbered scenarios would silently orphan every proof it had.
55
+ * `id` is therefore carried through untouched and is not user-editable.
56
+ */
57
+ export interface FormScenario {
58
+ /** `scn-NN`; stable for the life of the project. */
59
+ id: string;
60
+ name: string;
61
+ goal: string;
62
+ }
48
63
  /** One plan risk. */
49
64
  export interface FormRisk {
50
65
  name: string;
@@ -56,8 +71,13 @@ export interface FormProgress {
56
71
  seq: number | null;
57
72
  date: string;
58
73
  type: string;
74
+ /** v3.1: what moved compared to the previous round. Required. */
75
+ change: string;
59
76
  goal: string;
60
- items: string[];
77
+ /** `scn-NN` ids picked from the plan's scenarios. */
78
+ scenarioIds: string[];
79
+ /** `cri-NN` ids picked from the plan's criteria; independent of scenarios. */
80
+ criteriaIds: string[];
61
81
  actual: string;
62
82
  completion: string;
63
83
  evidence: Array<{
@@ -115,7 +135,7 @@ export interface FormProject {
115
135
  expected_recognition: string;
116
136
  our_edge: string;
117
137
  criteria: FormCriterion[];
118
- scenarios: string[];
138
+ scenarios: FormScenario[];
119
139
  risks: FormRisk[];
120
140
  timeline_start: string;
121
141
  timeline_end: string;
@@ -177,6 +197,7 @@ declare const ENUMS: {
177
197
  g2Ready: string[];
178
198
  recognition: string[];
179
199
  progressType: string[];
200
+ progressChange: string[];
180
201
  completion: string[];
181
202
  riskLevel: string[];
182
203
  gate3_1: string[];
@@ -184,9 +205,22 @@ declare const ENUMS: {
184
205
  evidenceType: string[];
185
206
  system: string[];
186
207
  };
208
+ /**
209
+ * The schema generation this form emits.
210
+ *
211
+ * Stamped into every generated page so a returned form can be checked against
212
+ * the schema that will read it. A v3.0 form uses `items` and string scenarios;
213
+ * importing it as v3.1 would silently drop every scenario and criterion
214
+ * reference, which is exactly the failure this constant exists to catch.
215
+ */
216
+ export declare const FORM_SCHEMA_VERSION = "3.1";
217
+ /** The schema generation a v3.0 form emitted; recognised only to reject it. */
218
+ export declare const LEGACY_FORM_SCHEMA_VERSION = "3.0";
187
219
  /** The state the generated page boots from. */
188
220
  export interface FormPayload {
189
221
  mode: 'fill' | 'blank';
222
+ /** The schema this page writes. Absent means a pre-v3.1 form. */
223
+ schemaVersion: string;
190
224
  generatedAt: string;
191
225
  today: string;
192
226
  projects: FormProject[];
@@ -216,3 +250,29 @@ export declare function formFileName(options: {
216
250
  export declare function yamlFileName(project: FormProject, now?: Date): string;
217
251
  /** Re-export the YAML library's parse for the round-trip test. */
218
252
  export { YAML };
253
+ /**
254
+ * Whether a returned form was generated by this schema generation.
255
+ *
256
+ * `poc-export` produces a standalone HTML file that colleagues fill in offline,
257
+ * so **old copies keep circulating** long after the schema moves. The v3.0 form
258
+ * carries `progress[].items` and a string array of scenarios; reading it as v3.1
259
+ * would drop every scenario and criterion reference without an error, and the
260
+ * ledger's whole proof chain hangs off those ids.
261
+ *
262
+ * So this is a hard gate rather than a tolerant reader: a stale form is refused
263
+ * with an explanation, not silently half-imported.
264
+ */
265
+ export interface FormCompatibility {
266
+ compatible: boolean;
267
+ /** The schema the file declares, or empty when it predates the stamp. */
268
+ declared: string;
269
+ /** A message safe to show the person who just filled the form in. */
270
+ reason: string;
271
+ }
272
+ /**
273
+ * Check a parsed form payload against {@link FORM_SCHEMA_VERSION}.
274
+ *
275
+ * Accepts the raw parsed object rather than a typed payload, because the whole
276
+ * point is to inspect a document whose shape may be from an older generation.
277
+ */
278
+ export declare function checkFormCompatibility(payload: unknown): FormCompatibility;
package/lib/form.js CHANGED
@@ -98,13 +98,23 @@ export function projectForForm(record) {
98
98
  customer_pain: text(plan.customer_pain),
99
99
  expected_recognition: text(plan.expected_recognition),
100
100
  our_edge: text(plan.our_edge),
101
- criteria: (Array.isArray(plan.criteria) ? plan.criteria : []).map((item) => ({
101
+ criteria: (Array.isArray(plan.criteria) ? plan.criteria : []).map((item, index) => ({
102
+ // A criterion without an id in the ledger is given one on the way out so
103
+ // the form can reference it; the Host is what writes it back.
104
+ id: text(item?.id) === '' ? `cri-${String(index + 1).padStart(2, '0')}` : text(item?.id),
102
105
  name: text(item?.name),
103
106
  metric: text(item?.metric),
104
107
  baseline: text(item?.baseline),
105
108
  target: text(item?.target),
106
109
  })),
107
- scenarios: (Array.isArray(plan.scenarios) ? plan.scenarios : []).map(text).filter((item) => item !== ''),
110
+ // v3.1: objects with a stable id, not bare strings.
111
+ scenarios: (Array.isArray(plan.scenarios) ? plan.scenarios : [])
112
+ .filter((item) => item !== null && item !== undefined)
113
+ .map((item, index) => ({
114
+ id: text(item?.id) === '' ? `scn-${String(index + 1).padStart(2, '0')}` : text(item?.id),
115
+ name: text(item?.name),
116
+ goal: text(item?.goal),
117
+ })),
108
118
  risks: (Array.isArray(plan.risks) ? plan.risks : []).map((item) => ({
109
119
  name: text(item?.name),
110
120
  level: text(item?.level).toLowerCase(),
@@ -132,8 +142,10 @@ export function blankProgress(existingCount) {
132
142
  seq: existingCount + 1,
133
143
  date: '',
134
144
  type: '',
145
+ change: '',
135
146
  goal: '',
136
- items: [''],
147
+ scenarioIds: [],
148
+ criteriaIds: [],
137
149
  actual: '',
138
150
  completion: '',
139
151
  evidence: [],
@@ -249,12 +261,20 @@ export function projectToYaml(project) {
249
261
  criteria: project.plan.criteria
250
262
  .filter((criterion) => criterion.name.trim() !== '')
251
263
  .map((criterion) => ({
264
+ // Never renumber: a returned criterion keeps the id evidence cites.
265
+ id: criterion.id.trim() === '' ? null : criterion.id.trim(),
252
266
  name: criterion.name.trim(),
253
267
  metric: criterion.metric.trim() === '' ? null : criterion.metric.trim(),
254
268
  baseline: criterion.baseline.trim() === '' ? null : criterion.baseline.trim(),
255
269
  target: criterion.target.trim() === '' ? null : criterion.target.trim(),
256
270
  })),
257
- scenarios: compact(project.plan.scenarios),
271
+ scenarios: project.plan.scenarios
272
+ .filter((scenario) => scenario.name.trim() !== '')
273
+ .map((scenario) => ({
274
+ id: scenario.id.trim() === '' ? null : scenario.id.trim(),
275
+ name: scenario.name.trim(),
276
+ goal: scenario.goal.trim() === '' ? null : scenario.goal.trim(),
277
+ })),
258
278
  our_edge: project.plan.our_edge === '' ? null : project.plan.our_edge,
259
279
  timeline: {
260
280
  start: project.plan.timeline_start === '' ? null : project.plan.timeline_start,
@@ -290,7 +310,8 @@ function progressIsEmpty(entry) {
290
310
  entry.type === '' &&
291
311
  entry.goal === '' &&
292
312
  entry.actual === '' &&
293
- compact(entry.items).length === 0 &&
313
+ compact(entry.scenarioIds).length === 0 &&
314
+ compact(entry.criteriaIds).length === 0 &&
294
315
  entry.evidence.every((item) => item.title.trim() === ''));
295
316
  }
296
317
  /** One progress entry in the ledger's own shape. */
@@ -299,8 +320,12 @@ function serializeProgress(entry) {
299
320
  seq: entry.seq,
300
321
  date: entry.date,
301
322
  type: entry.type === '' ? null : entry.type,
323
+ // `change` is mandatory in v3.1: a round that does not say what moved is the
324
+ // single most common way a timeline decays into "communicated with customer".
325
+ change: entry.change === '' ? null : entry.change,
302
326
  goal: entry.goal === '' ? null : entry.goal,
303
- items: compact(entry.items),
327
+ scenario_ids: compact(entry.scenarioIds),
328
+ criteria_ids: compact(entry.criteriaIds),
304
329
  actual: entry.actual === '' ? null : entry.actual,
305
330
  completion: entry.completion === '' ? null : entry.completion,
306
331
  evidence: entry.evidence
@@ -344,12 +369,15 @@ function escapeHtml(value) {
344
369
  const ENUMS = {
345
370
  pocType: ['SDL', 'ACG', 'AI安全', '保护AI', '虚拟化', '大体量项目'],
346
371
  stage: ['G0-立项', 'G1-方案设计', 'G2-方案验证', 'G3-结果验证', 'G4-结果转化', 'closed'],
347
- status: ['进行中', '暂停', '已关闭', '已取消'],
372
+ status: ['未开始', '进行中', '暂停', '已关闭', '已取消'],
348
373
  g0Conclusion: ['通过', '未通过-退出', '未通过-降级', '待评审'],
349
374
  g1Conclusion: ['通过', '补充后进入', '未通过'],
350
375
  g2Ready: ['Ready', '有风险', '未Ready'],
351
376
  recognition: ['认可', '部分认可', '未认可', '待确认'],
352
377
  progressType: ['内部Review', '客户阶段同步', 'Checkpoint'],
378
+ // v3.1: mandatory on every progress entry. "无实质进展" is an allowed value:
379
+ // saying "nothing moved" beats writing a sentence that hides it.
380
+ progressChange: ['阶段推进', '场景新增', '目标调整', '证据补充', '风险出现', '风险解除', '无实质进展'],
353
381
  completion: ['0%', '25%', '50%', '75%', '100%'],
354
382
  riskLevel: ['high', 'medium', 'low'],
355
383
  gate3_1: ['可证明', '待补证据'],
@@ -357,6 +385,17 @@ const ENUMS = {
357
385
  evidenceType: ['文档', '截图', '数据', '邮件', '链接'],
358
386
  system: ['人保体系', '国寿体系'],
359
387
  };
388
+ /**
389
+ * The schema generation this form emits.
390
+ *
391
+ * Stamped into every generated page so a returned form can be checked against
392
+ * the schema that will read it. A v3.0 form uses `items` and string scenarios;
393
+ * importing it as v3.1 would silently drop every scenario and criterion
394
+ * reference, which is exactly the failure this constant exists to catch.
395
+ */
396
+ export const FORM_SCHEMA_VERSION = '3.1';
397
+ /** The schema generation a v3.0 form emitted; recognised only to reject it. */
398
+ export const LEGACY_FORM_SCHEMA_VERSION = '3.0';
360
399
  /** The G0 prompts: the label and the reason each field exists. */
361
400
  const G0_PROMPTS = [
362
401
  { key: 'why_customer', label: '客户为什么要测', hint: '客户自己的痛点与压力,不是我们的卖点。' },
@@ -375,6 +414,7 @@ export function buildFormHtml(options) {
375
414
  const projects = options.mode === 'blank' ? [blankProject()] : options.projects;
376
415
  const payload = {
377
416
  mode: options.mode,
417
+ schemaVersion: FORM_SCHEMA_VERSION,
378
418
  generatedAt: now.toISOString(),
379
419
  today: now.toISOString().slice(0, 10),
380
420
  projects,
@@ -446,6 +486,40 @@ export function yamlFileName(project, now = new Date()) {
446
486
  }
447
487
  /** Re-export the YAML library's parse for the round-trip test. */
448
488
  export { YAML };
489
+ /**
490
+ * Check a parsed form payload against {@link FORM_SCHEMA_VERSION}.
491
+ *
492
+ * Accepts the raw parsed object rather than a typed payload, because the whole
493
+ * point is to inspect a document whose shape may be from an older generation.
494
+ */
495
+ export function checkFormCompatibility(payload) {
496
+ if (typeof payload !== 'object' || payload === null) {
497
+ return {
498
+ compatible: false,
499
+ declared: '',
500
+ reason: '这个文件不是本表单导出的格式,无法导入。',
501
+ };
502
+ }
503
+ const record = payload;
504
+ const declared = typeof record.schemaVersion === 'string' ? record.schemaVersion.trim() : '';
505
+ if (declared === FORM_SCHEMA_VERSION) {
506
+ return { compatible: true, declared, reason: '' };
507
+ }
508
+ if (declared === LEGACY_FORM_SCHEMA_VERSION || declared === '') {
509
+ return {
510
+ compatible: false,
511
+ declared: declared === '' ? LEGACY_FORM_SCHEMA_VERSION : declared,
512
+ reason: `这个表单是 v${LEGACY_FORM_SCHEMA_VERSION} 版本导出的,当前台账已升级到 v${FORM_SCHEMA_VERSION}。` +
513
+ '场景与指标改为按 id 关联,旧表单里的场景名无法对应,直接导入会丢失全部场景与指标引用。' +
514
+ '请重新导出一份 v' + FORM_SCHEMA_VERSION + ' 表单再填。',
515
+ };
516
+ }
517
+ return {
518
+ compatible: false,
519
+ declared,
520
+ reason: `这个表单声明的版本是 v${declared},当前台账读取的是 v${FORM_SCHEMA_VERSION},无法确认字段含义一致,已拒绝导入。`,
521
+ };
522
+ }
449
523
  /** Styles: one inline sheet, the console's own design tokens. */
450
524
  const FORM_CSS = `
451
525
  :root{--primary:#2864E8;--text:#192638;--bg:#F5F7FB;--border:#E6EBF2;--green:#218568;--amber:#B77919;--red:#C0392B;--muted:#6B7C93}
@@ -959,10 +1033,14 @@ const FORM_SCRIPT = `
959
1033
  lines.push(' - seq: ' + (entry.seq === null ? 'null' : entry.seq));
960
1034
  lines.push(' date: ' + scalar(entry.date));
961
1035
  lines.push(' type: ' + scalar(entry.type));
1036
+ lines.push(' change: ' + scalar(entry.change));
962
1037
  lines.push(' goal: ' + scalar(entry.goal));
963
- var items = entry.items.filter(function (item) { return text(item).trim() !== ''; });
964
- lines.push(' items:' + (items.length === 0 ? ' []' : ''));
965
- for (i = 0; i < items.length; i += 1) lines.push(' - ' + scalar(items[i]));
1038
+ var scnIds = entry.scenarioIds.filter(function (item) { return text(item).trim() !== ''; });
1039
+ lines.push(' scenario_ids:' + (scnIds.length === 0 ? ' []' : ''));
1040
+ for (i = 0; i < scnIds.length; i += 1) lines.push(' - ' + scalar(scnIds[i]));
1041
+ var criIds = entry.criteriaIds.filter(function (item) { return text(item).trim() !== ''; });
1042
+ lines.push(' criteria_ids:' + (criIds.length === 0 ? ' []' : ''));
1043
+ for (i = 0; i < criIds.length; i += 1) lines.push(' - ' + scalar(criIds[i]));
966
1044
  lines.push(' actual: ' + scalar(entry.actual));
967
1045
  lines.push(' completion: ' + scalar(entry.completion));
968
1046
  var evidence = entry.evidence.filter(function (item) { return text(item.title).trim() !== ''; });
package/lib/gap.d.ts CHANGED
@@ -1,18 +1,28 @@
1
1
  /**
2
- * The twelve v3 gap rules, as pure functions.
2
+ * The sixteen v3.1 gap rules, as pure functions.
3
3
  *
4
- * The rules are hard-coded here on purpose: they are the product's judgement,
5
- * not repository data, so they must not drift with a script the data source
6
- * happens to ship. Every rule is a total function of `(record, options)` —
7
- * no clock, no filesystem, no locale — so `tests/gap.spec.ts` can pin each one
8
- * to a fixture.
4
+ * Every rule is a total function of `(record, options)` — no clock, no
5
+ * filesystem, no locale — so `tests/gap.spec.ts` can pin each one to a fixture.
6
+ *
7
+ * Thresholds are NOT hard-coded here. They arrive through
8
+ * {@link ScanOptions.rules}, parsed from the ledger's `config/rules.yaml`, because
9
+ * the ledger treats that file as the single source ("three copied rule lists
10
+ * drift; one does not"). A caller that omits `rules` gets the built-in fallback,
11
+ * which is the same set of numbers but is labelled as a fallback in the UI.
9
12
  *
10
13
  * The v3 model is **progress-centred**: a project is judged by its latest
11
14
  * progress entry, not by a separately-maintained `result` block. Rules 8–10
12
- * therefore read `progress[progress.length - 1]`, and rule 7 compares "has any
13
- * progress" against the G2 readiness flag.
15
+ * therefore read the newest entry, and rule 7 compares "has any progress"
16
+ * against the G2 readiness flag.
17
+ *
18
+ * Rules 13–16 are the v3.1 additions and read the ledger's **derived**
19
+ * per-scenario and per-criterion state (`scenarios[].status`,
20
+ * `criteria[].status`) rather than re-deriving it: the ledger's `derive.mjs` is
21
+ * the only writer of those fields, and a second implementation here would
22
+ * eventually disagree with CI.
14
23
  */
15
24
  import type { GapItem, GapLevel, PocRecord, StageId } from './types.js';
25
+ import { type RulesBundle } from './rules.js';
16
26
  /** Normalize the free-form `stage` string onto a stage id. */
17
27
  export declare function normalizeStage(raw: unknown): {
18
28
  stage: StageId | null;
@@ -30,6 +40,14 @@ export interface ScanOptions {
30
40
  now: Date;
31
41
  /** Days in one stage after which rule 12 fires. */
32
42
  stallDays: number;
43
+ /**
44
+ * The thresholds and rule metadata in force.
45
+ *
46
+ * Omitted means "use the built-in fallback": the scan still runs, but the
47
+ * caller should surface that its findings came from fallback numbers, not from
48
+ * the ledger's `config/rules.yaml`.
49
+ */
50
+ rules?: RulesBundle;
33
51
  }
34
52
  /** Rule metadata: number, severity and sort weight. */
35
53
  export declare const RULE_META: Record<GapItem['rule'], {
package/lib/gap.js CHANGED
@@ -1,17 +1,27 @@
1
1
  /**
2
- * The twelve v3 gap rules, as pure functions.
2
+ * The sixteen v3.1 gap rules, as pure functions.
3
3
  *
4
- * The rules are hard-coded here on purpose: they are the product's judgement,
5
- * not repository data, so they must not drift with a script the data source
6
- * happens to ship. Every rule is a total function of `(record, options)` —
7
- * no clock, no filesystem, no locale — so `tests/gap.spec.ts` can pin each one
8
- * to a fixture.
4
+ * Every rule is a total function of `(record, options)` — no clock, no
5
+ * filesystem, no locale — so `tests/gap.spec.ts` can pin each one to a fixture.
6
+ *
7
+ * Thresholds are NOT hard-coded here. They arrive through
8
+ * {@link ScanOptions.rules}, parsed from the ledger's `config/rules.yaml`, because
9
+ * the ledger treats that file as the single source ("three copied rule lists
10
+ * drift; one does not"). A caller that omits `rules` gets the built-in fallback,
11
+ * which is the same set of numbers but is labelled as a fallback in the UI.
9
12
  *
10
13
  * The v3 model is **progress-centred**: a project is judged by its latest
11
14
  * progress entry, not by a separately-maintained `result` block. Rules 8–10
12
- * therefore read `progress[progress.length - 1]`, and rule 7 compares "has any
13
- * progress" against the G2 readiness flag.
15
+ * therefore read the newest entry, and rule 7 compares "has any progress"
16
+ * against the G2 readiness flag.
17
+ *
18
+ * Rules 13–16 are the v3.1 additions and read the ledger's **derived**
19
+ * per-scenario and per-criterion state (`scenarios[].status`,
20
+ * `criteria[].status`) rather than re-deriving it: the ledger's `derive.mjs` is
21
+ * the only writer of those fields, and a second implementation here would
22
+ * eventually disagree with CI.
14
23
  */
24
+ import { FALLBACK_RULE_META, fallbackRules } from './rules.js';
15
25
  /** Stage prefixes a raw `stage` value can normalize to, in order. */
16
26
  const STAGE_PREFIXES = [
17
27
  ['G0', 'G0'],
@@ -82,7 +92,18 @@ export const RULE_META = {
82
92
  'R11-no-next-milestone': { no: 11, level: 'high', priority: 96 },
83
93
  // R12: the project has not moved.
84
94
  'R12-stage-stalled': { no: 12, level: 'medium', priority: 40 },
95
+ // R13–R16: the plan is the right shape but the work has not moved. A scenario
96
+ // with no evidence behind it is the state-level twin of R8, per item instead
97
+ // of per entry.
98
+ 'R13-scenario-no-evidence': { no: 13, level: 'high', priority: 88 },
99
+ 'R14-scenario-awaiting-customer': { no: 14, level: 'info', priority: 30 },
100
+ 'R15-criteria-unverified': { no: 15, level: 'medium', priority: 44 },
101
+ 'R16-scenario-not-started': { no: 16, level: 'medium', priority: 42 },
85
102
  };
103
+ /** The thresholds in force, from the ledger bundle or the built-in fallback. */
104
+ function thresholdsOf(options) {
105
+ return (options.rules ?? fallbackRules()).thresholds;
106
+ }
86
107
  /** Build one finding, stamping the rule metadata from {@link RULE_META}. */
87
108
  function gap(poc, rule, extra = {}) {
88
109
  const meta = RULE_META[rule];
@@ -151,6 +172,7 @@ export function daysSince(date, now) {
151
172
  */
152
173
  export function scanGaps(poc, options) {
153
174
  const gaps = [];
175
+ const thresholds = thresholdsOf(options);
154
176
  const gate0 = poc.gate0 ?? {};
155
177
  const plan = poc.plan ?? {};
156
178
  const outcome = poc.outcome ?? {};
@@ -165,7 +187,7 @@ export function scanGaps(poc, options) {
165
187
  }
166
188
  // R2 — a large commitment whose G0 was never cleared.
167
189
  const conclusion = text(gate0.review?.conclusion);
168
- if (amountWan >= 300 && conclusion !== '通过') {
190
+ if (amountWan >= thresholds.largeAmountWan && conclusion !== '通过') {
169
191
  gaps.push(gap(poc, 'R2-large-amount-no-g0', { field: 'gate0.review.conclusion', params: { amountWan, conclusion: conclusion === '' ? '未评审' : conclusion } }));
170
192
  }
171
193
  // R3 — cleared the gate but never defined success.
@@ -175,16 +197,16 @@ export function scanGaps(poc, options) {
175
197
  // R4–R6 — focus limits. Only fires when the list is non-empty, so a project
176
198
  // that has not planned yet is not punished twice (R3 covers that case).
177
199
  const criteria = (plan.criteria ?? []).length;
178
- if (criteria > 0 && (criteria < 2 || criteria > 3)) {
179
- gaps.push(gap(poc, 'R4-criteria-count', { field: 'plan.criteria', params: { count: criteria, min: 2, max: 3 } }));
200
+ if (criteria > 0 && (criteria < thresholds.criteria.min || criteria > thresholds.criteria.max)) {
201
+ gaps.push(gap(poc, 'R4-criteria-count', { field: 'plan.criteria', params: { count: criteria, min: thresholds.criteria.min, max: thresholds.criteria.max } }));
180
202
  }
181
203
  const scenarios = (plan.scenarios ?? []).length;
182
- if (scenarios > 0 && (scenarios < 3 || scenarios > 5)) {
183
- gaps.push(gap(poc, 'R5-scenarios-count', { field: 'plan.scenarios', params: { count: scenarios, min: 3, max: 5 } }));
204
+ if (scenarios > 0 && (scenarios < thresholds.scenarios.min || scenarios > thresholds.scenarios.max)) {
205
+ gaps.push(gap(poc, 'R5-scenarios-count', { field: 'plan.scenarios', params: { count: scenarios, min: thresholds.scenarios.min, max: thresholds.scenarios.max } }));
184
206
  }
185
207
  const risks = (plan.risks ?? []).length;
186
- if (risks > 3) {
187
- gaps.push(gap(poc, 'R6-risks-overflow', { field: 'plan.risks', params: { count: risks, max: 3 } }));
208
+ if (risks > thresholds.risks.max) {
209
+ gaps.push(gap(poc, 'R6-risks-overflow', { field: 'plan.risks', params: { count: risks, max: thresholds.risks.max } }));
188
210
  }
189
211
  // R7 — testing started before G2 was ready.
190
212
  const ready = text(plan.gate2?.ready);
@@ -219,9 +241,58 @@ export function scanGaps(poc, options) {
219
241
  const since = text(poc.stage_since);
220
242
  if (/^\d{4}-\d{2}-\d{2}$/.test(since)) {
221
243
  const days = daysSince(since, options.now);
222
- if (days !== null && days > options.stallDays) {
223
- gaps.push(gap(poc, 'R12-stage-stalled', { field: 'stage_since', params: { days, stage: text(poc.stage), stallDays: options.stallDays } }));
244
+ if (days !== null && days > thresholds.stallDays) {
245
+ gaps.push(gap(poc, 'R12-stage-stalled', { field: 'stage_since', params: { days, stage: text(poc.stage), stallDays: thresholds.stallDays } }));
224
246
  }
225
247
  }
248
+ // R13–R16 — the v3.1 state rules. They read the ledger's DERIVED per-item
249
+ // state, never a locally recomputed one: `tools/derive.mjs` is the only writer
250
+ // of `scenarios[].status` / `criteria[].status`, and CI rejects a file whose
251
+ // stored value disagrees with it. Re-deriving here would give this plugin a
252
+ // second opinion that the ledger would then call wrong.
253
+ const scenarioItems = Array.isArray(plan.scenarios) ? plan.scenarios : [];
254
+ const criteriaItems = Array.isArray(plan.criteria) ? plan.criteria : [];
255
+ const hasProgress = progress.length > 0;
256
+ // R13 — a scenario was claimed but nothing backs it. Guarded by
257
+ // `requires-progress`: before any progress exists, "no evidence" is just the
258
+ // project not having started, which is not a finding.
259
+ const unproven = scenarioItems.filter((item) => text(item?.status) === '无证据');
260
+ if (hasProgress && unproven.length > 0) {
261
+ gaps.push(gap(poc, 'R13-scenario-no-evidence', {
262
+ field: 'plan.scenarios',
263
+ params: { count: unproven.length, scenarios: unproven.map((item) => text(item?.name) || text(item?.id)).filter((name) => name !== '').join(',') },
264
+ }));
265
+ }
266
+ // R14 — proof exists and the customer has not spoken. `info`, not `medium`:
267
+ // waiting on the customer is a status, not a fault of the project.
268
+ const awaiting = scenarioItems.filter((item) => text(item?.status) === '待客户确认');
269
+ if (awaiting.length > 0) {
270
+ gaps.push(gap(poc, 'R14-scenario-awaiting-customer', {
271
+ field: 'plan.scenarios',
272
+ params: { count: awaiting.length, scenarios: awaiting.map((item) => text(item?.name) || text(item?.id)).filter((name) => name !== '').join(',') },
273
+ }));
274
+ }
275
+ // R15 — the plan is the right SIZE but a criterion is unverified.
276
+ // The guard is deliberate and comes from the ledger: R4 already reports a
277
+ // plan of the wrong size, so firing R15 alongside it reports the same fact
278
+ // twice and trains people to ignore the list. Fix the plan first.
279
+ const criteriaInRange = criteria >= thresholds.criteria.min && criteria <= thresholds.criteria.max;
280
+ const unverified = criteriaItems.filter((item) => text(item?.status) === '未验证');
281
+ if (criteriaInRange && unverified.length > 0) {
282
+ gaps.push(gap(poc, 'R15-criteria-unverified', {
283
+ field: 'plan.criteria',
284
+ params: { count: unverified.length, criteria: unverified.map((item) => text(item?.name) || text(item?.id)).filter((name) => name !== '').join(',') },
285
+ }));
286
+ }
287
+ // R16 — the plan is the right size, work has begun, and a scenario was never
288
+ // reached. Same guard shape as R15, plus `requires-progress`.
289
+ const scenariosInRange = scenarios >= thresholds.scenarios.min && scenarios <= thresholds.scenarios.max;
290
+ const notStarted = scenarioItems.filter((item) => text(item?.status) === '未开始');
291
+ if (scenariosInRange && hasProgress && notStarted.length > 0) {
292
+ gaps.push(gap(poc, 'R16-scenario-not-started', {
293
+ field: 'plan.scenarios',
294
+ params: { count: notStarted.length, scenarios: notStarted.map((item) => text(item?.name) || text(item?.id)).filter((name) => name !== '').join(',') },
295
+ }));
296
+ }
226
297
  return gaps.sort((left, right) => right.priority - left.priority || left.ruleNo - right.ruleNo || left.rule.localeCompare(right.rule));
227
298
  }
package/lib/repo.d.ts CHANGED
@@ -13,6 +13,22 @@
13
13
  * 3. **A refresh is exclusive.** One lock file keeps two console instances in
14
14
  * the same DSH home from cloning into the same directory at once.
15
15
  *
16
+ * ## The ledger has three sources, not one
17
+ *
18
+ * As of schema 3.1 the repository publishes three distinct things, and they fail
19
+ * independently:
20
+ *
21
+ * - `projects/*.yaml` — the facts. Absence is an error: without it there is no
22
+ * console at all.
23
+ * - `config/*.yaml` — the judgement (thresholds, rule metadata, staleness
24
+ * limits). Absence is a **stale cache**, not a failure: the plugin falls back
25
+ * to its built-in numbers and says so.
26
+ * - `signals/*.yaml` — the agent's conclusions. Absence is normal: most projects
27
+ * have none, and a signal is an opinion rather than a fact.
28
+ *
29
+ * Treating all three the same would either refuse to render a perfectly usable
30
+ * older cache, or silently present fallback thresholds as the ledger's.
31
+ *
16
32
  * Authentication is deliberately never stored: the token is read from the
17
33
  * already-authenticated `gh` CLI at call time and passed to git through an
18
34
  * environment-scoped `http.extraheader`, so it never lands in `.git/config`,
@@ -121,4 +137,48 @@ export declare class RepoCache {
121
137
  projectFiles(): Promise<string[]>;
122
138
  /** Read one project file, bounded so one huge file cannot stall the console. */
123
139
  readProject(path: string): Promise<string>;
140
+ /**
141
+ * The ledger's `config/rules.yaml`, or `null` when the cache predates it.
142
+ *
143
+ * Returning `null` rather than throwing is deliberate: a cache cloned before
144
+ * the ledger added `config/` is a stale cache, not a broken one, and the caller
145
+ * falls back to the built-in thresholds while saying so.
146
+ */
147
+ readRules(): Promise<string | null>;
148
+ /**
149
+ * The ledger's `config/derive.yaml`.
150
+ *
151
+ * Declares which derived fields the ledger stores and which are computed at
152
+ * read time. The plugin needs it to honour the same split: a stored value is a
153
+ * pure function of the record, a computed one depends on the clock and must
154
+ * never be shown as though it were written down.
155
+ */
156
+ readDerive(): Promise<string | null>;
157
+ /**
158
+ * The ledger's `config/health.yaml`.
159
+ *
160
+ * Holds two separate staleness notions — facts (nothing happened) and judgment
161
+ * (nobody looked) — that fail for different reasons and must not be collapsed.
162
+ */
163
+ readHealth(): Promise<string | null>;
164
+ /** One file from `config/`, or `null` when absent or unreasonably large. */
165
+ private readConfigFile;
166
+ /**
167
+ * The agent conclusions under `signals/`, keyed by `poc_id`.
168
+ *
169
+ * A signal is an opinion, not a fact: it is written only by the agent account,
170
+ * and the ledger's own README requires consumers to degrade gracefully when a
171
+ * field is missing or the directory does not exist yet. A malformed signal
172
+ * therefore becomes a warning and is skipped — it must never fail the page that
173
+ * shows the human facts.
174
+ */
175
+ signalFiles(): Promise<Map<string, string>>;
176
+ /**
177
+ * Read a file that is allowed not to exist.
178
+ *
179
+ * `null` means "this cache does not carry it", which callers translate into a
180
+ * degraded-but-usable state. Only `ENOENT` is treated that way: a permission
181
+ * error is a real problem and must surface.
182
+ */
183
+ private readOptionalFile;
124
184
  }