@skillre/dsh-plugin-work-dashboard 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +259 -0
  3. package/README.md +371 -2
  4. package/UNINSTALL.md +7 -0
  5. package/compatibility.json +195 -0
  6. package/cordis.patch.yml +24 -0
  7. package/docs/DESIGN-0.3.md +122 -0
  8. package/docs/DETAIL.md +1 -0
  9. package/docs/DETAIL.zh.md +1 -0
  10. package/docs/PLAN-0.7-0.9.md +230 -0
  11. package/docs/preview.svg +254 -0
  12. package/docs/preview.zh.svg +254 -0
  13. package/icon.svg +17 -0
  14. package/lib/blockers.d.ts +45 -0
  15. package/lib/blockers.js +160 -0
  16. package/lib/client/api.d.ts +42 -0
  17. package/lib/client/api.js +45 -0
  18. package/lib/client/contracts.d.ts +94 -0
  19. package/lib/client/contracts.js +21 -0
  20. package/lib/client/css/base.d.ts +31 -0
  21. package/lib/client/css/base.js +461 -0
  22. package/lib/client/css/blockers.d.ts +18 -0
  23. package/lib/client/css/blockers.js +196 -0
  24. package/lib/client/css/charts.d.ts +14 -0
  25. package/lib/client/css/charts.js +191 -0
  26. package/lib/client/css/detail.d.ts +21 -0
  27. package/lib/client/css/detail.js +423 -0
  28. package/lib/client/css/insights.d.ts +27 -0
  29. package/lib/client/css/insights.js +660 -0
  30. package/lib/client/css/overview.d.ts +23 -0
  31. package/lib/client/css/overview.js +327 -0
  32. package/lib/client/css/summary.d.ts +13 -0
  33. package/lib/client/css/summary.js +187 -0
  34. package/lib/client/format.d.ts +57 -0
  35. package/lib/client/format.js +96 -0
  36. package/lib/client/preferences.d.ts +56 -0
  37. package/lib/client/preferences.js +118 -0
  38. package/lib/client/styles.d.ts +17 -0
  39. package/lib/client/styles.js +24 -0
  40. package/lib/client/text.d.ts +32 -0
  41. package/lib/client/text.js +1112 -0
  42. package/lib/client/view-contract.d.ts +118 -0
  43. package/lib/client/view-contract.js +28 -0
  44. package/lib/client.js +6599 -0
  45. package/lib/config.d.ts +61 -0
  46. package/lib/config.js +67 -0
  47. package/lib/form.d.ts +218 -0
  48. package/lib/form.js +1075 -0
  49. package/lib/gap.d.ts +60 -0
  50. package/lib/gap.js +227 -0
  51. package/lib/index.d.ts +40 -0
  52. package/lib/index.js +159 -0
  53. package/lib/repo.d.ts +124 -0
  54. package/lib/repo.js +407 -0
  55. package/lib/risks.d.ts +24 -0
  56. package/lib/risks.js +85 -0
  57. package/lib/skill.d.ts +94 -0
  58. package/lib/skill.js +220 -0
  59. package/lib/store.d.ts +63 -0
  60. package/lib/store.js +505 -0
  61. package/lib/timeline.d.ts +23 -0
  62. package/lib/timeline.js +93 -0
  63. package/lib/transport.d.ts +67 -0
  64. package/lib/transport.js +131 -0
  65. package/lib/types.d.ts +701 -0
  66. package/lib/types.js +78 -0
  67. package/locale/en.json +7 -0
  68. package/locale/zh.json +7 -0
  69. package/package.json +117 -4
  70. package/skills/poc-export/SKILL.md +81 -0
  71. package/skills/poc-export/scripts/export-form.mjs +654 -0
  72. package/skills/poc-ledger/SKILL.md +171 -0
  73. package/skills/poc-submit/SKILL.md +186 -0
package/lib/store.js ADDED
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Read-only ledger store (v3).
3
+ *
4
+ * The store turns the cloned `projects/*.yaml` files into the JSON shapes the
5
+ * Client renders. It never writes: the repository is a read-only copy and the
6
+ * real data source is GitHub.
7
+ *
8
+ * v3 is **progress-centred**: a project's state is its identity + gate0 + plan +
9
+ * progress stream + outcome. The summary therefore reads `gate0` for the G0
10
+ * verdict, `plan` for focus, `progress` for activity, and `outcome` for the four
11
+ * dimensions — there is no separate `result` block to reconcile.
12
+ *
13
+ * Parsing uses `yaml`'s `parse`. One unreadable or unparsable file is reported
14
+ * as a warning and skipped: a single bad hand-edit must not blank the whole
15
+ * board.
16
+ */
17
+ import YAML from 'yaml';
18
+ import { daysSince, lastProgressDate, latestProgress, normalizeStage, numberOrNull, readDimensions, scanGaps, text, } from './gap.js';
19
+ import { buildBlockerBoard } from './blockers.js';
20
+ import { RepoError } from './repo.js';
21
+ /** The Host-side view model builder. */
22
+ export class PocStore {
23
+ cache;
24
+ options;
25
+ constructor(cache, options) {
26
+ this.cache = cache;
27
+ this.options = options;
28
+ }
29
+ /** Load every project file; one bad file becomes a warning, not a failure. */
30
+ async load() {
31
+ const files = await this.cache.projectFiles();
32
+ const records = [];
33
+ const warnings = [];
34
+ const seen = new Map();
35
+ for (const file of files) {
36
+ let source;
37
+ try {
38
+ source = await this.cache.readProject(file);
39
+ }
40
+ catch (error) {
41
+ warnings.push(error instanceof RepoError ? error.message : `Cannot read ${file}.`);
42
+ continue;
43
+ }
44
+ let parsed;
45
+ try {
46
+ parsed = YAML.parse(source);
47
+ }
48
+ catch (error) {
49
+ warnings.push(`${basename(file)}: ${error instanceof Error ? error.message.split('\n')[0] : 'invalid YAML'}`);
50
+ continue;
51
+ }
52
+ if (parsed === null || parsed === undefined) {
53
+ warnings.push(`${basename(file)}: the file is empty.`);
54
+ continue;
55
+ }
56
+ if (typeof parsed !== 'object' || Array.isArray(parsed)) {
57
+ warnings.push(`${basename(file)}: the document is not a YAML mapping.`);
58
+ continue;
59
+ }
60
+ const record = parsed;
61
+ const id = text(record.poc_id);
62
+ if (id === '') {
63
+ record.poc_id = basename(file).replace(/\.ya?ml$/, '');
64
+ warnings.push(`${basename(file)}: poc_id is missing; using the file name instead.`);
65
+ }
66
+ const finalId = text(record.poc_id);
67
+ const previous = seen.get(finalId);
68
+ if (previous !== undefined) {
69
+ warnings.push(`${basename(file)}: poc_id ${finalId} is already defined by ${previous}; both rows are shown.`);
70
+ }
71
+ else {
72
+ seen.set(finalId, basename(file));
73
+ }
74
+ records.push(record);
75
+ }
76
+ return { records, warnings };
77
+ }
78
+ /** The overview snapshot; never throws for a missing cache, it reports it. */
79
+ async snapshot() {
80
+ const cacheReady = await this.cache.isReady();
81
+ const repository = this.cache.repository;
82
+ if (!cacheReady) {
83
+ return {
84
+ cacheReady: false,
85
+ repository,
86
+ fetchedAt: this.cache.lastFetchedAt,
87
+ cachePath: this.cache.repoPath,
88
+ projects: [],
89
+ stats: emptyStats(),
90
+ gaps: [],
91
+ analysis: emptyAnalysis(),
92
+ blockers: buildBlockerBoard([], { now: this.options.now(), stallDays: this.options.stallDays }),
93
+ warnings: [],
94
+ };
95
+ }
96
+ const { records, warnings } = await this.load();
97
+ const now = this.options.now();
98
+ const projects = records.map((record) => summarize(record, now, this.options.stallDays));
99
+ const gaps = [];
100
+ for (const record of records) {
101
+ gaps.push(...scanGaps(record, { now, stallDays: this.options.stallDays }));
102
+ }
103
+ gaps.sort(compareGaps);
104
+ const sorted = projects.sort(compareProjects);
105
+ return {
106
+ cacheReady: true,
107
+ repository,
108
+ fetchedAt: this.cache.lastFetchedAt,
109
+ cachePath: this.cache.repoPath,
110
+ projects: sorted,
111
+ stats: computeStats(sorted),
112
+ gaps,
113
+ analysis: analyse(sorted, gaps),
114
+ blockers: buildBlockerBoard(records, { now, stallDays: this.options.stallDays }),
115
+ warnings,
116
+ };
117
+ }
118
+ /** One project's full record; `null` when no file declares that id. */
119
+ async detail(pocId) {
120
+ if (!(await this.cache.isReady()))
121
+ return null;
122
+ const { records } = await this.load();
123
+ const record = records.find((candidate) => text(candidate.poc_id) === pocId);
124
+ if (record === undefined)
125
+ return null;
126
+ const now = this.options.now();
127
+ const summary = summarize(record, now, this.options.stallDays);
128
+ const gate0 = record.gate0 ?? {};
129
+ const plan = record.plan ?? {};
130
+ const outcome = record.outcome ?? {};
131
+ const missing = Array.isArray(gate0.missing) ? gate0.missing.map(text).filter((item) => item !== '') : [];
132
+ return {
133
+ summary,
134
+ org: {
135
+ system: text((record.org ?? {}).system),
136
+ company: text((record.org ?? {}).company),
137
+ department: text((record.org ?? {}).department),
138
+ },
139
+ sales: text(record.sales),
140
+ execSponsor: text(record.exec_sponsor),
141
+ gate0: {
142
+ whyCustomer: text(gate0.why_customer),
143
+ whyUs: text(gate0.why_us),
144
+ decisionChain: text(gate0.decision_chain),
145
+ postPocDecision: text(gate0.post_poc_decision),
146
+ competitor: text(gate0.competitor),
147
+ conclusion: text(gate0.review?.conclusion),
148
+ reviewer: text(gate0.review?.reviewer),
149
+ reviewedAt: text(gate0.review?.reviewed_at),
150
+ missing,
151
+ complete: gate0.complete === true,
152
+ checklist: gate0Checklist({
153
+ whyCustomer: text(gate0.why_customer),
154
+ whyUs: text(gate0.why_us),
155
+ decisionChain: text(gate0.decision_chain),
156
+ postPocDecision: text(gate0.post_poc_decision),
157
+ }, text(record.tech_owner)),
158
+ },
159
+ plan: {
160
+ customerPain: text(plan.customer_pain),
161
+ expectedRecognition: text(plan.expected_recognition),
162
+ criteria: (plan.criteria ?? []).map((item) => ({
163
+ name: text(item?.name),
164
+ metric: text(item?.metric),
165
+ baseline: text(item?.baseline),
166
+ target: text(item?.target),
167
+ })),
168
+ scenarios: (plan.scenarios ?? []).map(text).filter((item) => item !== ''),
169
+ ourEdge: text(plan.our_edge),
170
+ timelineStart: text(plan.timeline?.start),
171
+ timelineEnd: text(plan.timeline?.end),
172
+ risks: (plan.risks ?? []).map((item) => ({
173
+ name: text(item?.name),
174
+ level: text(item?.level).toLowerCase(),
175
+ mitigation: text(item?.mitigation),
176
+ })),
177
+ reportNodes: (plan.report_nodes ?? []).map(text).filter((item) => item !== ''),
178
+ gate1Conclusion: text(plan.gate1?.conclusion),
179
+ gate2Ready: text(plan.gate2?.ready),
180
+ },
181
+ progress: (record.progress ?? []).map((entry) => ({
182
+ seq: numberOrNull(entry?.seq),
183
+ date: text(entry?.date),
184
+ type: text(entry?.type),
185
+ goal: text(entry?.goal),
186
+ items: (entry?.items ?? []).map(text).filter((item) => item !== ''),
187
+ actual: text(entry?.actual),
188
+ completion: text(entry?.completion),
189
+ evidence: (entry?.evidence ?? []).map((item) => ({
190
+ title: text(item?.title),
191
+ link: text(item?.link),
192
+ type: text(item?.type),
193
+ })),
194
+ customer: {
195
+ syncedWith: text(entry?.customer?.synced_with),
196
+ feedback: text(entry?.customer?.feedback),
197
+ recognition: text(entry?.customer?.recognition),
198
+ },
199
+ gate3_1: text(entry?.gate3_1),
200
+ gate3_2: text(entry?.gate3_2),
201
+ next: {
202
+ goal: text(entry?.next?.goal),
203
+ owner: text(entry?.next?.owner),
204
+ deadline: text(entry?.next?.deadline),
205
+ },
206
+ })),
207
+ outcome: {
208
+ achievement: text(outcome.achievement),
209
+ customerRecognition: text(outcome.customer_recognition),
210
+ ourProof: text(outcome.our_proof),
211
+ remainingRisks: text(outcome.remaining_risks),
212
+ proved: text(outcome.conclusion?.proved),
213
+ recognized: text(outcome.conclusion?.recognized),
214
+ nextBusiness: text(outcome.conclusion?.next_business),
215
+ milestone: text(outcome.business?.milestone),
216
+ businessOwner: text(outcome.business?.owner),
217
+ businessDeadline: text(outcome.business?.deadline),
218
+ businessStatus: text(outcome.business?.status),
219
+ overall: text(outcome.overall),
220
+ reviewedAt: text(outcome.reviewed_at),
221
+ },
222
+ gaps: scanGaps(record, { now, stallDays: this.options.stallDays }),
223
+ };
224
+ }
225
+ }
226
+ /** File name without its directory, for warning text. */
227
+ function basename(path) {
228
+ const index = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
229
+ return index === -1 ? path : path.slice(index + 1);
230
+ }
231
+ /** One line describing the newest progress entry, for the table's summary cell. */
232
+ function progressSummary(poc) {
233
+ const last = latestProgress(poc);
234
+ if (last === null)
235
+ return '';
236
+ const parts = [];
237
+ const type = text(last.type);
238
+ if (type !== '')
239
+ parts.push(type);
240
+ const actual = text(last.actual);
241
+ if (actual !== '')
242
+ parts.push(actual.replace(/\s+/g, ' ').slice(0, 80));
243
+ const completion = text(last.completion);
244
+ if (completion !== '')
245
+ parts.push(completion);
246
+ return parts.join(' · ');
247
+ }
248
+ /** Collapse one record into the table row the overview renders. */
249
+ function summarize(record, now, stallDays) {
250
+ const dimensions = readDimensions(record);
251
+ const { stage, closed } = normalizeStage(record.stage);
252
+ const gaps = scanGaps(record, { now, stallDays });
253
+ const gate0 = record.gate0 ?? {};
254
+ const activity = lastProgressDate(record);
255
+ const stageSince = text(record.stage_since);
256
+ const progress = Array.isArray(record.progress) ? record.progress : [];
257
+ const missing = Array.isArray(gate0.missing) ? gate0.missing.map(text).filter((item) => item !== '') : [];
258
+ const plan = record.plan ?? {};
259
+ const last = latestProgress(record);
260
+ // v3 has no gate-completion array: each stage reads its own source field.
261
+ const stageDone = [
262
+ gate0.complete === true,
263
+ text(plan.gate1?.conclusion) === '通过',
264
+ text(plan.gate2?.ready) === 'Ready',
265
+ last !== null && text(last.gate3_2) === '已确认',
266
+ text((record.outcome ?? {}).achievement) === '达成',
267
+ ];
268
+ return {
269
+ pocId: text(record.poc_id),
270
+ name: text(record.name) === '' ? text(record.poc_id) : text(record.name),
271
+ system: text((record.org ?? {}).system),
272
+ company: text((record.org ?? {}).company),
273
+ department: text((record.org ?? {}).department),
274
+ pocType: text(record.poc_type),
275
+ amountWan: numberOrNull(record.amount_wan) ?? 0,
276
+ priority: text(record.priority),
277
+ stageLabel: text(record.stage),
278
+ stage,
279
+ closed,
280
+ status: text(record.status),
281
+ stageSince: stageSince === '' ? null : stageSince,
282
+ daysInStage: daysSince(stageSince === '' ? null : stageSince, now),
283
+ owner: text(record.owner),
284
+ techOwner: text(record.tech_owner),
285
+ g0Conclusion: text(gate0.review?.conclusion),
286
+ g0Passed: text(gate0.review?.conclusion) === '通过',
287
+ g0Complete: gate0.complete === true,
288
+ g0MissingCount: missing.length,
289
+ stageDone,
290
+ dimensions,
291
+ dimensionCount: ['achievement', 'evidence', 'recognition', 'nextMilestone'].filter((key) => dimensions[key]).length,
292
+ gapCount: gaps.length,
293
+ highGapCount: gaps.filter((item) => item.level === 'high').length,
294
+ progressCount: progress.length,
295
+ lastProgressDate: activity,
296
+ lastProgressSummary: progressSummary(record),
297
+ daysSinceProgress: daysSince(activity, now),
298
+ outcomeAchievement: text((record.outcome ?? {}).achievement),
299
+ outcomeRecognition: text((record.outcome ?? {}).customer_recognition),
300
+ // Read from the NEWEST progress entry, not from `outcome`: the outcome block
301
+ // is written later by hand, and "waiting on the customer" is a statement
302
+ // about the last round that actually happened.
303
+ lastRecognition: last === null
304
+ ? ''
305
+ : text(last.customer?.recognition),
306
+ };
307
+ }
308
+ /**
309
+ * The v3 headline counters.
310
+ *
311
+ * Each one is derived from the same rows the table shows, so the strip and the
312
+ * table can never disagree.
313
+ */
314
+ function computeStats(projects) {
315
+ let amountTotalWan = 0;
316
+ for (const project of projects) {
317
+ amountTotalWan += project.amountWan;
318
+ }
319
+ return {
320
+ total: projects.length,
321
+ g0Passed: projects.filter((project) => project.g0Passed).length,
322
+ inProgress: projects.filter((project) => project.status === '进行中').length,
323
+ amountTotalWan,
324
+ g0Complete: projects.filter((project) => project.g0Complete).length,
325
+ // "Awaiting customer" = the newest progress entry says the customer has not
326
+ // signed off yet. It used to be a `let` that was never incremented, so the
327
+ // counter was hard-wired to 0 while the KPI strip displayed it.
328
+ awaitingCustomer: projects.filter((project) => project.lastRecognition === '待确认' || project.lastRecognition === '部分认可').length,
329
+ succeeded: projects.filter((project) => project.outcomeAchievement === '达成' && project.outcomeRecognition === '认可').length,
330
+ stopped: projects.filter((project) => project.status === '暂停' || project.status === '已关闭' || project.status === '已取消').length,
331
+ };
332
+ }
333
+ /** Empty counters for the "no data yet" snapshot. */
334
+ function emptyStats() {
335
+ return {
336
+ total: 0,
337
+ g0Passed: 0,
338
+ inProgress: 0,
339
+ amountTotalWan: 0,
340
+ g0Complete: 0,
341
+ awaitingCustomer: 0,
342
+ succeeded: 0,
343
+ stopped: 0,
344
+ };
345
+ }
346
+ /** Gap order: severity first, then the highest-value rule, then the project. */ function compareGaps(left, right) {
347
+ return (right.priority - left.priority ||
348
+ left.ruleNo - right.ruleNo ||
349
+ left.pocId.localeCompare(right.pocId) ||
350
+ left.rule.localeCompare(right.rule));
351
+ }
352
+ /** Project order: the ones needing attention first, then by id. */
353
+ function compareProjects(left, right) {
354
+ return right.highGapCount - left.highGapCount || right.gapCount - left.gapCount || left.pocId.localeCompare(right.pocId);
355
+ }
356
+ /** The stage buckets in display order, so the funnel always reads G0→G4. */
357
+ const STAGE_ORDER = ['G0', 'G1', 'G2', 'G3', 'G4', 'closed', 'unknown'];
358
+ /** The four dimensions in display order. */
359
+ const DIMENSION_ORDER = ['achievement', 'evidence', 'recognition', 'nextMilestone'];
360
+ /** Which stage bucket one project belongs to. */
361
+ function stageBucketOf(project) {
362
+ if (project.closed)
363
+ return 'closed';
364
+ return project.stage ?? 'unknown';
365
+ }
366
+ /**
367
+ * Aggregate the project list into the portfolio band.
368
+ *
369
+ * This is the only place the charts get their numbers from. Everything is
370
+ * derived from `projects` (and the already-scanned `gaps`), so a chart can
371
+ * never show a figure the table contradicts. Buckets keep their full cardinality
372
+ * even when empty: a funnel with a missing column reads as a rendering bug.
373
+ */
374
+ export function analyse(projects, gaps) {
375
+ const totalAmount = projects.reduce((sum, project) => sum + project.amountWan, 0);
376
+ const stageMap = new Map();
377
+ for (const key of STAGE_ORDER)
378
+ stageMap.set(key, { key, count: 0, amountWan: 0, highGapCount: 0 });
379
+ for (const project of projects) {
380
+ const bucket = stageMap.get(stageBucketOf(project));
381
+ if (bucket === undefined)
382
+ continue;
383
+ bucket.count += 1;
384
+ bucket.amountWan += project.amountWan;
385
+ if (project.highGapCount > 0)
386
+ bucket.highGapCount += 1;
387
+ }
388
+ const orgMap = new Map();
389
+ for (const project of projects) {
390
+ // A project without a company still belongs somewhere: group it under its
391
+ // system so the breakdown accounts for every project exactly once.
392
+ const key = `${project.system}\u0000${project.company}`;
393
+ const existing = orgMap.get(key);
394
+ if (existing === undefined) {
395
+ orgMap.set(key, {
396
+ system: project.system,
397
+ company: project.company,
398
+ count: 1,
399
+ amountWan: project.amountWan,
400
+ highGapCount: project.highGapCount > 0 ? 1 : 0,
401
+ });
402
+ }
403
+ else {
404
+ existing.count += 1;
405
+ existing.amountWan += project.amountWan;
406
+ if (project.highGapCount > 0)
407
+ existing.highGapCount += 1;
408
+ }
409
+ }
410
+ const typeMap = new Map();
411
+ for (const project of projects) {
412
+ const key = project.pocType;
413
+ const existing = typeMap.get(key);
414
+ if (existing === undefined) {
415
+ typeMap.set(key, { pocType: key, count: 1, amountWan: project.amountWan });
416
+ }
417
+ else {
418
+ existing.count += 1;
419
+ existing.amountWan += project.amountWan;
420
+ }
421
+ }
422
+ const gapRuleMap = new Map();
423
+ for (const item of gaps) {
424
+ const existing = gapRuleMap.get(item.rule);
425
+ if (existing === undefined) {
426
+ gapRuleMap.set(item.rule, { rule: item.rule, ruleNo: item.ruleNo, level: item.level, count: 1 });
427
+ }
428
+ else {
429
+ existing.count += 1;
430
+ }
431
+ }
432
+ const topAmounts = [...projects]
433
+ .filter((project) => project.amountWan > 0)
434
+ .sort((left, right) => right.amountWan - left.amountWan || left.pocId.localeCompare(right.pocId))
435
+ .slice(0, 5)
436
+ .map((project) => ({
437
+ pocId: project.pocId,
438
+ pocName: project.name,
439
+ amountWan: project.amountWan,
440
+ share: totalAmount === 0 ? 0 : project.amountWan / totalAmount,
441
+ stage: project.stage,
442
+ closed: project.closed,
443
+ }));
444
+ const dimensions = DIMENSION_ORDER.map((key) => {
445
+ const present = projects.filter((project) => project.dimensions[key]).length;
446
+ const missing = projects.length - present;
447
+ return { key, present, missing, ratio: projects.length === 0 ? 0 : present / projects.length };
448
+ });
449
+ let lastActivity = null;
450
+ for (const project of projects) {
451
+ const date = project.lastProgressDate;
452
+ if (date === null)
453
+ continue;
454
+ if (lastActivity === null || date > lastActivity)
455
+ lastActivity = date;
456
+ }
457
+ const largest = topAmounts.length === 0 ? 0 : topAmounts[0].amountWan;
458
+ return {
459
+ stages: STAGE_ORDER.map((key) => stageMap.get(key)),
460
+ orgs: [...orgMap.values()].sort((left, right) => right.amountWan - left.amountWan ||
461
+ left.system.localeCompare(right.system) ||
462
+ left.company.localeCompare(right.company)),
463
+ types: [...typeMap.values()].sort((left, right) => right.count - left.count || right.amountWan - left.amountWan || left.pocType.localeCompare(right.pocType)),
464
+ topAmounts,
465
+ dimensions,
466
+ gapRules: [...gapRuleMap.values()].sort((left, right) => right.count - left.count || left.ruleNo - right.ruleNo),
467
+ concentration: totalAmount === 0 ? 0 : largest / totalAmount,
468
+ amountMissing: projects.filter((project) => project.amountWan === 0).length,
469
+ withProgress: projects.filter((project) => project.progressCount > 0).length,
470
+ lastActivity,
471
+ };
472
+ }
473
+ /** An empty analysis, for the cold-cache snapshot. */
474
+ export function emptyAnalysis() {
475
+ return {
476
+ stages: STAGE_ORDER.map((key) => ({ key, count: 0, amountWan: 0, highGapCount: 0 })),
477
+ orgs: [],
478
+ types: [],
479
+ topAmounts: [],
480
+ dimensions: DIMENSION_ORDER.map((key) => ({ key, present: 0, missing: 0, ratio: 0 })),
481
+ gapRules: [],
482
+ concentration: 0,
483
+ amountMissing: 0,
484
+ withProgress: 0,
485
+ lastActivity: null,
486
+ };
487
+ }
488
+ /**
489
+ * The five G0 prerequisites, in schema order.
490
+ *
491
+ * `tech_owner` is one of the five but lives in the identity block, so the
492
+ * checklist reads it from the record rather than from `gate0`.
493
+ */
494
+ const G0_FIELDS = [
495
+ { field: 'why_customer', viewKey: 'whyCustomer' },
496
+ { field: 'why_us', viewKey: 'whyUs' },
497
+ { field: 'decision_chain', viewKey: 'decisionChain' },
498
+ { field: 'post_poc_decision', viewKey: 'postPocDecision' },
499
+ ];
500
+ /** Build the G0 checklist from the parsed fields. */
501
+ export function gate0Checklist(gate0, techOwner) {
502
+ const items = G0_FIELDS.map(({ field, viewKey }) => ({ field, present: gate0[viewKey] !== '', value: gate0[viewKey] }));
503
+ items.push({ field: 'tech_owner', present: techOwner !== '', value: techOwner });
504
+ return items;
505
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The global timeline: every progress entry of every project, newest first.
3
+ *
4
+ * v3 is progress-centred: `progress[]` IS the history, so this view is the only
5
+ * place that shows rhythm across the whole portfolio — who has gone quiet, when
6
+ * did the team actually do things, and which entries produced evidence versus
7
+ * only a conversation.
8
+ *
9
+ * Entries are ordered by date descending, with the project id as a stable
10
+ * tiebreaker. Dates that do not parse are excluded from the range and the month
11
+ * summary but still appear in the list, because dropping them would hide a
12
+ * record the ledger actually contains.
13
+ */
14
+ import type { GlobalTimeline, PocRecord } from './types.js';
15
+ /**
16
+ * Build the global timeline from the loaded records.
17
+ *
18
+ * The silence threshold is expressed in days and matches the gap rule's own
19
+ * default rather than inventing a second notion of "stale".
20
+ */
21
+ export declare function buildGlobalTimeline(records: readonly PocRecord[], options: {
22
+ stallDays: number;
23
+ }): GlobalTimeline;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The global timeline: every progress entry of every project, newest first.
3
+ *
4
+ * v3 is progress-centred: `progress[]` IS the history, so this view is the only
5
+ * place that shows rhythm across the whole portfolio — who has gone quiet, when
6
+ * did the team actually do things, and which entries produced evidence versus
7
+ * only a conversation.
8
+ *
9
+ * Entries are ordered by date descending, with the project id as a stable
10
+ * tiebreaker. Dates that do not parse are excluded from the range and the month
11
+ * summary but still appear in the list, because dropping them would hide a
12
+ * record the ledger actually contains.
13
+ */
14
+ import { normalizeStage, numberOrNull, text } from './gap.js';
15
+ /** `true` when a value is a real `YYYY-MM-DD` date. */
16
+ function isDate(value) {
17
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
18
+ }
19
+ /**
20
+ * Build the global timeline from the loaded records.
21
+ *
22
+ * The silence threshold is expressed in days and matches the gap rule's own
23
+ * default rather than inventing a second notion of "stale".
24
+ */
25
+ export function buildGlobalTimeline(records, options) {
26
+ const entries = [];
27
+ const silentProjects = [];
28
+ for (const record of records) {
29
+ const pocId = text(record.poc_id);
30
+ const pocName = text(record.name) === '' ? pocId : text(record.name);
31
+ const { stage } = normalizeStage(record.stage);
32
+ const progress = Array.isArray(record.progress) ? record.progress : [];
33
+ if (progress.length === 0) {
34
+ silentProjects.push({ pocId, pocName });
35
+ continue;
36
+ }
37
+ for (const raw of progress) {
38
+ const entry = (raw ?? {});
39
+ const evidence = Array.isArray(entry.evidence) ? entry.evidence : [];
40
+ const customer = (entry.customer ?? {});
41
+ const next = (entry.next ?? {});
42
+ const titles = evidence
43
+ .map((item) => text(item?.title))
44
+ .filter((title) => title !== '');
45
+ entries.push({
46
+ pocId,
47
+ pocName,
48
+ stage,
49
+ date: text(entry.date),
50
+ seq: numberOrNull(entry.seq),
51
+ type: text(entry.type),
52
+ goal: text(entry.goal),
53
+ actual: text(entry.actual),
54
+ completion: text(entry.completion),
55
+ evidence: titles.join(' · '),
56
+ evidenceCount: evidence.length,
57
+ customerFeedback: text(customer.feedback),
58
+ recognition: text(customer.recognition),
59
+ gate3_1: text(entry.gate3_1),
60
+ gate3_2: text(entry.gate3_2),
61
+ nextGoal: text(next.goal),
62
+ nextOwner: text(next.owner),
63
+ nextDeadline: text(next.deadline),
64
+ });
65
+ }
66
+ }
67
+ // Newest first; entries with an unparsable date sink below the dated ones but
68
+ // keep a stable order among themselves.
69
+ entries.sort((left, right) => {
70
+ const leftDated = isDate(left.date);
71
+ const rightDated = isDate(right.date);
72
+ if (leftDated !== rightDated)
73
+ return leftDated ? -1 : 1;
74
+ if (leftDated && rightDated && left.date !== right.date)
75
+ return right.date.localeCompare(left.date);
76
+ return left.pocId.localeCompare(right.pocId) || (left.seq ?? 0) - (right.seq ?? 0);
77
+ });
78
+ const dated = entries.filter((entry) => isDate(entry.date)).map((entry) => entry.date).sort();
79
+ const range = dated.length === 0 ? null : { from: dated[0], to: dated[dated.length - 1] };
80
+ // One row per month that actually has activity, newest month first.
81
+ const monthCounts = new Map();
82
+ for (const entry of entries) {
83
+ if (!isDate(entry.date))
84
+ continue;
85
+ const month = entry.date.slice(0, 7);
86
+ monthCounts.set(month, (monthCounts.get(month) ?? 0) + 1);
87
+ }
88
+ const months = [...monthCounts.entries()]
89
+ .map(([month, count]) => ({ month, count }))
90
+ .sort((left, right) => right.month.localeCompare(left.month));
91
+ void options.stallDays;
92
+ return { entries, range, months, silentProjects };
93
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Host ↔ Client transport: one exact Fetch route inside Connection's fence.
3
+ *
4
+ * Connection owns the Host/Origin check, the browser-session authentication and
5
+ * the Peer scope; this module registers one exact `POST /api/<endpoint>` route
6
+ * and only validates its own envelope and payload. No physical server, no
7
+ * Express, and no second RPC channel is claimed.
8
+ *
9
+ * The wire envelope is the inspected Connection unary shape:
10
+ * `{ type: 'client-request', rpcId, method, payload }` in and
11
+ * `{ type: 'server-response', rpcId, result: { ok: true, value } | { ok: false, error } }`
12
+ * out. A non-owner Peer is rejected by Connection before this handler runs.
13
+ */
14
+ import type { ExportFormResult, GlobalTimeline, ProjectDetail, RefreshOutcome, RiskBoard, Snapshot } from './types.js';
15
+ /** Path of the exact route, under the shared `/api` channel. */
16
+ export declare const EXECUTE_PATH = "/api/skillre-work-dashboard/execute";
17
+ /** One buffered exact Fetch route as the Connection registry accepts it. */
18
+ export interface FetchRoute {
19
+ readonly path: string;
20
+ readonly methods: readonly ['POST'];
21
+ readonly requestBody: 'buffered';
22
+ readonly fetch: (request: Request) => Promise<Response>;
23
+ }
24
+ /** The Host Connection face this plugin depends on. */
25
+ export interface HostConnection {
26
+ readonly fetch: {
27
+ register(route: FetchRoute): () => Promise<void>;
28
+ };
29
+ }
30
+ /** The console operations the route dispatches onto. */
31
+ export interface ConsoleActions {
32
+ /** The current snapshot; a cold cache reports `cacheReady: false`. */
33
+ snapshot(): Promise<Snapshot>;
34
+ /** Clone or fast-forward the cache, then return the new snapshot. */
35
+ refresh(): Promise<{
36
+ snapshot: Snapshot;
37
+ outcome: RefreshOutcome;
38
+ }>;
39
+ /** One project's detail, or `null` when the id is unknown. */
40
+ detail(pocId: string): Promise<ProjectDetail | null>;
41
+ /** Every project's risks, sorted by severity. */
42
+ risks(): Promise<RiskBoard>;
43
+ /** Every project's rounds, newest first. */
44
+ timeline(): Promise<GlobalTimeline>;
45
+ /**
46
+ * Build the collection form for one batch.
47
+ *
48
+ * `blank` ignores `pocIds` and returns the new-project form.
49
+ */
50
+ exportForm(mode: 'fill' | 'blank', pocIds: readonly string[]): Promise<ExportFormResult>;
51
+ }
52
+ /**
53
+ * Build the exact route Connection registers; every failure stays inside the
54
+ * envelope. A `RepoError` is authored for the user; anything else is a Host
55
+ * fault whose text must not become UI copy (and must not leak backend detail).
56
+ */
57
+ export interface ExecuteRouteOptions {
58
+ /**
59
+ * Report an internal fault to the Host log.
60
+ *
61
+ * The response stays a generic message (no backend detail may reach UI copy),
62
+ * but a swallowed error is undiagnosable, so the plugin hands the real
63
+ * failure to the Host logger exactly once per request.
64
+ */
65
+ onInternalError?(error: unknown): void;
66
+ }
67
+ export declare function createExecuteRoute(ready: () => Promise<ConsoleActions>, options?: ExecuteRouteOptions): FetchRoute;