@sentropic/track 0.98.10 → 0.98.11-rc.13

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 (218) hide show
  1. package/README.md +39 -6
  2. package/dist/adopt/apply.d.ts +30 -0
  3. package/dist/adopt/apply.d.ts.map +1 -0
  4. package/dist/adopt/apply.js +573 -0
  5. package/dist/adopt/apply.js.map +1 -0
  6. package/dist/adopt/plan.d.ts +63 -0
  7. package/dist/adopt/plan.d.ts.map +1 -0
  8. package/dist/adopt/plan.js +320 -0
  9. package/dist/adopt/plan.js.map +1 -0
  10. package/dist/capture/cli.d.ts +5 -0
  11. package/dist/capture/cli.d.ts.map +1 -0
  12. package/dist/capture/cli.js +532 -0
  13. package/dist/capture/cli.js.map +1 -0
  14. package/dist/capture/index.d.ts +8 -0
  15. package/dist/capture/index.d.ts.map +1 -0
  16. package/dist/capture/index.js +8 -0
  17. package/dist/capture/index.js.map +1 -0
  18. package/dist/capture/inscribe.d.ts +64 -0
  19. package/dist/capture/inscribe.d.ts.map +1 -0
  20. package/dist/capture/inscribe.js +407 -0
  21. package/dist/capture/inscribe.js.map +1 -0
  22. package/dist/capture/markers.d.ts +10 -0
  23. package/dist/capture/markers.d.ts.map +1 -0
  24. package/dist/capture/markers.js +26 -0
  25. package/dist/capture/markers.js.map +1 -0
  26. package/dist/capture/queue.d.ts +131 -0
  27. package/dist/capture/queue.d.ts.map +1 -0
  28. package/dist/capture/queue.js +422 -0
  29. package/dist/capture/queue.js.map +1 -0
  30. package/dist/capture/reader.d.ts +42 -0
  31. package/dist/capture/reader.d.ts.map +1 -0
  32. package/dist/capture/reader.js +72 -0
  33. package/dist/capture/reader.js.map +1 -0
  34. package/dist/capture/registry.d.ts +42 -0
  35. package/dist/capture/registry.d.ts.map +1 -0
  36. package/dist/capture/registry.js +141 -0
  37. package/dist/capture/registry.js.map +1 -0
  38. package/dist/capture/secrets.d.ts +30 -0
  39. package/dist/capture/secrets.d.ts.map +1 -0
  40. package/dist/capture/secrets.js +145 -0
  41. package/dist/capture/secrets.js.map +1 -0
  42. package/dist/cli/adopt.d.ts +10 -0
  43. package/dist/cli/adopt.d.ts.map +1 -0
  44. package/dist/cli/adopt.js +151 -0
  45. package/dist/cli/adopt.js.map +1 -0
  46. package/dist/cli/desync.d.ts +24 -4
  47. package/dist/cli/desync.d.ts.map +1 -1
  48. package/dist/cli/desync.js +86 -22
  49. package/dist/cli/desync.js.map +1 -1
  50. package/dist/cli/events-contains.d.ts +2 -0
  51. package/dist/cli/events-contains.d.ts.map +1 -1
  52. package/dist/cli/events-contains.js +1 -1
  53. package/dist/cli/events-contains.js.map +1 -1
  54. package/dist/cli/index.d.ts +2 -0
  55. package/dist/cli/index.d.ts.map +1 -1
  56. package/dist/cli/index.js +443 -17
  57. package/dist/cli/index.js.map +1 -1
  58. package/dist/cli/install-skills.d.ts +2 -0
  59. package/dist/cli/install-skills.d.ts.map +1 -1
  60. package/dist/cli/install-skills.js +74 -12
  61. package/dist/cli/install-skills.js.map +1 -1
  62. package/dist/cli/journal-reference.d.ts +46 -0
  63. package/dist/cli/journal-reference.d.ts.map +1 -0
  64. package/dist/cli/journal-reference.js +434 -0
  65. package/dist/cli/journal-reference.js.map +1 -0
  66. package/dist/cli/journal.d.ts +12 -0
  67. package/dist/cli/journal.d.ts.map +1 -0
  68. package/dist/cli/journal.js +302 -0
  69. package/dist/cli/journal.js.map +1 -0
  70. package/dist/cli/resolve.d.ts.map +1 -1
  71. package/dist/cli/resolve.js +9 -0
  72. package/dist/cli/resolve.js.map +1 -1
  73. package/dist/cli/restructure-apply.d.ts +3 -0
  74. package/dist/cli/restructure-apply.d.ts.map +1 -1
  75. package/dist/cli/restructure-apply.js +5 -1
  76. package/dist/cli/restructure-apply.js.map +1 -1
  77. package/dist/events/store.d.ts +5 -1
  78. package/dist/events/store.d.ts.map +1 -1
  79. package/dist/events/store.js +8 -1
  80. package/dist/events/store.js.map +1 -1
  81. package/dist/events/types.d.ts +8 -3
  82. package/dist/events/types.d.ts.map +1 -1
  83. package/dist/events/types.js +12 -0
  84. package/dist/events/types.js.map +1 -1
  85. package/dist/focus-vendor/artifact/check.d.ts +73 -0
  86. package/dist/focus-vendor/artifact/check.d.ts.map +1 -0
  87. package/dist/focus-vendor/artifact/check.js +148 -0
  88. package/dist/focus-vendor/artifact/check.js.map +1 -0
  89. package/dist/focus-vendor/artifact/index.d.ts +3 -0
  90. package/dist/focus-vendor/artifact/index.d.ts.map +1 -0
  91. package/dist/focus-vendor/artifact/index.js +3 -0
  92. package/dist/focus-vendor/artifact/index.js.map +1 -0
  93. package/dist/focus-vendor/artifact/manifest.d.ts +74 -0
  94. package/dist/focus-vendor/artifact/manifest.d.ts.map +1 -0
  95. package/dist/focus-vendor/artifact/manifest.js +485 -0
  96. package/dist/focus-vendor/artifact/manifest.js.map +1 -0
  97. package/dist/focus-vendor/cli/index.d.ts +1 -1
  98. package/dist/focus-vendor/index.d.ts +1 -0
  99. package/dist/focus-vendor/index.js +1 -0
  100. package/dist/focus-vendor/index.js.map +1 -1
  101. package/dist/focus-vendor/registry/entries.v1.json +1 -1
  102. package/dist/fs-private.d.ts +37 -0
  103. package/dist/fs-private.d.ts.map +1 -0
  104. package/dist/fs-private.js +224 -0
  105. package/dist/fs-private.js.map +1 -0
  106. package/dist/graph-export.d.ts +19 -0
  107. package/dist/graph-export.d.ts.map +1 -1
  108. package/dist/graph-export.js +53 -0
  109. package/dist/graph-export.js.map +1 -1
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +8 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/journal/identity.d.ts +37 -0
  115. package/dist/journal/identity.d.ts.map +1 -0
  116. package/dist/journal/identity.js +134 -0
  117. package/dist/journal/identity.js.map +1 -0
  118. package/dist/journal/index-store.d.ts +56 -0
  119. package/dist/journal/index-store.d.ts.map +1 -0
  120. package/dist/journal/index-store.js +167 -0
  121. package/dist/journal/index-store.js.map +1 -0
  122. package/dist/journal/index.d.ts +4 -0
  123. package/dist/journal/index.d.ts.map +1 -0
  124. package/dist/journal/index.js +4 -0
  125. package/dist/journal/index.js.map +1 -0
  126. package/dist/journal/inscription.d.ts +28 -0
  127. package/dist/journal/inscription.d.ts.map +1 -0
  128. package/dist/journal/inscription.js +93 -0
  129. package/dist/journal/inscription.js.map +1 -0
  130. package/dist/model/blocker.d.ts +2 -0
  131. package/dist/model/blocker.d.ts.map +1 -1
  132. package/dist/model/blocker.js.map +1 -1
  133. package/dist/model/decision.d.ts +11 -0
  134. package/dist/model/decision.d.ts.map +1 -1
  135. package/dist/model/decision.js +4 -0
  136. package/dist/model/decision.js.map +1 -1
  137. package/dist/model/demand.d.ts +34 -1
  138. package/dist/model/demand.d.ts.map +1 -1
  139. package/dist/model/demand.js +4 -0
  140. package/dist/model/demand.js.map +1 -1
  141. package/dist/model/item.d.ts +3 -1
  142. package/dist/model/item.d.ts.map +1 -1
  143. package/dist/model/item.js.map +1 -1
  144. package/dist/model/report-status.d.ts +124 -21
  145. package/dist/model/report-status.d.ts.map +1 -1
  146. package/dist/model/report-status.js +372 -38
  147. package/dist/model/report-status.js.map +1 -1
  148. package/dist/read/commands.d.ts +15 -0
  149. package/dist/read/commands.d.ts.map +1 -1
  150. package/dist/read/commands.js +26 -0
  151. package/dist/read/commands.js.map +1 -1
  152. package/dist/read/contract.d.ts +24 -0
  153. package/dist/read/contract.d.ts.map +1 -1
  154. package/dist/read/contract.js +68 -1
  155. package/dist/read/contract.js.map +1 -1
  156. package/dist/read/index.d.ts +2 -2
  157. package/dist/read/index.d.ts.map +1 -1
  158. package/dist/read/index.js +1 -1
  159. package/dist/read/index.js.map +1 -1
  160. package/dist/report/audit.d.ts +2 -19
  161. package/dist/report/audit.d.ts.map +1 -1
  162. package/dist/report/audit.js +9 -26
  163. package/dist/report/audit.js.map +1 -1
  164. package/dist/report/index.d.ts +2 -0
  165. package/dist/report/index.d.ts.map +1 -1
  166. package/dist/report/index.js +2 -0
  167. package/dist/report/index.js.map +1 -1
  168. package/dist/report/owner-table-qualified.d.ts +153 -0
  169. package/dist/report/owner-table-qualified.d.ts.map +1 -0
  170. package/dist/report/owner-table-qualified.js +702 -0
  171. package/dist/report/owner-table-qualified.js.map +1 -0
  172. package/dist/report/owner-table-scope.d.ts +41 -0
  173. package/dist/report/owner-table-scope.d.ts.map +1 -0
  174. package/dist/report/owner-table-scope.js +92 -0
  175. package/dist/report/owner-table-scope.js.map +1 -0
  176. package/dist/report/owner-table-strings.d.ts +142 -0
  177. package/dist/report/owner-table-strings.d.ts.map +1 -0
  178. package/dist/report/owner-table-strings.js +321 -0
  179. package/dist/report/owner-table-strings.js.map +1 -0
  180. package/dist/report/owner-table.d.ts +194 -0
  181. package/dist/report/owner-table.d.ts.map +1 -0
  182. package/dist/report/owner-table.js +2154 -0
  183. package/dist/report/owner-table.js.map +1 -0
  184. package/dist/report/stage-status-lexicon.d.ts.map +1 -1
  185. package/dist/report/stage-status-lexicon.js +61 -37
  186. package/dist/report/stage-status-lexicon.js.map +1 -1
  187. package/dist/report/stage-status.d.ts +20 -9
  188. package/dist/report/stage-status.d.ts.map +1 -1
  189. package/dist/report/stage-status.js +211 -85
  190. package/dist/report/stage-status.js.map +1 -1
  191. package/dist/report/velocity-eta.d.ts +81 -0
  192. package/dist/report/velocity-eta.d.ts.map +1 -0
  193. package/dist/report/velocity-eta.js +217 -0
  194. package/dist/report/velocity-eta.js.map +1 -0
  195. package/dist/state/fold.d.ts +11 -0
  196. package/dist/state/fold.d.ts.map +1 -1
  197. package/dist/state/fold.js +492 -7
  198. package/dist/state/fold.js.map +1 -1
  199. package/dist/state-home.d.ts +28 -0
  200. package/dist/state-home.d.ts.map +1 -0
  201. package/dist/state-home.js +63 -0
  202. package/dist/state-home.js.map +1 -0
  203. package/dist/track.d.ts +133 -8
  204. package/dist/track.d.ts.map +1 -1
  205. package/dist/track.js +767 -28
  206. package/dist/track.js.map +1 -1
  207. package/dist/workspace-id.d.ts.map +1 -1
  208. package/dist/workspace-id.js +5 -0
  209. package/dist/workspace-id.js.map +1 -1
  210. package/dist/write-policy.d.ts +83 -0
  211. package/dist/write-policy.d.ts.map +1 -0
  212. package/dist/write-policy.js +290 -0
  213. package/dist/write-policy.js.map +1 -0
  214. package/package.json +1 -1
  215. package/registry/entries.v1.json +1 -1
  216. package/skills/present-decision/SKILL.md +9 -16
  217. package/skills/present-decision/assets/dossier-template.md +2 -3
  218. package/skills/present-decision/assets/self-audit.md +3 -3
@@ -0,0 +1,2154 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { isOwnerGateTitle, isSettled } from '../model/decision.js';
4
+ import { DomainError } from '../model/item.js';
5
+ import { isValidMeasuredVelocityProvenance, REPORT_STAGES, REPORT_STATUSES, } from '../model/report-status.js';
6
+ import { effectiveOpenBlockersForItem } from './blocker-status.js';
7
+ import { cleanDisplayText, shortDecisionSubject } from './format.js';
8
+ import { deriveItemStageStatus, STAGE_RANK, } from './stage-status.js';
9
+ import { evaluateEtaDeadline, qualifyVelocityEta, } from './velocity-eta.js';
10
+ import { formatBlockingDecisionTodoCause, formatPartialScopeNoDecisionsSentence, formatStrictEmptyRefLabel, MOTIF_CAPTURE_INACTIVE, MOTIF_POLICY_ABSENT, } from './owner-table-strings.js';
11
+ export const OWNER_TABLE_HEADERS = [
12
+ '#',
13
+ 'Statut',
14
+ 'Étape',
15
+ 'ETA (étape cible)',
16
+ 'Ta demande',
17
+ 'Fait',
18
+ 'À faire (qui)',
19
+ 'Décision',
20
+ ];
21
+ export const OWNER_TABLE_NO_DEMANDS_MESSAGE = 'aucune demande owner numérotée dans le journal (.track) — tableau owner refusé ' +
22
+ '(des demandes ou décisions owner ouvertes peuvent exister hors journal ; ' +
23
+ 'enregistre une demande avec `track demand raise --text <text>`, ' +
24
+ 'ou utilise `track report --status-table` pour la vue technique)';
25
+ export const OWNER_TABLE_ALL_ARCHIVED_MESSAGE = 'aucune demande owner active dans le journal (.track) — toutes les demandes numérotées sont archivées, ' +
26
+ 'tableau owner vide refusé';
27
+ export function formatOwnerTableNoJournalMessage(cwd, reason) {
28
+ const detail = reason !== undefined && reason.trim() !== ''
29
+ ? reason.trim()
30
+ : `aucun journal .track trouvé depuis ${cwd} et aucune captation active`;
31
+ return (`REFUSED: dossier non couvert — ${detail} — tableau owner refusé ` +
32
+ `(des demandes ou décisions owner ouvertes peuvent exister hors journal). ` +
33
+ `Passe --track-dir <dossier> (ou TRACK_DIR) vers le journal concerné, ou initialise un journal avec \`track init\`.`);
34
+ }
35
+ const BANNED_STEMS = [
36
+ Buffer.from([0x68, 0x6f, 0x6e, 0x6e, 0xc3, 0xaa, 0x74]).toString('utf8'),
37
+ Buffer.from([0x68, 0x6f, 0x6e, 0x6e, 0x65, 0x74]).toString('utf8'),
38
+ Buffer.from([0x68, 0x6f, 0x6e, 0x65, 0x73, 0x74, 0x6c, 0x79]).toString('utf8'),
39
+ ];
40
+ function resolveOwnerTablePolicy(options, view) {
41
+ const direct = options?.policy ?? view?.policy;
42
+ if (direct !== undefined) {
43
+ return { policy: direct };
44
+ }
45
+ const rawPath = options?.policyPath ??
46
+ view?.policyPath ??
47
+ process.env['TRACK_OWNER_POLICY_FILE'] ??
48
+ process.env['TRACK_OWNER_REPORT_POLICY'];
49
+ if (rawPath === undefined || rawPath.trim() === '') {
50
+ const defaultLocalPolicy = options?.defaultPolicyPath ?? view?.defaultPolicyPath;
51
+ if (defaultLocalPolicy !== undefined &&
52
+ defaultLocalPolicy.trim() !== '' &&
53
+ existsSync(defaultLocalPolicy.trim())) {
54
+ const parsed = JSON.parse(readFileSync(defaultLocalPolicy.trim(), 'utf8'));
55
+ return { policy: parsed };
56
+ }
57
+ const stateLocalPolicy = options?.statePolicyPath ?? view?.statePolicyPath;
58
+ if (stateLocalPolicy !== undefined &&
59
+ stateLocalPolicy.trim() !== '' &&
60
+ existsSync(stateLocalPolicy.trim())) {
61
+ const parsed = JSON.parse(readFileSync(stateLocalPolicy.trim(), 'utf8'));
62
+ return { policy: parsed };
63
+ }
64
+ return {
65
+ notice: 'Private-name gate skipped: no unversioned local policy file configured (set --policy <path> or TRACK_OWNER_POLICY_FILE).',
66
+ };
67
+ }
68
+ const trimmed = rawPath.trim();
69
+ if (!existsSync(trimmed)) {
70
+ return {
71
+ notice: `Private-name gate skipped: local policy file not found at ${trimmed}.`,
72
+ };
73
+ }
74
+ const parsed = JSON.parse(readFileSync(trimmed, 'utf8'));
75
+ return { policy: parsed };
76
+ }
77
+ function sha256Hex(input) {
78
+ return createHash('sha256').update(input, 'utf8').digest('hex');
79
+ }
80
+ function matchesPrivateTermToken(token, policy) {
81
+ if (policy.privateTermHashes === undefined || policy.privateTermHashes.length === 0) {
82
+ return false;
83
+ }
84
+ const nfcLower = token.normalize('NFC').toLowerCase();
85
+ const nfdStripped = token.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase();
86
+ const variants = nfcLower === nfdStripped ? [nfcLower] : [nfcLower, nfdStripped];
87
+ const defaultSalt = policy.salt ?? '';
88
+ for (const entry of policy.privateTermHashes) {
89
+ let salt = defaultSalt;
90
+ let targetHash;
91
+ if (typeof entry === 'string') {
92
+ const colonIdx = entry.lastIndexOf(':');
93
+ if (colonIdx > 0 && /^[0-9a-f]{64}$/iu.test(entry.slice(colonIdx + 1))) {
94
+ salt = entry.slice(0, colonIdx);
95
+ targetHash = entry.slice(colonIdx + 1).toLowerCase();
96
+ }
97
+ else {
98
+ targetHash = entry.toLowerCase();
99
+ }
100
+ }
101
+ else {
102
+ salt = entry.salt ?? defaultSalt;
103
+ targetHash = entry.hash.toLowerCase();
104
+ }
105
+ for (const tok of variants) {
106
+ if (salt !== '') {
107
+ if (sha256Hex(`${salt}:${tok}`) === targetHash || sha256Hex(`${salt}${tok}`) === targetHash) {
108
+ return true;
109
+ }
110
+ }
111
+ else if (sha256Hex(tok) === targetHash) {
112
+ return true;
113
+ }
114
+ }
115
+ }
116
+ return false;
117
+ }
118
+ export const PRIVATE_TERM_MASK_PLACEHOLDER = '[terme masqué]';
119
+ /**
120
+ * Replace any token matching `policy.privateTermHashes` with `[terme masqué]` (spec §7.5, plan/07 Lot 4).
121
+ * Uses the exact same normalization & salted SHA-256 matching rules as `matchesPrivateTermPolicy`.
122
+ */
123
+ export function maskPrivateTermsWithPolicy(text, policy) {
124
+ if (policy?.privateTermHashes === undefined || policy.privateTermHashes.length === 0) {
125
+ return { text, masked: false, count: 0 };
126
+ }
127
+ let count = 0;
128
+ const out = text.replace(/[\p{L}\p{N}_-]+/gu, (compound) => {
129
+ if (matchesPrivateTermToken(compound, policy)) {
130
+ count += 1;
131
+ return PRIVATE_TERM_MASK_PLACEHOLDER;
132
+ }
133
+ return compound.replace(/[\p{L}\p{N}]+/gu, (part) => {
134
+ if (matchesPrivateTermToken(part, policy)) {
135
+ count += 1;
136
+ return PRIVATE_TERM_MASK_PLACEHOLDER;
137
+ }
138
+ return part;
139
+ });
140
+ });
141
+ return { text: out, masked: count > 0, count };
142
+ }
143
+ function matchesPrivateTermPolicy(text, policy) {
144
+ if (policy?.privateTermHashes === undefined || policy.privateTermHashes.length === 0) {
145
+ return false;
146
+ }
147
+ const nfcLower = text.normalize('NFC').toLowerCase();
148
+ const nfdStripped = text.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase();
149
+ const tokens = new Set();
150
+ for (const variant of [nfcLower, nfdStripped]) {
151
+ for (const tok of variant.split(/[^\p{L}\p{N}_-]+/u)) {
152
+ if (tok.length > 0)
153
+ tokens.add(tok);
154
+ }
155
+ for (const tok of variant.split(/[^\p{L}\p{N}]+/u)) {
156
+ if (tok.length > 0)
157
+ tokens.add(tok);
158
+ }
159
+ }
160
+ if (tokens.size === 0)
161
+ return false;
162
+ const defaultSalt = policy.salt ?? '';
163
+ for (const entry of policy.privateTermHashes) {
164
+ let salt = defaultSalt;
165
+ let targetHash;
166
+ if (typeof entry === 'string') {
167
+ const colonIdx = entry.lastIndexOf(':');
168
+ if (colonIdx > 0 && /^[0-9a-f]{64}$/iu.test(entry.slice(colonIdx + 1))) {
169
+ salt = entry.slice(0, colonIdx);
170
+ targetHash = entry.slice(colonIdx + 1).toLowerCase();
171
+ }
172
+ else {
173
+ targetHash = entry.toLowerCase();
174
+ }
175
+ }
176
+ else {
177
+ salt = entry.salt ?? defaultSalt;
178
+ targetHash = entry.hash.toLowerCase();
179
+ }
180
+ for (const tok of tokens) {
181
+ if (salt !== '') {
182
+ if (sha256Hex(`${salt}:${tok}`) === targetHash || sha256Hex(`${salt}${tok}`) === targetHash) {
183
+ return true;
184
+ }
185
+ }
186
+ else if (sha256Hex(tok) === targetHash) {
187
+ return true;
188
+ }
189
+ }
190
+ }
191
+ return false;
192
+ }
193
+ const COMMIT_HASH_RE = /\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/iu;
194
+ const ULID_RE = /\b[0-9A-HJKMNP-TV-Z]{26}\b/u;
195
+ const JARGON_RE = /\b(?:worktrees?|subagents?|bwrap|tmux|pty-host|events\.jsonl|aggregateId|specStatus|realizedCommit|lanes?|shards?)\b|(?:^|[^\p{L}\p{N}])claude:[a-z0-9_.:-]+/iu;
196
+ const WP_INTERNAL_RE = /\bWP-?\d+\b/u;
197
+ const PRIVATE_PATH_RE = new RegExp(String.raw `(?:^|[\s(])/(?:home|Users|tmp|var/folders)/[^\s)]+`, 'iu');
198
+ const PRIVATE_DIGEST_RE = /\bsha256[:=][0-9a-f]{8,}\b/iu;
199
+ export function formatOwnerStatusCell(row) {
200
+ if (row.kind === 'demand-title' || row.status === undefined) {
201
+ return '—';
202
+ }
203
+ switch (row.status) {
204
+ case 'on-track':
205
+ return '🔵 sur la voie';
206
+ case 'waiting':
207
+ return '🟡 en attente';
208
+ case 'unforeseen':
209
+ return '🟠 dérive';
210
+ case 'blocked':
211
+ return '🔴 bloqué';
212
+ case 'not-started':
213
+ return row.pausedByOwner === true ? '⚪ en pause' : '⚪ pas commencé';
214
+ case 'done':
215
+ return '✅ fait';
216
+ case 'withdrawn':
217
+ return '⚫ retiré';
218
+ case 'not-qualified':
219
+ return '— sans témoin';
220
+ }
221
+ }
222
+ export function formatOwnerStageCell(row) {
223
+ if (row.stage === undefined || row.stage === '—') {
224
+ return '—';
225
+ }
226
+ if (row.requestedStage !== undefined && row.requestedStage === row.stage) {
227
+ return `${row.stage} (demandée)`;
228
+ }
229
+ return row.stage;
230
+ }
231
+ export function formatOwnerEtaEntry(eta) {
232
+ const target = eta.targetLabel !== undefined && eta.targetLabel.trim() !== ''
233
+ ? `${eta.targetStage} (${eta.targetLabel.trim()})`
234
+ : eta.targetStage;
235
+ const sourceText = eta.source === 'measured'
236
+ ? 'mesuré'
237
+ : eta.source === 'committed'
238
+ ? `engagé : ${eta.by ?? ''}`
239
+ : 'inconnu';
240
+ if (eta.slip !== undefined) {
241
+ if (eta.when === '—' || eta.when === eta.slip.initialWhen) {
242
+ return `${target} → ${eta.when} (dépassé : ${eta.slip.initialWhen}, ${sourceText})`;
243
+ }
244
+ return `${target} → ${eta.when} (${sourceText}, glissement depuis ${eta.slip.initialWhen})`;
245
+ }
246
+ return `${target} → ${eta.when} (${sourceText})`;
247
+ }
248
+ export function formatOwnerEtaCell(etas) {
249
+ if (etas.length === 0)
250
+ return '—';
251
+ return etas.map(formatOwnerEtaEntry).join(' · ');
252
+ }
253
+ export function formatOwnerDecisionCell(row) {
254
+ if (row.decisionRefs.length === 0)
255
+ return '—';
256
+ if (row.status === 'withdrawn') {
257
+ return row.decisionRefs.map((ref) => `${ref} (décision sans objet)`).join(' · ');
258
+ }
259
+ const sansObjetSet = new Set(row.sansObjetDecisionRefs ?? []);
260
+ const blockingSet = row.blockingDecisionRefs !== undefined
261
+ ? new Set(row.blockingDecisionRefs)
262
+ : row.decisionBlocking === true
263
+ ? new Set(row.decisionRefs)
264
+ : new Set();
265
+ return row.decisionRefs
266
+ .map((ref) => {
267
+ if (sansObjetSet.has(ref))
268
+ return `${ref} (décision sans objet)`;
269
+ return blockingSet.has(ref) ? `🚩 ${ref} bloquante` : ref;
270
+ })
271
+ .join(' · ');
272
+ }
273
+ function checkTextGates(text, context, violations, policy) {
274
+ const loc = {
275
+ ...(context.rowNum !== undefined ? { rowNum: context.rowNum } : {}),
276
+ ...(context.rowId !== undefined ? { rowId: context.rowId } : {}),
277
+ ...(context.cell !== undefined ? { cell: context.cell } : {}),
278
+ ...(context.decisionRef !== undefined ? { decisionRef: context.decisionRef } : {}),
279
+ ...(context.decisionId !== undefined ? { decisionId: context.decisionId } : {}),
280
+ };
281
+ if (COMMIT_HASH_RE.test(text)) {
282
+ violations.push({
283
+ code: 'internal-jargon',
284
+ check: 'text.commit-hash',
285
+ ...loc,
286
+ message: `${context.field} contains a commit hash`,
287
+ });
288
+ }
289
+ if (ULID_RE.test(text)) {
290
+ violations.push({
291
+ code: 'internal-jargon',
292
+ check: 'text.internal-id',
293
+ ...loc,
294
+ message: `${context.field} contains an internal ULID`,
295
+ });
296
+ }
297
+ const checkWpToken = context.field.includes('"Fait"') || context.field.includes('"À faire (qui)"');
298
+ if (JARGON_RE.test(text) || (checkWpToken && WP_INTERNAL_RE.test(text))) {
299
+ violations.push({
300
+ code: 'internal-jargon',
301
+ check: 'text.jargon',
302
+ ...loc,
303
+ message: `${context.field} contains internal jargon`,
304
+ });
305
+ }
306
+ const nfcLower = text.normalize('NFC').toLowerCase();
307
+ const nfdStripped = text.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase();
308
+ const hasBannedStem = BANNED_STEMS.some((stem) => nfcLower.includes(stem) || nfdStripped.includes(stem));
309
+ const hasPrivateTerm = matchesPrivateTermPolicy(text, policy);
310
+ if (hasBannedStem || hasPrivateTerm || PRIVATE_PATH_RE.test(text) || PRIVATE_DIGEST_RE.test(text)) {
311
+ violations.push({
312
+ code: 'banned-word',
313
+ check: 'text.reserved',
314
+ ...loc,
315
+ message: `${context.field} contains a banned word, private term, private path, or private digest`,
316
+ });
317
+ }
318
+ }
319
+ /** Check whether a label or arbitrary display string trips any text gate (for label fallback). */
320
+ export function hasTextGateViolation(text, options) {
321
+ const { policy } = resolveOwnerTablePolicy(options);
322
+ const probe = [];
323
+ checkTextGates(text, { field: 'label' }, probe, policy);
324
+ return probe.length > 0;
325
+ }
326
+ function isBlankOrDash(value) {
327
+ if (value === undefined)
328
+ return true;
329
+ const trimmed = value.trim();
330
+ return trimmed === '' || trimmed === '—' || trimmed === '-';
331
+ }
332
+ function isDecisionIncomplete(d) {
333
+ const validRecommendedLetter = !isBlankOrDash(d.recommendedLetter) && d.options.some((o) => o.letter === d.recommendedLetter);
334
+ return (isBlankOrDash(d.question) ||
335
+ d.options.length < 2 ||
336
+ !validRecommendedLetter ||
337
+ isBlankOrDash(d.recommendation));
338
+ }
339
+ function strictDecisionLabel(d) {
340
+ if (d.ref.trim() !== '')
341
+ return d.ref.trim();
342
+ if (d.kind === 'owner-gate')
343
+ return formatStrictEmptyRefLabel('owner-gate');
344
+ return formatStrictEmptyRefLabel('decision', !isDecisionIncomplete(d));
345
+ }
346
+ function parseDecisionRefNumber(ref) {
347
+ const m = /^D(\d+)$/u.exec(ref.trim());
348
+ return m !== null ? Number(m[1]) : Number.MAX_SAFE_INTEGER;
349
+ }
350
+ function auditRowEtaEntries(row, violations, policy, requireMissedSlipStatus) {
351
+ if (row.etas.length > 2) {
352
+ violations.push({
353
+ code: 'invalid-eta',
354
+ check: 'eta.too-many',
355
+ rowNum: row.num,
356
+ rowId: row.id,
357
+ cell: 'eta',
358
+ message: `row #${row.num} carries ${row.etas.length} ETAs (maximum 2 allowed)`,
359
+ });
360
+ }
361
+ for (const eta of row.etas) {
362
+ if (!REPORT_STAGES.includes(eta.targetStage)) {
363
+ violations.push({
364
+ code: 'invalid-eta',
365
+ check: 'eta.invalid-stage',
366
+ rowNum: row.num,
367
+ rowId: row.id,
368
+ cell: 'eta',
369
+ message: `row #${row.num} has an ETA without a valid target stage`,
370
+ });
371
+ }
372
+ if (eta.source !== 'measured' && eta.source !== 'committed' && eta.source !== 'unknown') {
373
+ violations.push({
374
+ code: 'invalid-eta',
375
+ check: 'eta.invalid-source',
376
+ rowNum: row.num,
377
+ rowId: row.id,
378
+ cell: 'eta',
379
+ message: `row #${row.num} has an ETA without a valid source (measured|committed|unknown)`,
380
+ });
381
+ }
382
+ if (eta.source === 'committed' && isBlankOrDash(eta.by)) {
383
+ violations.push({
384
+ code: 'invalid-eta',
385
+ check: 'eta.committed-no-by',
386
+ rowNum: row.num,
387
+ rowId: row.id,
388
+ cell: 'eta',
389
+ message: `row #${row.num} has a committed ETA without naming who committed ("by")`,
390
+ });
391
+ }
392
+ if (eta.source === 'unknown' && !isBlankOrDash(eta.when)) {
393
+ violations.push({
394
+ code: 'invalid-eta',
395
+ check: 'eta.unknown-with-date',
396
+ rowNum: row.num,
397
+ rowId: row.id,
398
+ cell: 'eta',
399
+ message: `row #${row.num} has an unknown ETA with a target date (must be "—")`,
400
+ });
401
+ }
402
+ if (eta.source === 'measured') {
403
+ if (!isValidMeasuredVelocityProvenance(eta.measured) ||
404
+ STAGE_RANK[eta.targetStage] < STAGE_RANK['dev']) {
405
+ violations.push({
406
+ code: 'invalid-eta',
407
+ check: 'eta.measured-unproven',
408
+ rowNum: row.num,
409
+ rowId: row.id,
410
+ cell: 'eta',
411
+ message: `row #${row.num} has a measured ETA without qualified velocity provenance (sampleCount > 0 and matching digests)`,
412
+ });
413
+ }
414
+ }
415
+ if ((eta.source === 'measured' || eta.source === 'committed') && isBlankOrDash(eta.when) && eta.slip === undefined) {
416
+ violations.push({
417
+ code: 'invalid-eta',
418
+ check: 'eta.missing-date',
419
+ rowNum: row.num,
420
+ rowId: row.id,
421
+ cell: 'eta',
422
+ message: `row #${row.num} has a ${eta.source} ETA without a target date`,
423
+ });
424
+ }
425
+ if (requireMissedSlipStatus &&
426
+ eta.slip !== undefined &&
427
+ row.pausedByOwner !== true &&
428
+ row.status !== 'unforeseen' &&
429
+ row.status !== 'blocked' &&
430
+ row.status !== 'withdrawn') {
431
+ violations.push({
432
+ code: 'invalid-eta',
433
+ check: 'eta.missed-status',
434
+ rowNum: row.num,
435
+ rowId: row.id,
436
+ cell: 'eta',
437
+ message: `row #${row.num} has a missed ETA and must be 🟠 dérive (or 🔴 bloqué)`,
438
+ });
439
+ }
440
+ if (eta.by !== undefined) {
441
+ checkTextGates(eta.by, { rowNum: row.num, rowId: row.id, cell: 'eta', field: `row #${row.num} ETA "by"` }, violations, policy);
442
+ }
443
+ if (eta.targetLabel !== undefined) {
444
+ checkTextGates(eta.targetLabel, { rowNum: row.num, rowId: row.id, cell: 'eta', field: `row #${row.num} ETA "targetLabel"` }, violations, policy);
445
+ }
446
+ checkTextGates(eta.when, { rowNum: row.num, rowId: row.id, cell: 'eta', field: `row #${row.num} ETA "when"` }, violations, policy);
447
+ if (eta.slip?.initialWhen !== undefined) {
448
+ checkTextGates(eta.slip.initialWhen, { rowNum: row.num, rowId: row.id, cell: 'eta', field: `row #${row.num} ETA slip "initialWhen"` }, violations, policy);
449
+ }
450
+ if (eta.slip?.reason !== undefined) {
451
+ checkTextGates(eta.slip.reason, { rowNum: row.num, rowId: row.id, cell: 'eta', field: `row #${row.num} ETA slip "reason"` }, violations, policy);
452
+ }
453
+ }
454
+ }
455
+ /**
456
+ * Blocking gates on the owner table (Owner Decisions 14/11 & 15/11).
457
+ * The render refuses (`ok === false`) on any violation.
458
+ */
459
+ export function auditOwnerTable(view, options) {
460
+ const violations = [];
461
+ const { policy, notice } = resolveOwnerTablePolicy(options, view);
462
+ const archivedSet = new Set(view.archivedNumbers);
463
+ const seenNums = new Set();
464
+ const hasNumberedRow = view.rows.some((row) => Number.isInteger(row.num) && row.num >= 1);
465
+ if (view.registeredNumbers.length === 0 && !hasNumberedRow) {
466
+ violations.push({
467
+ code: 'no-owner-demands',
468
+ check: 'demands.none',
469
+ message: OWNER_TABLE_NO_DEMANDS_MESSAGE,
470
+ });
471
+ }
472
+ else if (view.rows.length === 0) {
473
+ violations.push({
474
+ code: 'no-owner-demands',
475
+ check: 'demands.all-archived',
476
+ message: OWNER_TABLE_ALL_ARCHIVED_MESSAGE,
477
+ });
478
+ }
479
+ let prevTopLevelNum = 0;
480
+ let activeTitleRow;
481
+ let lotCountForActiveTitle = 0;
482
+ for (const row of view.rows) {
483
+ const rowKind = row.kind ?? 'single';
484
+ if (!Number.isInteger(row.num) || row.num < 1) {
485
+ violations.push({
486
+ code: 'missing-row',
487
+ check: 'row.unnumbered',
488
+ rowNum: row.num,
489
+ rowId: row.id,
490
+ cell: 'request',
491
+ message: `row #${String(row.num)} must have a positive integer request number`,
492
+ });
493
+ }
494
+ if (rowKind === 'lot') {
495
+ if (activeTitleRow === undefined ||
496
+ row.parentDemandId === undefined ||
497
+ row.parentDemandId !== activeTitleRow.id ||
498
+ row.num !== activeTitleRow.num) {
499
+ violations.push({
500
+ code: 'missing-row',
501
+ check: 'row.lot-orphan',
502
+ rowNum: row.num,
503
+ rowId: row.id,
504
+ cell: 'request',
505
+ message: `lot row #${row.num} (${row.id}) must immediately follow its parent demand-title row`,
506
+ });
507
+ }
508
+ else {
509
+ lotCountForActiveTitle++;
510
+ }
511
+ }
512
+ else {
513
+ if (activeTitleRow !== undefined && lotCountForActiveTitle < 2) {
514
+ violations.push({
515
+ code: 'missing-row',
516
+ check: 'row.title-few-lots',
517
+ rowNum: activeTitleRow.num,
518
+ rowId: activeTitleRow.id,
519
+ cell: 'request',
520
+ message: `demand-title row #${activeTitleRow.num} must be followed by at least 2 lot rows`,
521
+ });
522
+ }
523
+ if (seenNums.has(row.num)) {
524
+ violations.push({
525
+ code: 'missing-row',
526
+ check: 'registry.duplicate',
527
+ rowNum: row.num,
528
+ rowId: row.id,
529
+ cell: 'request',
530
+ message: `duplicate request number #${row.num}`,
531
+ });
532
+ }
533
+ if (prevTopLevelNum > 0 && row.num <= prevTopLevelNum) {
534
+ violations.push({
535
+ code: 'missing-row',
536
+ check: 'row.order',
537
+ rowNum: row.num,
538
+ rowId: row.id,
539
+ cell: 'request',
540
+ message: `rows must be in strictly ascending # order`,
541
+ });
542
+ }
543
+ seenNums.add(row.num);
544
+ prevTopLevelNum = row.num;
545
+ if (rowKind === 'demand-title') {
546
+ activeTitleRow = row;
547
+ lotCountForActiveTitle = 0;
548
+ }
549
+ else {
550
+ activeTitleRow = undefined;
551
+ lotCountForActiveTitle = 0;
552
+ }
553
+ }
554
+ }
555
+ if (activeTitleRow !== undefined && lotCountForActiveTitle < 2) {
556
+ violations.push({
557
+ code: 'missing-row',
558
+ check: 'row.title-few-lots',
559
+ rowNum: activeTitleRow.num,
560
+ rowId: activeTitleRow.id,
561
+ cell: 'request',
562
+ message: `demand-title row #${activeTitleRow.num} must be followed by at least 2 lot rows`,
563
+ });
564
+ }
565
+ for (const registered of view.registeredNumbers) {
566
+ if (!seenNums.has(registered) && !archivedSet.has(registered)) {
567
+ violations.push({
568
+ code: 'missing-row',
569
+ check: 'registry.missing',
570
+ rowNum: registered,
571
+ message: `request #${registered} is missing without an owner archive event`,
572
+ });
573
+ }
574
+ }
575
+ const allKnownNums = new Set([...seenNums, ...archivedSet]);
576
+ if (allKnownNums.size > 0) {
577
+ const maxNum = Math.max(...allKnownNums);
578
+ for (let n = 1; n <= maxNum; n++) {
579
+ if (!allKnownNums.has(n)) {
580
+ violations.push({
581
+ code: 'missing-row',
582
+ check: 'registry.hole',
583
+ rowNum: n,
584
+ message: `request #${n} is missing from 1..${maxNum} without an owner archive event`,
585
+ });
586
+ }
587
+ }
588
+ }
589
+ const decisionById = new Map();
590
+ const decisionMap = new Map();
591
+ for (const d of view.decisions) {
592
+ decisionById.set(d.id, d);
593
+ if (d.ref.trim() !== '') {
594
+ if (decisionMap.has(d.ref)) {
595
+ violations.push({
596
+ code: 'invalid-decision',
597
+ check: 'decision.duplicate-ref',
598
+ decisionRef: d.ref,
599
+ decisionId: d.id,
600
+ message: `duplicate decision ref ${d.ref}`,
601
+ });
602
+ }
603
+ decisionMap.set(d.ref, d);
604
+ }
605
+ }
606
+ const referencedDecisionIds = new Set();
607
+ const referencedDecisions = new Set();
608
+ for (const row of view.rows) {
609
+ const rowKind = row.kind ?? 'single';
610
+ if (isBlankOrDash(row.request)) {
611
+ violations.push({
612
+ code: 'missing-row',
613
+ check: 'row.request-missing',
614
+ rowNum: row.num,
615
+ rowId: row.id,
616
+ cell: 'request',
617
+ message: `row #${row.num} is missing its owner request text`,
618
+ });
619
+ }
620
+ else if (rowKind === 'lot' && !/^↳ lot \d+ — \S/u.test(row.request)) {
621
+ violations.push({
622
+ code: 'missing-row',
623
+ check: 'row.lot-format',
624
+ rowNum: row.num,
625
+ rowId: row.id,
626
+ cell: 'request',
627
+ message: `lot row #${row.num} must be formatted as "↳ lot N — <title>"`,
628
+ });
629
+ }
630
+ if (rowKind === 'demand-title') {
631
+ if (row.status !== undefined) {
632
+ violations.push({
633
+ code: 'missing-witness',
634
+ check: 'row.title-field',
635
+ rowNum: row.num,
636
+ rowId: row.id,
637
+ cell: 'status',
638
+ message: `demand-title row #${row.num} must not carry a status (got "${String(row.status)}")`,
639
+ });
640
+ }
641
+ if (row.stage !== undefined) {
642
+ violations.push({
643
+ code: 'missing-witness',
644
+ check: 'row.title-field',
645
+ rowNum: row.num,
646
+ rowId: row.id,
647
+ cell: 'stage',
648
+ message: `demand-title row #${row.num} must not carry a stage (got "${String(row.stage)}")`,
649
+ });
650
+ }
651
+ if (row.done.trim() !== '—') {
652
+ violations.push({
653
+ code: 'missing-witness',
654
+ check: 'row.title-field',
655
+ rowNum: row.num,
656
+ rowId: row.id,
657
+ cell: 'done',
658
+ message: `demand-title row #${row.num} must have "—" in "Fait"`,
659
+ });
660
+ }
661
+ if (row.todo.trim() !== '—') {
662
+ violations.push({
663
+ code: 'missing-witness',
664
+ check: 'row.title-field',
665
+ rowNum: row.num,
666
+ rowId: row.id,
667
+ cell: 'todo',
668
+ message: `demand-title row #${row.num} must have "—" in "À faire (qui)"`,
669
+ });
670
+ }
671
+ if (row.pausedByOwner === true) {
672
+ violations.push({
673
+ code: 'missing-witness',
674
+ check: 'row.title-field',
675
+ rowNum: row.num,
676
+ rowId: row.id,
677
+ cell: 'status',
678
+ message: `demand-title row #${row.num} must not carry pausedByOwner`,
679
+ });
680
+ }
681
+ if (row.hasWitness === true) {
682
+ violations.push({
683
+ code: 'missing-witness',
684
+ check: 'row.title-field',
685
+ rowNum: row.num,
686
+ rowId: row.id,
687
+ cell: 'done',
688
+ message: `demand-title row #${row.num} must not carry hasWitness`,
689
+ });
690
+ }
691
+ const expectedTitleBlocking = (row.blockingDecisionIds?.length ?? 0) > 0 || (row.blockingDecisionRefs?.length ?? 0) > 0
692
+ ? true
693
+ : undefined;
694
+ const hasUnlistedBlockingId = row.decisionIds !== undefined &&
695
+ (row.blockingDecisionIds ?? []).some((id) => !row.decisionIds.includes(id));
696
+ const hasUnlistedBlockingRef = (row.blockingDecisionRefs ?? []).some((ref) => !row.decisionRefs.includes(ref));
697
+ if (row.decisionBlocking !== expectedTitleBlocking || hasUnlistedBlockingId || hasUnlistedBlockingRef) {
698
+ violations.push({
699
+ code: 'invalid-decision',
700
+ check: 'row.title-blocking-inconsistent',
701
+ rowNum: row.num,
702
+ rowId: row.id,
703
+ cell: 'decision',
704
+ message: `demand-title row #${row.num} has inconsistent decisionBlocking / blockingDecisionRefs`,
705
+ });
706
+ }
707
+ auditRowEtaEntries(row, violations, policy, false);
708
+ }
709
+ else {
710
+ if (row.status === undefined || !REPORT_STATUSES.includes(row.status)) {
711
+ violations.push({
712
+ code: 'missing-witness',
713
+ check: 'row.status-invalid',
714
+ rowNum: row.num,
715
+ rowId: row.id,
716
+ cell: 'status',
717
+ message: `row #${row.num} has invalid status "${String(row.status)}"`,
718
+ });
719
+ }
720
+ if (row.stage !== undefined && !REPORT_STAGES.includes(row.stage)) {
721
+ violations.push({
722
+ code: 'missing-witness',
723
+ check: 'row.stage-invalid',
724
+ rowNum: row.num,
725
+ rowId: row.id,
726
+ cell: 'stage',
727
+ message: `row #${row.num} has invalid stage "${String(row.stage)}"`,
728
+ });
729
+ }
730
+ // Gate: 🔴 without a cause in À faire
731
+ if (row.status === 'blocked') {
732
+ if (isBlankOrDash(row.todo)) {
733
+ violations.push({
734
+ code: 'blocked-without-cause',
735
+ check: 'row.blocked-no-cause',
736
+ rowNum: row.num,
737
+ rowId: row.id,
738
+ cell: 'todo',
739
+ message: `row #${row.num} is 🔴 bloqué without a cause in "À faire (qui)"`,
740
+ });
741
+ }
742
+ }
743
+ // Gate: blocking decision must make row 🔴 bloqué with "bloqué par ..." in À faire
744
+ if (row.decisionBlocking === true) {
745
+ if ((row.decisionIds?.length ?? 0) === 0 && row.decisionRefs.length === 0) {
746
+ violations.push({
747
+ code: 'invalid-decision',
748
+ check: 'row.blocking-no-ref',
749
+ rowNum: row.num,
750
+ rowId: row.id,
751
+ cell: 'decision',
752
+ message: `row #${row.num} is marked decisionBlocking without any D#`,
753
+ });
754
+ }
755
+ if (row.status !== 'blocked') {
756
+ violations.push({
757
+ code: 'blocked-without-cause',
758
+ check: 'row.blocking-not-blocked',
759
+ rowNum: row.num,
760
+ rowId: row.id,
761
+ cell: 'status',
762
+ message: `row #${row.num} has a blocking decision (🚩) and must be 🔴 bloqué`,
763
+ });
764
+ }
765
+ if (!/bloqué par (?:D\d+|OWNER GATE|décision à (?:instruire|numéroter))/u.test(row.todo)) {
766
+ violations.push({
767
+ code: 'blocked-without-cause',
768
+ check: 'row.blocking-no-cause',
769
+ rowNum: row.num,
770
+ rowId: row.id,
771
+ cell: 'todo',
772
+ message: `row #${row.num} has a blocking decision (🚩) and must state "bloqué par D#" in "À faire (qui)"`,
773
+ });
774
+ }
775
+ }
776
+ // Gate: ✅ or 🔵 without a witness; merged is never ✅ fait; stage 'done' requires ✅ fait; ⚫ without reason
777
+ if (row.status !== 'done' && row.status !== 'withdrawn' && row.stage === 'done') {
778
+ violations.push({
779
+ code: 'missing-witness',
780
+ check: 'row.stage-done-mismatch',
781
+ rowNum: row.num,
782
+ rowId: row.id,
783
+ cell: 'stage',
784
+ message: `row #${row.num} cannot have stage "done" while status is "${String(row.status)}" (stage "done" requires ✅ fait)`,
785
+ });
786
+ }
787
+ if (row.status === 'done') {
788
+ if (row.stage !== 'done') {
789
+ violations.push({
790
+ code: 'missing-witness',
791
+ check: 'status.unproven',
792
+ rowNum: row.num,
793
+ rowId: row.id,
794
+ cell: 'stage',
795
+ message: `row #${row.num} cannot be ✅ fait at stage "${String(row.stage ?? '—')}" (requires stage "done")`,
796
+ });
797
+ }
798
+ if (row.hasWitness !== true || isBlankOrDash(row.done)) {
799
+ violations.push({
800
+ code: 'missing-witness',
801
+ check: 'status.unproven',
802
+ rowNum: row.num,
803
+ rowId: row.id,
804
+ cell: 'done',
805
+ message: `row #${row.num} is ✅ fait without a recorded witness in "Fait"`,
806
+ });
807
+ }
808
+ }
809
+ else if (row.status === 'on-track') {
810
+ if (row.stage === undefined || row.hasWitness !== true || isBlankOrDash(row.done)) {
811
+ violations.push({
812
+ code: 'missing-witness',
813
+ check: 'status.unproven',
814
+ rowNum: row.num,
815
+ rowId: row.id,
816
+ cell: 'done',
817
+ message: `row #${row.num} is 🔵 sur la voie without a conformity witness at stage "${String(row.stage ?? '—')}"`,
818
+ });
819
+ }
820
+ }
821
+ else if (row.status === 'withdrawn') {
822
+ if (isBlankOrDash(row.done)) {
823
+ violations.push({
824
+ code: 'missing-witness',
825
+ check: 'row.withdrawn-no-reason',
826
+ rowNum: row.num,
827
+ rowId: row.id,
828
+ cell: 'done',
829
+ message: `row #${row.num} is ⚫ retiré without a reason in "Fait"`,
830
+ });
831
+ }
832
+ if ((row.blockingDecisionIds?.length ?? 0) > 0 || (row.blockingDecisionRefs?.length ?? 0) > 0) {
833
+ violations.push({
834
+ code: 'invalid-decision',
835
+ check: 'row.withdrawn-blocking',
836
+ rowNum: row.num,
837
+ rowId: row.id,
838
+ cell: 'decision',
839
+ message: `row #${row.num} is ⚫ retiré and must not carry blocking decisions`,
840
+ });
841
+ }
842
+ }
843
+ // Gate: ETA without a target stage or a source (up to 2 ETAs per row)
844
+ if ((row.status === 'done' || row.status === 'withdrawn') && row.etas.length > 0) {
845
+ violations.push({
846
+ code: 'invalid-eta',
847
+ check: 'eta.terminal-active',
848
+ rowNum: row.num,
849
+ rowId: row.id,
850
+ cell: 'eta',
851
+ message: `row #${row.num} is terminal (${row.status}) and must not carry active ETAs`,
852
+ });
853
+ }
854
+ if (row.etas.length === 0 && row.status !== 'done' && row.status !== 'withdrawn') {
855
+ violations.push({
856
+ code: 'invalid-eta',
857
+ check: 'eta.missing',
858
+ rowNum: row.num,
859
+ rowId: row.id,
860
+ cell: 'eta',
861
+ message: `row #${row.num} is missing an ETA entry (target stage + source required)`,
862
+ });
863
+ }
864
+ auditRowEtaEntries(row, violations, policy, true);
865
+ }
866
+ // Gate: row pointing to unlisted decisions or inconsistent sansObjet / withdrawn decision links (by identity + explicit refs)
867
+ const emittedRowDecisionKeys = new Set();
868
+ const rowSansObjetIdSet = new Set(row.sansObjetDecisionIds ?? []);
869
+ const rowBlockingIdSet = new Set(row.blockingDecisionIds ?? []);
870
+ if (row.decisionIds !== undefined) {
871
+ for (const dId of rowSansObjetIdSet) {
872
+ const dec = decisionById.get(dId);
873
+ const dLabel = dec !== undefined ? strictDecisionLabel(dec) : 'décision';
874
+ if (!row.decisionIds.includes(dId)) {
875
+ violations.push({
876
+ code: 'invalid-decision',
877
+ check: 'decision.sans-objet-inconsistent',
878
+ rowNum: row.num,
879
+ rowId: row.id,
880
+ cell: 'decision',
881
+ ...(dec?.ref ? { decisionRef: dec.ref } : {}),
882
+ decisionId: dId,
883
+ message: `row #${row.num} lists ${dLabel} in sansObjetDecisionIds without including it in decisionIds`,
884
+ });
885
+ }
886
+ if (rowBlockingIdSet.has(dId)) {
887
+ emittedRowDecisionKeys.add(`decision.sans-objet-blocking:${dId}`);
888
+ violations.push({
889
+ code: 'invalid-decision',
890
+ check: 'decision.sans-objet-blocking',
891
+ rowNum: row.num,
892
+ rowId: row.id,
893
+ cell: 'decision',
894
+ ...(dec?.ref ? { decisionRef: dec.ref } : {}),
895
+ decisionId: dId,
896
+ message: `row #${row.num} cannot mark decision ${dLabel} as both sansObjet and blocking`,
897
+ });
898
+ }
899
+ }
900
+ for (const dId of row.decisionIds) {
901
+ referencedDecisionIds.add(dId);
902
+ const dec = decisionById.get(dId);
903
+ if (dec === undefined) {
904
+ violations.push({
905
+ code: 'invalid-decision',
906
+ check: 'decision.unlisted',
907
+ rowNum: row.num,
908
+ rowId: row.id,
909
+ cell: 'decision',
910
+ decisionId: dId,
911
+ message: `row #${row.num} points to unlisted decision`,
912
+ });
913
+ }
914
+ else {
915
+ if (dec.ref !== '')
916
+ referencedDecisions.add(dec.ref);
917
+ const dLabel = strictDecisionLabel(dec);
918
+ if (row.status === 'withdrawn' && dec.sansObjet !== true) {
919
+ emittedRowDecisionKeys.add(`withdrawn-not-sans-objet:${dId}`);
920
+ violations.push({
921
+ code: 'invalid-decision',
922
+ check: 'decision.sans-objet-inconsistent',
923
+ rowNum: row.num,
924
+ rowId: row.id,
925
+ cell: 'decision',
926
+ ...(dec.ref !== '' ? { decisionRef: dec.ref } : {}),
927
+ decisionId: dec.id,
928
+ message: `row #${row.num} is ⚫ retiré and references decision ${dLabel} which is not marked sansObjet`,
929
+ });
930
+ }
931
+ if (rowSansObjetIdSet.has(dId) && dec.sansObjet !== true) {
932
+ emittedRowDecisionKeys.add(`row-marks-non-sans-objet:${dId}`);
933
+ violations.push({
934
+ code: 'invalid-decision',
935
+ check: 'decision.sans-objet-inconsistent',
936
+ rowNum: row.num,
937
+ rowId: row.id,
938
+ cell: 'decision',
939
+ ...(dec.ref !== '' ? { decisionRef: dec.ref } : {}),
940
+ decisionId: dec.id,
941
+ message: `row #${row.num} marks decision ${dLabel} in sansObjetDecisionRefs, but decision ${dLabel} is not sansObjet`,
942
+ });
943
+ }
944
+ if (dec.sansObjet === true && !rowSansObjetIdSet.has(dId)) {
945
+ emittedRowDecisionKeys.add(`missing-sans-objet-mark:${dId}`);
946
+ violations.push({
947
+ code: 'invalid-decision',
948
+ check: 'decision.sans-objet-inconsistent',
949
+ rowNum: row.num,
950
+ rowId: row.id,
951
+ cell: 'decision',
952
+ ...(dec.ref !== '' ? { decisionRef: dec.ref } : {}),
953
+ decisionId: dec.id,
954
+ message: `row #${row.num} references sans-objet decision ${dLabel} without listing it in sansObjetDecisionRefs`,
955
+ });
956
+ }
957
+ }
958
+ }
959
+ }
960
+ const rowSansObjetSet = new Set(row.sansObjetDecisionRefs ?? []);
961
+ for (const ref of rowSansObjetSet) {
962
+ if (!row.decisionRefs.includes(ref)) {
963
+ violations.push({
964
+ code: 'invalid-decision',
965
+ check: 'decision.sans-objet-inconsistent',
966
+ rowNum: row.num,
967
+ rowId: row.id,
968
+ cell: 'decision',
969
+ decisionRef: ref,
970
+ message: `row #${row.num} lists ${ref} in sansObjetDecisionRefs without including it in decisionRefs`,
971
+ });
972
+ }
973
+ if ((row.blockingDecisionRefs ?? []).includes(ref)) {
974
+ const dec = decisionMap.get(ref);
975
+ if (dec === undefined || !emittedRowDecisionKeys.has(`decision.sans-objet-blocking:${dec.id}`)) {
976
+ violations.push({
977
+ code: 'invalid-decision',
978
+ check: 'decision.sans-objet-blocking',
979
+ rowNum: row.num,
980
+ rowId: row.id,
981
+ cell: 'decision',
982
+ decisionRef: ref,
983
+ ...(dec !== undefined ? { decisionId: dec.id } : {}),
984
+ message: `row #${row.num} cannot mark decision ${ref} as both sansObjet and blocking`,
985
+ });
986
+ }
987
+ }
988
+ }
989
+ for (const ref of row.decisionRefs) {
990
+ referencedDecisions.add(ref);
991
+ const dec = decisionMap.get(ref);
992
+ if (dec === undefined) {
993
+ violations.push({
994
+ code: 'invalid-decision',
995
+ check: 'decision.unlisted',
996
+ rowNum: row.num,
997
+ rowId: row.id,
998
+ cell: 'decision',
999
+ decisionRef: ref,
1000
+ message: `row #${row.num} points to unlisted decision ${ref}`,
1001
+ });
1002
+ }
1003
+ else {
1004
+ referencedDecisionIds.add(dec.id);
1005
+ if (row.status === 'withdrawn' &&
1006
+ dec.sansObjet !== true &&
1007
+ !emittedRowDecisionKeys.has(`withdrawn-not-sans-objet:${dec.id}`)) {
1008
+ violations.push({
1009
+ code: 'invalid-decision',
1010
+ check: 'decision.sans-objet-inconsistent',
1011
+ rowNum: row.num,
1012
+ rowId: row.id,
1013
+ cell: 'decision',
1014
+ decisionRef: ref,
1015
+ decisionId: dec.id,
1016
+ message: `row #${row.num} is ⚫ retiré and references decision ${ref} which is not marked sansObjet`,
1017
+ });
1018
+ }
1019
+ if (rowSansObjetSet.has(ref) &&
1020
+ dec.sansObjet !== true &&
1021
+ !emittedRowDecisionKeys.has(`row-marks-non-sans-objet:${dec.id}`)) {
1022
+ violations.push({
1023
+ code: 'invalid-decision',
1024
+ check: 'decision.sans-objet-inconsistent',
1025
+ rowNum: row.num,
1026
+ rowId: row.id,
1027
+ cell: 'decision',
1028
+ decisionRef: ref,
1029
+ decisionId: dec.id,
1030
+ message: `row #${row.num} marks decision ${ref} in sansObjetDecisionRefs, but decision ${ref} is not sansObjet`,
1031
+ });
1032
+ }
1033
+ if (dec.sansObjet === true &&
1034
+ !rowSansObjetSet.has(ref) &&
1035
+ !emittedRowDecisionKeys.has(`missing-sans-objet-mark:${dec.id}`)) {
1036
+ violations.push({
1037
+ code: 'invalid-decision',
1038
+ check: 'decision.sans-objet-inconsistent',
1039
+ rowNum: row.num,
1040
+ rowId: row.id,
1041
+ cell: 'decision',
1042
+ decisionRef: ref,
1043
+ decisionId: dec.id,
1044
+ message: `row #${row.num} references sans-objet decision ${ref} without listing it in sansObjetDecisionRefs`,
1045
+ });
1046
+ }
1047
+ }
1048
+ }
1049
+ // Gate: commit hash, ULID, internal jargon, or banned word in owner text
1050
+ if (row.captured === true) {
1051
+ if (row.capturedTitle !== undefined && row.capturedTitle.trim() !== '') {
1052
+ checkTextGates(row.capturedTitle, { rowNum: row.num, rowId: row.id, cell: 'request', field: `row #${row.num} "Ta demande" (title)` }, violations, policy);
1053
+ }
1054
+ if (row.capturedText !== undefined && row.capturedText.trim() !== '') {
1055
+ checkTextGates(row.capturedText, { rowNum: row.num, rowId: row.id, cell: 'request', field: `row #${row.num} "Ta demande" (text)` }, violations, policy);
1056
+ }
1057
+ }
1058
+ else {
1059
+ checkTextGates(row.request, { rowNum: row.num, rowId: row.id, cell: 'request', field: `row #${row.num} "Ta demande"` }, violations, policy);
1060
+ }
1061
+ checkTextGates(row.done, { rowNum: row.num, rowId: row.id, cell: 'done', field: `row #${row.num} "Fait"` }, violations, policy);
1062
+ checkTextGates(row.todo, { rowNum: row.num, rowId: row.id, cell: 'todo', field: `row #${row.num} "À faire (qui)"` }, violations, policy);
1063
+ }
1064
+ // Gate: decision without a row, or decision missing question / options / recommendation / dossierLink
1065
+ for (const d of view.decisions) {
1066
+ const isOwnerGate = d.kind === 'owner-gate';
1067
+ const dLabel = strictDecisionLabel(d);
1068
+ const dRefOpt = d.ref.trim() !== '' ? { decisionRef: d.ref } : {};
1069
+ if (d.sansObjet === true && d.blocking === true) {
1070
+ violations.push({
1071
+ code: 'invalid-decision',
1072
+ check: 'decision.sans-objet-blocking',
1073
+ ...dRefOpt,
1074
+ decisionId: d.id,
1075
+ message: `decision ${dLabel} is sans objet and must not be marked blocking`,
1076
+ });
1077
+ }
1078
+ if (isOwnerGate) {
1079
+ // OWNER GATE bypasses E4-E6 decision checks; text gates still apply to displayed fields.
1080
+ if (d.session !== undefined && d.session.trim() !== '') {
1081
+ checkTextGates(d.session, { decisionId: d.id, field: `decision ${dLabel} session` }, violations, policy);
1082
+ }
1083
+ continue;
1084
+ }
1085
+ const isReferenced = referencedDecisionIds.has(d.id) || (d.ref.trim() !== '' && referencedDecisions.has(d.ref));
1086
+ if (!isReferenced && d.sansObjet !== true) {
1087
+ violations.push({
1088
+ code: 'invalid-decision',
1089
+ check: 'decision.no-row',
1090
+ ...dRefOpt,
1091
+ decisionId: d.id,
1092
+ message: `decision ${dLabel} is not referenced by any row`,
1093
+ });
1094
+ }
1095
+ if (isDecisionIncomplete(d)) {
1096
+ violations.push({
1097
+ code: 'invalid-decision',
1098
+ check: 'decision.to-instruct',
1099
+ ...dRefOpt,
1100
+ decisionId: d.id,
1101
+ message: `decision ${dLabel} must carry a question, at least 2 options with consequences, and a valid recommendation`,
1102
+ });
1103
+ }
1104
+ if (isBlankOrDash(d.dossierLink)) {
1105
+ violations.push({
1106
+ code: 'invalid-decision',
1107
+ check: 'decision.no-dossier',
1108
+ ...dRefOpt,
1109
+ decisionId: d.id,
1110
+ message: `decision ${dLabel} is missing a dossier link`,
1111
+ });
1112
+ }
1113
+ checkTextGates(d.question, { ...dRefOpt, decisionId: d.id, field: `decision ${dLabel} question` }, violations, policy);
1114
+ checkTextGates(d.recommendation, { ...dRefOpt, decisionId: d.id, field: `decision ${dLabel} recommendation` }, violations, policy);
1115
+ if (d.dossierLink !== undefined) {
1116
+ checkTextGates(d.dossierLink, { ...dRefOpt, decisionId: d.id, field: `decision ${dLabel} dossierLink` }, violations, policy);
1117
+ }
1118
+ for (const opt of d.options) {
1119
+ checkTextGates(`${opt.label} ${opt.consequence}`, { ...dRefOpt, decisionId: d.id, field: `decision ${dLabel} option ${opt.letter}` }, violations, policy);
1120
+ }
1121
+ }
1122
+ if (view.replyLine !== undefined && view.replyLine !== '') {
1123
+ checkTextGates(view.replyLine, { field: 'replyLine' }, violations, policy);
1124
+ }
1125
+ // Class E9 (lot 2): structured decision without a registered number — appended AFTER existing
1126
+ // strict audit findings so `--strict` keeps lot-0 ordering and adds `[decision-unnumbered]` after.
1127
+ for (const d of view.decisions) {
1128
+ if (d.kind === 'owner-gate')
1129
+ continue;
1130
+ if (isDecisionIncomplete(d))
1131
+ continue;
1132
+ if (d.ref.trim() === '') {
1133
+ violations.push({
1134
+ code: 'decision-unnumbered',
1135
+ check: 'decision.unnumbered',
1136
+ decisionId: d.id,
1137
+ message: `decision ${strictDecisionLabel(d)} has no registered number`,
1138
+ });
1139
+ }
1140
+ }
1141
+ return {
1142
+ ok: violations.length === 0,
1143
+ violations,
1144
+ ...(notice !== undefined ? { notices: [notice] } : {}),
1145
+ };
1146
+ }
1147
+ function escapePipeCell(value) {
1148
+ return cleanDisplayText(value).replace(/\|/gu, '\\|');
1149
+ }
1150
+ /**
1151
+ * Render the owner table in Markdown (`md` / `text`) or JSON (`json`).
1152
+ * Refuses with a `DomainError` (`REFUSED: ...`) if any blocking gate fails.
1153
+ */
1154
+ export function renderOwnerTable(view, format = 'md', options) {
1155
+ const audit = auditOwnerTable(view, options);
1156
+ if (!audit.ok) {
1157
+ const details = audit.violations.map((v) => `- [${v.code}] ${v.message}`).join('\n');
1158
+ throw new DomainError(`REFUSED: owner table failed blocking gates:\n${details}`);
1159
+ }
1160
+ if (format === 'json') {
1161
+ return JSON.stringify(view, null, 2) + '\n';
1162
+ }
1163
+ const lines = [
1164
+ `| ${OWNER_TABLE_HEADERS.join(' | ')} |`,
1165
+ '| ---: | --- | --- | --- | --- | --- | --- | --- |',
1166
+ ];
1167
+ for (const row of view.rows) {
1168
+ const cells = [
1169
+ String(row.num),
1170
+ formatOwnerStatusCell(row),
1171
+ formatOwnerStageCell(row),
1172
+ escapePipeCell(formatOwnerEtaCell(row.etas)),
1173
+ escapePipeCell(row.request),
1174
+ escapePipeCell(row.done),
1175
+ escapePipeCell(row.todo),
1176
+ escapePipeCell(formatOwnerDecisionCell(row)),
1177
+ ];
1178
+ lines.push(`| ${cells.join(' | ')} |`);
1179
+ }
1180
+ lines.push('');
1181
+ lines.push("**Décisions qui t'attendent**");
1182
+ lines.push('');
1183
+ if (view.decisions.length === 0) {
1184
+ const scopeMotifs = audit.notices !== undefined && audit.notices.length > 0
1185
+ ? [MOTIF_CAPTURE_INACTIVE, MOTIF_POLICY_ABSENT]
1186
+ : [MOTIF_CAPTURE_INACTIVE];
1187
+ lines.push(formatPartialScopeNoDecisionsSentence(scopeMotifs));
1188
+ }
1189
+ else {
1190
+ for (const d of view.decisions) {
1191
+ const refHeading = d.sansObjet === true ? `**${d.ref}** (décision sans objet)` : `**${d.ref}**`;
1192
+ lines.push(`- ${refHeading} — ${cleanDisplayText(d.question)}`);
1193
+ for (const opt of d.options) {
1194
+ lines.push(` - **${opt.letter} · ${cleanDisplayText(opt.label)}** — ${cleanDisplayText(opt.consequence)}`);
1195
+ }
1196
+ const dossierSuffix = d.dossierLink !== undefined && d.dossierLink.trim() !== ''
1197
+ ? ` · Dossier : ${d.dossierLink.trim()}`
1198
+ : '';
1199
+ lines.push(` - Reco : **${d.recommendedLetter}** (${cleanDisplayText(d.recommendation)})${dossierSuffix}`);
1200
+ }
1201
+ }
1202
+ const hasReservedReply = view.replyLine.includes('aucune décision en attente');
1203
+ if (view.replyLine !== '' && !hasReservedReply) {
1204
+ lines.push('');
1205
+ lines.push(`\`${view.replyLine}\``);
1206
+ }
1207
+ return lines.join('\n') + '\n';
1208
+ }
1209
+ export function optionLetter(index) {
1210
+ let n = Math.max(0, Math.floor(index));
1211
+ let s = '';
1212
+ do {
1213
+ s = String.fromCharCode(65 + (n % 26)) + s;
1214
+ n = Math.floor(n / 26) - 1;
1215
+ } while (n >= 0);
1216
+ return s;
1217
+ }
1218
+ function defaultTargetStageFor(stage, requestedStage) {
1219
+ if (stage === undefined) {
1220
+ return requestedStage ?? 'spec';
1221
+ }
1222
+ if (requestedStage !== undefined && STAGE_RANK[requestedStage] > STAGE_RANK[stage]) {
1223
+ return requestedStage;
1224
+ }
1225
+ switch (stage) {
1226
+ case 'brainstorm':
1227
+ return 'spec';
1228
+ case 'spec':
1229
+ case 'plan':
1230
+ return 'dev';
1231
+ case 'dev':
1232
+ case 'test':
1233
+ return 'pr';
1234
+ case 'pr':
1235
+ case 'review':
1236
+ return 'merged';
1237
+ case 'merged':
1238
+ return 'published';
1239
+ case 'published':
1240
+ return 'preprod';
1241
+ case 'preprod':
1242
+ return 'prod';
1243
+ case 'prod':
1244
+ case 'done':
1245
+ return 'done';
1246
+ }
1247
+ }
1248
+ /**
1249
+ * Legacy prose helper (never applied to gated owner-table cells so blocking gates
1250
+ * cannot be bypassed by silent text rewriting).
1251
+ */
1252
+ export function normalizeLegacyOwnerProse(input) {
1253
+ let out = input;
1254
+ out = out.replace(PRIVATE_DIGEST_RE, 'empreinte vérifiée');
1255
+ out = out.replace(PRIVATE_PATH_RE, ' (chemin local)');
1256
+ out = out.replace(ULID_RE, 'réf. interne');
1257
+ out = out.replace(/\(\s*(?=[0-9a-f]{7,40}\s*\))(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\s*\)/giu, '');
1258
+ out = out.replace(COMMIT_HASH_RE, 'rév.');
1259
+ out = out.replace(/\b[a-z0-9_.-]+\/[a-z0-9_.-]+#(\d+)\b/giu, '#$1');
1260
+ out = out.replace(/\brealization=to-do\b/giu, 'non démarré');
1261
+ out = out.replace(/\brealization=in-progress\b/giu, 'en cours');
1262
+ out = out.replace(/\brealization=done\b/giu, 'réalisé');
1263
+ out = out.replace(/\bspec=to-specify\b/giu, 'à spécifier');
1264
+ out = out.replace(/\brecette=unknown\b/giu, 'recette non qualifiée');
1265
+ out = out.replace(/\bworktrees?\b/giu, 'espace');
1266
+ out = out.replace(/\bsubagents?\b/giu, 'agent');
1267
+ out = out.replace(/\bbwrap\b/giu, 'bac à sable');
1268
+ out = out.replace(/\btmux\b/giu, 'terminal');
1269
+ out = out.replace(/\bpty-host\b/giu, 'hôte terminal');
1270
+ out = out.replace(/\bevents\.jsonl\b/giu, 'journal');
1271
+ out = out.replace(/\baggregateId\b/giu, 'identifiant');
1272
+ out = out.replace(/\bspecStatus\b/giu, 'état de spec');
1273
+ out = out.replace(/\brealizedCommit\b/giu, 'ancrage');
1274
+ out = out.replace(/\blanes?\b/giu, 'piste');
1275
+ out = out.replace(/\bshards?\b/giu, 'lot');
1276
+ return cleanDisplayText(out);
1277
+ }
1278
+ function hasValidArchiveDecision(state, decisionId) {
1279
+ if (decisionId === undefined || decisionId.trim() === '')
1280
+ return false;
1281
+ const dec = state.decisions.get(decisionId);
1282
+ return dec !== undefined && dec.outcome === 'go';
1283
+ }
1284
+ /**
1285
+ * Project the folded `State` and event log into an `OwnerTableView`.
1286
+ * Pure read-time projection: never invents request numbers, causes, withdrawal reasons,
1287
+ * stages without links, or recommendations, and never rewrites gated text.
1288
+ */
1289
+ export function projectOwnerTable(state, events, options = {}) {
1290
+ const baselineCommit = options.baselineCommit ?? 'HEAD';
1291
+ const registeredNumbers = new Set();
1292
+ const archivedNumbers = new Set();
1293
+ const everOwnerItemIds = new Set();
1294
+ const historicalItemNumbers = new Map();
1295
+ const historicalItemRequests = new Map();
1296
+ const createdAtByAggregate = new Map();
1297
+ const promotedItemIds = new Set();
1298
+ for (const demand of state.demands.values()) {
1299
+ for (const itemId of demand.itemIds ?? [])
1300
+ promotedItemIds.add(itemId);
1301
+ }
1302
+ for (const ev of events) {
1303
+ if (typeof ev.at === 'string' &&
1304
+ !createdAtByAggregate.has(ev.aggregateId) &&
1305
+ (ev.type === 'demand.raised' ||
1306
+ ev.type === 'item.created' ||
1307
+ ev.type === 'decision.created' ||
1308
+ ev.type === 'item.report-updated')) {
1309
+ createdAtByAggregate.set(ev.aggregateId, ev.at);
1310
+ }
1311
+ if (ev.type === 'demand.owner-numbered') {
1312
+ const demand = state.demands.get(ev.aggregateId);
1313
+ if (options.workspace !== undefined && demand !== undefined && demand.workspace !== options.workspace)
1314
+ continue;
1315
+ const num = ev.payload.number;
1316
+ if (typeof num === 'number' && Number.isInteger(num) && num >= 1) {
1317
+ registeredNumbers.add(num);
1318
+ }
1319
+ }
1320
+ else if (ev.type === 'item.report-updated') {
1321
+ const item = state.items.get(ev.aggregateId);
1322
+ if (options.workspace !== undefined && item !== undefined && item.workspace !== options.workspace)
1323
+ continue;
1324
+ const payload = ev.payload;
1325
+ if (typeof payload?.ownerNumber === 'number' && Number.isInteger(payload.ownerNumber) && payload.ownerNumber >= 1) {
1326
+ if (!promotedItemIds.has(ev.aggregateId)) {
1327
+ registeredNumbers.add(payload.ownerNumber);
1328
+ }
1329
+ historicalItemNumbers.set(ev.aggregateId, payload.ownerNumber);
1330
+ }
1331
+ const histReq = typeof payload?.ownerSummary === 'string' && payload.ownerSummary.trim() !== ''
1332
+ ? payload.ownerSummary.trim()
1333
+ : typeof payload?.ownerRequest === 'string' && payload.ownerRequest.trim() !== ''
1334
+ ? payload.ownerRequest.trim()
1335
+ : undefined;
1336
+ if (histReq !== undefined) {
1337
+ historicalItemRequests.set(ev.aggregateId, histReq);
1338
+ }
1339
+ if (payload?.ownerNumber !== undefined || histReq !== undefined) {
1340
+ everOwnerItemIds.add(ev.aggregateId);
1341
+ }
1342
+ }
1343
+ }
1344
+ for (const demand of state.demands.values()) {
1345
+ if (options.workspace !== undefined && demand.workspace !== options.workspace)
1346
+ continue;
1347
+ if (demand.ownerNumber !== undefined) {
1348
+ registeredNumbers.add(demand.ownerNumber);
1349
+ if (demand.archived !== undefined && hasValidArchiveDecision(state, demand.archived.decisionId)) {
1350
+ archivedNumbers.add(demand.ownerNumber);
1351
+ }
1352
+ }
1353
+ }
1354
+ for (const item of state.items.values()) {
1355
+ if (options.workspace !== undefined && item.workspace !== options.workspace)
1356
+ continue;
1357
+ if (promotedItemIds.has(item.id))
1358
+ continue;
1359
+ const num = item.report?.ownerNumber ?? historicalItemNumbers.get(item.id);
1360
+ if (item.report?.ownerNumber !== undefined) {
1361
+ registeredNumbers.add(item.report.ownerNumber);
1362
+ }
1363
+ if (num !== undefined &&
1364
+ item.report?.archived !== undefined &&
1365
+ hasValidArchiveDecision(state, item.report.archived.decisionId)) {
1366
+ archivedNumbers.add(num);
1367
+ }
1368
+ }
1369
+ const candidates = [];
1370
+ for (const demand of state.demands.values()) {
1371
+ if (options.workspace !== undefined && demand.workspace !== options.workspace)
1372
+ continue;
1373
+ if (demand.archived !== undefined && hasValidArchiveDecision(state, demand.archived.decisionId))
1374
+ continue;
1375
+ const promoted = (demand.itemIds ?? [])
1376
+ .map((id) => state.items.get(id))
1377
+ .filter((it) => it !== undefined);
1378
+ candidates.push({
1379
+ kind: 'demand',
1380
+ id: demand.id,
1381
+ ...(demand.ownerNumber !== undefined ? { explicitNumber: demand.ownerNumber } : {}),
1382
+ demand,
1383
+ items: promoted,
1384
+ });
1385
+ }
1386
+ for (const item of state.items.values()) {
1387
+ if (options.workspace !== undefined && item.workspace !== options.workspace)
1388
+ continue;
1389
+ if (promotedItemIds.has(item.id))
1390
+ continue;
1391
+ if (item.report?.archived !== undefined && hasValidArchiveDecision(state, item.report.archived.decisionId))
1392
+ continue;
1393
+ const resolvedItemNumber = item.report?.ownerNumber ?? historicalItemNumbers.get(item.id);
1394
+ const hasOwnerMeta = everOwnerItemIds.has(item.id) ||
1395
+ resolvedItemNumber !== undefined ||
1396
+ item.report?.ownerSummary !== undefined ||
1397
+ item.report?.ownerRequest !== undefined;
1398
+ if (!hasOwnerMeta)
1399
+ continue;
1400
+ candidates.push({
1401
+ kind: 'item',
1402
+ id: item.id,
1403
+ ...(resolvedItemNumber !== undefined ? { explicitNumber: resolvedItemNumber } : {}),
1404
+ items: [item],
1405
+ });
1406
+ }
1407
+ const numberedCandidates = candidates.map((c) => ({
1408
+ ...c,
1409
+ num: c.explicitNumber ?? 0,
1410
+ }));
1411
+ numberedCandidates.sort((a, b) => {
1412
+ if (a.num > 0 && b.num > 0)
1413
+ return a.num - b.num;
1414
+ if (a.num > 0)
1415
+ return -1;
1416
+ if (b.num > 0)
1417
+ return 1;
1418
+ return 0;
1419
+ });
1420
+ const pauseDecisionIds = new Set();
1421
+ for (const item of state.items.values()) {
1422
+ if (options.workspace !== undefined && item.workspace !== options.workspace)
1423
+ continue;
1424
+ if (item.report?.pausedByOwner === true &&
1425
+ item.report.pauseDecisionId !== undefined &&
1426
+ item.report.pauseDecisionId.trim() !== '') {
1427
+ const dec = state.decisions.get(item.report.pauseDecisionId);
1428
+ if (dec !== undefined && (dec.outcome === 'go' || dec.outcome === 'deferred')) {
1429
+ pauseDecisionIds.add(dec.id);
1430
+ }
1431
+ }
1432
+ }
1433
+ const isTargetArchived = (targetId, seen = new Set()) => {
1434
+ if (seen.has(targetId))
1435
+ return false;
1436
+ seen.add(targetId);
1437
+ const dem = state.demands.get(targetId);
1438
+ if (dem !== undefined) {
1439
+ return dem.archived !== undefined && hasValidArchiveDecision(state, dem.archived.decisionId);
1440
+ }
1441
+ const it = state.items.get(targetId);
1442
+ if (it === undefined)
1443
+ return false;
1444
+ if (it.report?.archived !== undefined && hasValidArchiveDecision(state, it.report.archived.decisionId)) {
1445
+ return true;
1446
+ }
1447
+ if (it.demandId !== undefined && isTargetArchived(it.demandId, seen))
1448
+ return true;
1449
+ for (const parentDem of state.demands.values()) {
1450
+ if (parentDem.itemIds?.includes(it.id) && isTargetArchived(parentDem.id, seen))
1451
+ return true;
1452
+ }
1453
+ if (it.parentId !== undefined && isTargetArchived(it.parentId, seen))
1454
+ return true;
1455
+ return false;
1456
+ };
1457
+ const isTargetWithdrawnOrArchived = (targetId, seen = new Set()) => {
1458
+ if (isTargetArchived(targetId))
1459
+ return true;
1460
+ if (seen.has(targetId))
1461
+ return false;
1462
+ seen.add(targetId);
1463
+ const dem = state.demands.get(targetId);
1464
+ if (dem !== undefined) {
1465
+ if (dem.status === 'rejected' || dem.status === 'duplicate')
1466
+ return true;
1467
+ const itemIds = dem.itemIds ?? [];
1468
+ return itemIds.length > 0 && itemIds.every((id) => isTargetWithdrawnOrArchived(id, new Set(seen)));
1469
+ }
1470
+ const it = state.items.get(targetId);
1471
+ if (it === undefined)
1472
+ return false;
1473
+ if (it.realization === 'cancelled' || it.realization === 'rejected')
1474
+ return true;
1475
+ if (it.demandId !== undefined) {
1476
+ const parentDem = state.demands.get(it.demandId);
1477
+ if (parentDem !== undefined && (parentDem.status === 'rejected' || parentDem.status === 'duplicate')) {
1478
+ return true;
1479
+ }
1480
+ }
1481
+ for (const parentDem of state.demands.values()) {
1482
+ if (parentDem.itemIds?.includes(it.id) &&
1483
+ (parentDem.status === 'rejected' || parentDem.status === 'duplicate')) {
1484
+ return true;
1485
+ }
1486
+ }
1487
+ if (it.parentId !== undefined && isTargetWithdrawnOrArchived(it.parentId, seen))
1488
+ return true;
1489
+ return false;
1490
+ };
1491
+ // Every unsettled decision in the workspace (except owner-pause deferrals) is listed,
1492
+ // including legacy decisions without options (which fail Gate 5 instead of silently disappearing)
1493
+ const pendingDecisions = [];
1494
+ for (const decision of state.decisions.values()) {
1495
+ if (options.workspace !== undefined && decision.workspace !== options.workspace)
1496
+ continue;
1497
+ if (isSettled(decision.outcome) ||
1498
+ (decision.outcome === 'deferred' && pauseDecisionIds.has(decision.id))) {
1499
+ continue;
1500
+ }
1501
+ pendingDecisions.push(decision);
1502
+ }
1503
+ const extractOwnerGateSession = (context) => {
1504
+ if (context === undefined)
1505
+ return undefined;
1506
+ for (const line of context.split('\n')) {
1507
+ const match = /^\s*Target instance and session:\s*(.+?)\s*$/iu.exec(line);
1508
+ if (match !== null && match[1] !== undefined && match[1].trim() !== '') {
1509
+ return match[1].trim();
1510
+ }
1511
+ }
1512
+ return undefined;
1513
+ };
1514
+ const sansObjetDecisionIds = new Set();
1515
+ const decisionRefById = new Map();
1516
+ const ownerDecisionById = new Map();
1517
+ const ownerDecisions = pendingDecisions.map((d) => {
1518
+ const isGate = isOwnerGateTitle(d.title);
1519
+ const sansObjet = d.targets.length > 0 && d.targets.every((targetId) => isTargetWithdrawnOrArchived(targetId));
1520
+ if (sansObjet) {
1521
+ sansObjetDecisionIds.add(d.id);
1522
+ }
1523
+ const question = cleanDisplayText(shortDecisionSubject(d.title));
1524
+ const rawOptions = Array.isArray(d.dossier?.options) ? d.dossier.options : [];
1525
+ const optionsList = rawOptions.map((opt, optIdx) => ({
1526
+ letter: optionLetter(optIdx),
1527
+ label: cleanDisplayText(opt.title),
1528
+ consequence: cleanDisplayText(opt.summary),
1529
+ }));
1530
+ const recOptionId = d.dossier?.recommendation?.optionId;
1531
+ const recRationale = d.dossier?.recommendation?.rationale;
1532
+ const recIdx = recOptionId !== undefined ? rawOptions.findIndex((o) => o.id === recOptionId) : -1;
1533
+ const recommendedLetter = recIdx >= 0 ? optionLetter(recIdx) : '';
1534
+ const recommendation = recIdx >= 0 && recRationale !== undefined && recRationale.trim() !== ''
1535
+ ? cleanDisplayText(recRationale)
1536
+ : '';
1537
+ // Stable decision numbers (lot 2): positional numbering is removed. OWNER GATE, E5 (incomplete
1538
+ // dossier — hides even a recorded number until complete), and E9 (no registered number) carry
1539
+ // internal `ref: ''` (JSON `null`).
1540
+ const incomplete = isDecisionIncomplete({
1541
+ question,
1542
+ options: optionsList,
1543
+ recommendedLetter,
1544
+ recommendation,
1545
+ });
1546
+ const ref = isGate || incomplete
1547
+ ? ''
1548
+ : d.ownerNumber !== undefined && Number.isInteger(d.ownerNumber) && d.ownerNumber >= 1
1549
+ ? `D${d.ownerNumber}`
1550
+ : '';
1551
+ decisionRefById.set(d.id, ref);
1552
+ const artifactLink = d.dossier?.artifacts?.find((a) => a.kind === 'rendered-view')?.viewRef;
1553
+ const hasOpenBlocker = !sansObjet &&
1554
+ !pauseDecisionIds.has(d.id) &&
1555
+ [...state.blockers.values()].some((b) => b.open && b.kind === 'decision' && b.ref === d.id);
1556
+ const rawQa = Array.isArray(d.dossier?.qa) ? d.dossier.qa : [];
1557
+ const openQuestionCount = rawQa.filter((q) => q.answer === undefined || q.answer.trim() === '').length;
1558
+ const createdAt = createdAtByAggregate.get(d.id);
1559
+ const session = isGate ? extractOwnerGateSession(d.dossier?.context) : undefined;
1560
+ const entry = {
1561
+ ref,
1562
+ id: d.id,
1563
+ kind: isGate ? 'owner-gate' : 'decision',
1564
+ question,
1565
+ options: optionsList,
1566
+ recommendedLetter,
1567
+ recommendation,
1568
+ ...(artifactLink !== undefined ? { dossierLink: artifactLink } : {}),
1569
+ blocking: hasOpenBlocker,
1570
+ ...(sansObjet ? { sansObjet: true } : {}),
1571
+ ...(createdAt !== undefined ? { createdAt } : {}),
1572
+ deferred: d.outcome === 'deferred',
1573
+ openQuestionCount,
1574
+ ...(session !== undefined ? { session } : {}),
1575
+ };
1576
+ ownerDecisionById.set(d.id, entry);
1577
+ return entry;
1578
+ });
1579
+ const decisionTargetsItem = (d, item, demandIdForSingle) => {
1580
+ for (const targetId of d.targets) {
1581
+ if (demandIdForSingle !== undefined && targetId === demandIdForSingle)
1582
+ return true;
1583
+ if (item !== undefined && targetId === item.id)
1584
+ return true;
1585
+ const visited = new Set();
1586
+ let curr = state.items.get(targetId);
1587
+ while (curr !== undefined && !visited.has(curr.id)) {
1588
+ visited.add(curr.id);
1589
+ if (item !== undefined && curr.id === item.id)
1590
+ return true;
1591
+ if (demandIdForSingle !== undefined && curr.demandId === demandIdForSingle)
1592
+ return true;
1593
+ curr = curr.parentId !== undefined ? state.items.get(curr.parentId) : undefined;
1594
+ }
1595
+ }
1596
+ return false;
1597
+ };
1598
+ const projectSingleOrLotRow = (params) => {
1599
+ const { rowKind, num, rowId, parentDemandId, demand, item, request, requestedStage } = params;
1600
+ const report = item?.report;
1601
+ const derived = item !== undefined ? deriveItemStageStatus(state, events, item, baselineCommit) : undefined;
1602
+ let stage;
1603
+ let status;
1604
+ let hasWitness = false;
1605
+ let pausedByOwner = false;
1606
+ if (item === undefined && demand !== undefined) {
1607
+ stage = undefined;
1608
+ if (demand.status === 'rejected' || demand.status === 'duplicate') {
1609
+ status = 'withdrawn';
1610
+ }
1611
+ else if (demand.status === 'parked') {
1612
+ if (demand.parkReason !== undefined && demand.parkReason.trim() !== '') {
1613
+ status = 'not-started';
1614
+ pausedByOwner = true;
1615
+ }
1616
+ else {
1617
+ status = 'not-qualified';
1618
+ }
1619
+ }
1620
+ else {
1621
+ status = 'not-started';
1622
+ }
1623
+ }
1624
+ else if (derived !== undefined) {
1625
+ stage = derived.linkedStage;
1626
+ hasWitness =
1627
+ stage !== undefined &&
1628
+ derived.qualified &&
1629
+ derived.linkedStageEvidence !== undefined &&
1630
+ derived.linkedStageEvidence.trim() !== '';
1631
+ pausedByOwner = derived.status === 'not-started' && derived.pausedByOwner === true;
1632
+ status = derived.status;
1633
+ if (status === 'on-track' && (!hasWitness || stage === undefined || stage === 'done')) {
1634
+ status = 'not-qualified';
1635
+ }
1636
+ else if (status === 'done' && (stage !== 'done' || !hasWitness)) {
1637
+ status = hasWitness && stage !== undefined && stage !== 'done' ? 'on-track' : 'not-qualified';
1638
+ }
1639
+ }
1640
+ else {
1641
+ status = 'not-started';
1642
+ }
1643
+ // Decisions linked to this specific row (a lot row never reads decisions targeting the demand or sibling lots)
1644
+ const linkedDecisionIds = new Set();
1645
+ for (const d of pendingDecisions) {
1646
+ if (decisionTargetsItem(d, item, rowKind === 'single' ? demand?.id : undefined)) {
1647
+ if (status !== 'withdrawn' || sansObjetDecisionIds.has(d.id)) {
1648
+ linkedDecisionIds.add(d.id);
1649
+ }
1650
+ }
1651
+ }
1652
+ const rowDecisionIds = [...linkedDecisionIds];
1653
+ const explicitRefs = status === 'withdrawn' ? [] : (report?.decisionRefs ?? []);
1654
+ const rowDecisionRefs = [
1655
+ ...explicitRefs,
1656
+ ...rowDecisionIds
1657
+ .map((id) => decisionRefById.get(id))
1658
+ .filter((r) => r !== undefined && r !== ''),
1659
+ ];
1660
+ const uniqueDecisionRefs = [...new Set(rowDecisionRefs)];
1661
+ const openDecisionBlockers = item === undefined || status === 'withdrawn'
1662
+ ? []
1663
+ : (() => {
1664
+ const itPauseId = item.report?.pausedByOwner === true && item.report.pauseDecisionId !== undefined
1665
+ ? item.report.pauseDecisionId
1666
+ : undefined;
1667
+ const itOwnerPaused = itPauseId !== undefined && pauseDecisionIds.has(itPauseId);
1668
+ return effectiveOpenBlockersForItem(state, item.id, baselineCommit).filter((b) => {
1669
+ if (b.kind !== 'decision')
1670
+ return false;
1671
+ if (itOwnerPaused && (b.ref === undefined || b.ref === itPauseId))
1672
+ return false;
1673
+ if (b.ref !== undefined && pauseDecisionIds.has(b.ref))
1674
+ return false;
1675
+ return true;
1676
+ });
1677
+ })();
1678
+ const blockingDecisionIdSet = new Set();
1679
+ const blockingDecisionRefSet = new Set();
1680
+ if (status !== 'withdrawn') {
1681
+ for (const dId of linkedDecisionIds) {
1682
+ const isBlockingThisRow = openDecisionBlockers.some((b) => b.ref === undefined || b.ref === dId) ||
1683
+ (rowKind === 'single' &&
1684
+ demand !== undefined &&
1685
+ [...state.blockers.values()].some((b) => b.open && b.kind === 'decision' && b.targetId === demand.id && b.ref === dId));
1686
+ if (isBlockingThisRow) {
1687
+ blockingDecisionIdSet.add(dId);
1688
+ const ref = decisionRefById.get(dId);
1689
+ if (ref !== undefined && ref !== '')
1690
+ blockingDecisionRefSet.add(ref);
1691
+ }
1692
+ }
1693
+ if (!pausedByOwner && report?.decisionBlocking === true) {
1694
+ for (const dId of rowDecisionIds)
1695
+ blockingDecisionIdSet.add(dId);
1696
+ for (const ref of uniqueDecisionRefs)
1697
+ blockingDecisionRefSet.add(ref);
1698
+ }
1699
+ }
1700
+ // Also incorporate item.report.decisionExpectations if set and no native Decision exists
1701
+ if (status !== 'withdrawn' &&
1702
+ report?.decisionExpectations !== undefined &&
1703
+ rowDecisionIds.length === 0 &&
1704
+ uniqueDecisionRefs.length === 0) {
1705
+ // Synthetic `:expectation` decisions retain identity and qualify as E5 without invented numbering.
1706
+ const ref = '';
1707
+ const syntheticId = `${rowId}:expectation`;
1708
+ rowDecisionIds.push(syntheticId);
1709
+ if (report.decisionBlocking === true || openDecisionBlockers.length > 0) {
1710
+ blockingDecisionIdSet.add(syntheticId);
1711
+ }
1712
+ const opts = report.decisionExpectations.options.map((o, idx) => ({
1713
+ letter: optionLetter(idx),
1714
+ label: cleanDisplayText(o.label),
1715
+ consequence: cleanDisplayText(o.consequence),
1716
+ }));
1717
+ const syntheticCreatedAt = createdAtByAggregate.get(item?.id ?? rowId) ?? createdAtByAggregate.get(rowId);
1718
+ const syntheticEntry = {
1719
+ ref,
1720
+ id: syntheticId,
1721
+ kind: 'decision',
1722
+ question: cleanDisplayText(report.decisionExpectations.question),
1723
+ options: opts,
1724
+ recommendedLetter: '',
1725
+ recommendation: '',
1726
+ ...(report.decisionExpectations.dossier !== undefined
1727
+ ? { dossierLink: report.decisionExpectations.dossier }
1728
+ : {}),
1729
+ blocking: blockingDecisionIdSet.has(syntheticId),
1730
+ ...(syntheticCreatedAt !== undefined ? { createdAt: syntheticCreatedAt } : {}),
1731
+ deferred: false,
1732
+ openQuestionCount: 0,
1733
+ };
1734
+ decisionRefById.set(syntheticId, ref);
1735
+ ownerDecisionById.set(syntheticId, syntheticEntry);
1736
+ ownerDecisions.push(syntheticEntry);
1737
+ }
1738
+ const sansObjetDecisionIdSet = new Set();
1739
+ const sansObjetDecisionRefSet = new Set();
1740
+ for (const dId of linkedDecisionIds) {
1741
+ if (sansObjetDecisionIds.has(dId)) {
1742
+ sansObjetDecisionIdSet.add(dId);
1743
+ const ref = decisionRefById.get(dId);
1744
+ if (ref !== undefined && ref !== '')
1745
+ sansObjetDecisionRefSet.add(ref);
1746
+ }
1747
+ }
1748
+ const rowSansObjetIds = rowDecisionIds.filter((dId) => sansObjetDecisionIdSet.has(dId));
1749
+ const rowBlockingIds = rowDecisionIds.filter((dId) => blockingDecisionIdSet.has(dId));
1750
+ const sansObjetDecisionRefs = uniqueDecisionRefs.filter((ref) => sansObjetDecisionRefSet.has(ref));
1751
+ const blockingDecisionRefs = uniqueDecisionRefs.filter((ref) => blockingDecisionRefSet.has(ref));
1752
+ const decisionBlocking = status !== 'withdrawn' &&
1753
+ (rowBlockingIds.length > 0 ||
1754
+ blockingDecisionRefs.length > 0 ||
1755
+ (!pausedByOwner && report?.decisionBlocking === true));
1756
+ if (decisionBlocking) {
1757
+ status = 'blocked';
1758
+ }
1759
+ const toEtaEntry = (j) => ({
1760
+ targetStage: j.targetStage,
1761
+ ...(j.targetLabel !== undefined ? { targetLabel: j.targetLabel } : {}),
1762
+ when: j.when,
1763
+ source: j.source,
1764
+ ...(j.by !== undefined ? { by: j.by } : {}),
1765
+ ...(j.slip !== undefined ? { slip: j.slip } : {}),
1766
+ ...(j.measured !== undefined ? { measured: j.measured } : {}),
1767
+ });
1768
+ const baseSlots = [];
1769
+ const itemEtas = item?.etaJournal !== undefined && item.etaJournal.length > 0
1770
+ ? item.etaJournal.filter((j) => j.delivered !== true)
1771
+ : (report?.etas ?? []);
1772
+ for (const j of itemEtas) {
1773
+ baseSlots.push({ entry: toEtaEntry(j), origin: 'item' });
1774
+ }
1775
+ if (rowKind === 'single' && demand?.etaJournal !== undefined) {
1776
+ for (const j of demand.etaJournal.filter((entry) => entry.delivered !== true)) {
1777
+ baseSlots.push({ entry: toEtaEntry(j), origin: 'demand' });
1778
+ }
1779
+ }
1780
+ const lookupVelocityInputs = () => {
1781
+ if (options.velocityBindings === undefined)
1782
+ return [];
1783
+ // A lot row reads ONLY its own item id; never the parent demand or request number
1784
+ const keysToTry = rowKind === 'lot'
1785
+ ? item !== undefined
1786
+ ? [item.id]
1787
+ : []
1788
+ : [
1789
+ rowId,
1790
+ ...(item !== undefined && item.id !== rowId ? [item.id] : []),
1791
+ ...(num > 0 ? [String(num)] : []),
1792
+ ];
1793
+ const matched = [];
1794
+ const seenKeys = new Set();
1795
+ for (const k of keysToTry) {
1796
+ if (seenKeys.has(k))
1797
+ continue;
1798
+ seenKeys.add(k);
1799
+ const found = options.velocityBindings instanceof Map
1800
+ ? options.velocityBindings.get(k)
1801
+ : options.velocityBindings[k];
1802
+ if (found !== undefined) {
1803
+ const list = Array.isArray(found) ? found : [found];
1804
+ matched.push(...list);
1805
+ }
1806
+ }
1807
+ return matched;
1808
+ };
1809
+ const velocityInputs = lookupVelocityInputs();
1810
+ const velocitySlots = velocityInputs.map((vInput) => {
1811
+ const priorSlot = baseSlots.find((s) => s.entry.targetStage === vInput.targetStage && s.entry.slip !== undefined) ??
1812
+ baseSlots.find((s) => s.entry.targetStage === vInput.targetStage);
1813
+ const qualified = qualifyVelocityEta({
1814
+ ...vInput,
1815
+ ...(vInput.slip !== undefined
1816
+ ? { slip: vInput.slip }
1817
+ : priorSlot?.entry.slip !== undefined
1818
+ ? { slip: priorSlot.entry.slip }
1819
+ : {}),
1820
+ });
1821
+ return {
1822
+ entry: qualified.eta,
1823
+ origin: 'velocity',
1824
+ };
1825
+ });
1826
+ const rawSlots = [...velocitySlots, ...baseSlots];
1827
+ const evaluatedSlots = rawSlots.map((slot) => ({
1828
+ ...evaluateEtaDeadline(slot.entry, stage, {
1829
+ ...(options.now !== undefined ? { now: options.now } : {}),
1830
+ pausedByOwner,
1831
+ }),
1832
+ origin: slot.origin,
1833
+ }));
1834
+ const displaySlots = evaluatedSlots.filter((ev) => stage === undefined || STAGE_RANK[stage] < STAGE_RANK[ev.eta.targetStage]);
1835
+ const anyEtaMissed = displaySlots.some((ev) => ev.missed);
1836
+ let etas;
1837
+ if (status === 'done' || status === 'withdrawn') {
1838
+ etas = [];
1839
+ }
1840
+ else if (displaySlots.length > 0) {
1841
+ const byStage = new Map();
1842
+ for (const ev of displaySlots) {
1843
+ const prev = byStage.get(ev.eta.targetStage);
1844
+ if (prev === undefined || (!prev.missed && ev.missed)) {
1845
+ byStage.set(ev.eta.targetStage, ev);
1846
+ }
1847
+ }
1848
+ const unique = [...byStage.values()];
1849
+ unique.sort((a, b) => (b.missed ? 1 : 0) - (a.missed ? 1 : 0) ||
1850
+ STAGE_RANK[a.eta.targetStage] - STAGE_RANK[b.eta.targetStage]);
1851
+ etas = unique.slice(0, 2).map((ev) => ev.eta);
1852
+ }
1853
+ else {
1854
+ etas = [
1855
+ {
1856
+ targetStage: defaultTargetStageFor(stage, requestedStage),
1857
+ when: '—',
1858
+ source: 'unknown',
1859
+ },
1860
+ ];
1861
+ }
1862
+ if (anyEtaMissed && status !== 'withdrawn' && status !== 'done' && status !== 'blocked') {
1863
+ status = 'unforeseen';
1864
+ }
1865
+ // Done cell (`Fait`)
1866
+ let doneText;
1867
+ if (status === 'withdrawn') {
1868
+ const itemFacts = report?.facts?.trim() !== '' ? report?.facts?.trim() : undefined;
1869
+ let settledDecisionReason;
1870
+ if (item !== undefined) {
1871
+ const linkedSettled = [...state.decisions.values()]
1872
+ .filter((d) => d.targets.includes(item.id) && d.outcome === 'no-go')
1873
+ .sort((a, b) => (a.id < b.id ? -1 : 1));
1874
+ for (const decision of linkedSettled) {
1875
+ const selected = decision.dossier.options.find((o) => o.id === decision.dossier.selectedOptionId);
1876
+ const cand = selected?.summary?.trim() || selected?.title?.trim();
1877
+ if (cand !== undefined && cand !== '') {
1878
+ settledDecisionReason = cand;
1879
+ break;
1880
+ }
1881
+ }
1882
+ }
1883
+ const reopenReason = item?.reopenings?.at(-1)?.reason?.trim() !== '' ? item?.reopenings?.at(-1)?.reason?.trim() : undefined;
1884
+ const reason = (rowKind === 'single' ? demand?.rejectReason : undefined) ??
1885
+ itemFacts ??
1886
+ settledDecisionReason ??
1887
+ reopenReason;
1888
+ doneText = reason !== undefined && reason.trim() !== '' ? cleanDisplayText(reason) : '—';
1889
+ }
1890
+ else {
1891
+ const parts = [];
1892
+ if (report?.facts !== undefined && report.facts.trim() !== '') {
1893
+ parts.push(cleanDisplayText(report.facts));
1894
+ }
1895
+ if (parts.length === 0 &&
1896
+ derived?.linkedStageEvidence !== undefined &&
1897
+ derived.linkedStageEvidence.trim() !== '') {
1898
+ parts.push(`Preuve : ${cleanDisplayText(derived.linkedStageEvidence)}`);
1899
+ }
1900
+ doneText = parts.length > 0 ? parts.join(' · ') : '—';
1901
+ }
1902
+ // Todo cell (`À faire (qui)`) — never inject a fallback cause when blocked
1903
+ let todoText;
1904
+ if (status === 'withdrawn') {
1905
+ todoText = '—';
1906
+ }
1907
+ else {
1908
+ const openBlockers = item !== undefined ? effectiveOpenBlockersForItem(state, item.id, baselineCommit) : [];
1909
+ const blockerReasons = openBlockers
1910
+ .filter((b) => b.kind !== 'decision')
1911
+ .map((b) => cleanDisplayText(b.reason))
1912
+ .filter((r) => r.length > 0);
1913
+ const baseTodoParts = [];
1914
+ if (rowBlockingIds.length > 0) {
1915
+ for (const dId of rowBlockingIds) {
1916
+ const dec = ownerDecisionById.get(dId);
1917
+ if (dec === undefined)
1918
+ continue;
1919
+ const isGate = dec.kind === 'owner-gate';
1920
+ const incomplete = !isGate && isDecisionIncomplete(dec);
1921
+ const isToNumber = !isGate && !incomplete && dec.ref === '';
1922
+ baseTodoParts.push(formatBlockingDecisionTodoCause({
1923
+ kind: dec.kind ?? 'decision',
1924
+ ref: dec.ref !== '' ? dec.ref : null,
1925
+ isToInstruct: incomplete,
1926
+ isToNumber,
1927
+ session: dec.session ?? null,
1928
+ }));
1929
+ }
1930
+ }
1931
+ else if (blockingDecisionRefs.length > 0) {
1932
+ for (const ref of blockingDecisionRefs) {
1933
+ baseTodoParts.push(formatBlockingDecisionTodoCause({
1934
+ kind: 'decision',
1935
+ ref,
1936
+ isToInstruct: false,
1937
+ }));
1938
+ }
1939
+ }
1940
+ if (blockerReasons.length > 0) {
1941
+ baseTodoParts.push(...new Set(blockerReasons));
1942
+ }
1943
+ if (report?.waitingOn !== undefined && report.waitingOn.trim() !== '') {
1944
+ const w = `attente : ${cleanDisplayText(report.waitingOn)}`;
1945
+ if (!baseTodoParts.includes(w))
1946
+ baseTodoParts.push(w);
1947
+ }
1948
+ if (report?.nextAction !== undefined && report.nextAction.trim() !== '') {
1949
+ const na = cleanDisplayText(report.nextAction);
1950
+ if (!baseTodoParts.includes(na))
1951
+ baseTodoParts.push(na);
1952
+ }
1953
+ else if (report?.proposal !== undefined && report.proposal.trim() !== '') {
1954
+ const pr = cleanDisplayText(report.proposal);
1955
+ if (!baseTodoParts.includes(pr))
1956
+ baseTodoParts.push(pr);
1957
+ }
1958
+ if (baseTodoParts.length === 0 &&
1959
+ rowKind === 'single' &&
1960
+ demand !== undefined &&
1961
+ item === undefined &&
1962
+ status !== 'blocked') {
1963
+ if (demand.status === 'parked' && demand.parkReason !== undefined && demand.parkReason.trim() !== '') {
1964
+ baseTodoParts.push(`en pause (${cleanDisplayText(demand.parkReason)})`);
1965
+ }
1966
+ }
1967
+ todoText = baseTodoParts.length > 0 ? baseTodoParts.join(' ; ') : '—';
1968
+ }
1969
+ const rowCreatedAt = createdAtByAggregate.get(rowId) ??
1970
+ (item !== undefined ? createdAtByAggregate.get(item.id) : undefined);
1971
+ const capturedDemand = rowKind === 'single' && demand?.captured === true ? demand : undefined;
1972
+ const capturedTitle = capturedDemand !== undefined ? (capturedDemand.ownerSummary ?? capturedDemand.raw.title) : undefined;
1973
+ const capturedText = capturedDemand !== undefined ? capturedDemand.raw.text : undefined;
1974
+ return {
1975
+ kind: rowKind,
1976
+ ...(parentDemandId !== undefined ? { parentDemandId } : {}),
1977
+ num,
1978
+ id: rowId,
1979
+ status,
1980
+ ...(pausedByOwner ? { pausedByOwner: true } : {}),
1981
+ ...(stage !== undefined ? { stage } : {}),
1982
+ ...(requestedStage !== undefined ? { requestedStage } : {}),
1983
+ etas,
1984
+ request,
1985
+ done: doneText,
1986
+ todo: todoText,
1987
+ decisionRefs: uniqueDecisionRefs,
1988
+ ...(sansObjetDecisionRefs.length > 0 ? { sansObjetDecisionRefs } : {}),
1989
+ ...(blockingDecisionRefs.length > 0 ? { blockingDecisionRefs } : {}),
1990
+ decisionIds: rowDecisionIds,
1991
+ ...(rowBlockingIds.length > 0 ? { blockingDecisionIds: rowBlockingIds } : {}),
1992
+ ...(rowSansObjetIds.length > 0 ? { sansObjetDecisionIds: rowSansObjetIds } : {}),
1993
+ ...(decisionBlocking ? { decisionBlocking: true } : {}),
1994
+ hasWitness,
1995
+ ...(rowCreatedAt !== undefined ? { createdAt: rowCreatedAt } : {}),
1996
+ ...(capturedDemand !== undefined
1997
+ ? {
1998
+ captured: true,
1999
+ ...(capturedDemand.captureOrigin !== undefined ? { captureOrigin: capturedDemand.captureOrigin } : {}),
2000
+ ...(capturedTitle !== undefined && capturedTitle.trim() !== '' ? { capturedTitle: cleanDisplayText(capturedTitle) } : {}),
2001
+ ...(capturedText !== undefined ? { capturedText: cleanDisplayText(capturedText) } : {}),
2002
+ ...(capturedDemand.maskedAtInscription === true ? { maskedAtInscription: true } : {}),
2003
+ }
2004
+ : {}),
2005
+ };
2006
+ };
2007
+ const rows = [];
2008
+ for (const c of numberedCandidates) {
2009
+ if (c.kind === 'demand' && c.items.length > 1) {
2010
+ const demand = c.demand;
2011
+ const rawTitleRequest = demand.ownerSummary ?? demand.raw.title ?? demand.raw.text ?? '';
2012
+ const titleRequest = cleanDisplayText(rawTitleRequest);
2013
+ // Decisions targeting the demand itself (not individual lots)
2014
+ const titleDecisionIds = [];
2015
+ for (const d of pendingDecisions) {
2016
+ if (d.targets.includes(demand.id)) {
2017
+ titleDecisionIds.push(d.id);
2018
+ }
2019
+ }
2020
+ const titleDecisionRefs = titleDecisionIds
2021
+ .map((id) => decisionRefById.get(id))
2022
+ .filter((r) => r !== undefined && r !== '');
2023
+ const titleSansObjetIds = titleDecisionIds.filter((dId) => sansObjetDecisionIds.has(dId));
2024
+ const titleSansObjetRefs = titleSansObjetIds
2025
+ .map((dId) => decisionRefById.get(dId))
2026
+ .filter((r) => r !== undefined && r !== '');
2027
+ const titleBlockingIds = titleDecisionIds.filter((dId) => !sansObjetDecisionIds.has(dId) &&
2028
+ [...state.blockers.values()].some((b) => b.open && b.kind === 'decision' && b.targetId === demand.id && b.ref === dId));
2029
+ const titleBlockingRefs = titleBlockingIds
2030
+ .map((dId) => decisionRefById.get(dId))
2031
+ .filter((r) => r !== undefined && r !== '');
2032
+ // Demand-level ETA (demand.eta-set) shows on the title row only if set, with its own slip/rebaseline logic
2033
+ const activeDemandEtas = (demand.etaJournal ?? []).filter((j) => j.delivered !== true);
2034
+ const titleEtas = activeDemandEtas.length > 0
2035
+ ? activeDemandEtas
2036
+ .map((j) => evaluateEtaDeadline({
2037
+ targetStage: j.targetStage,
2038
+ ...(j.targetLabel !== undefined ? { targetLabel: j.targetLabel } : {}),
2039
+ when: j.when,
2040
+ source: j.source,
2041
+ ...(j.by !== undefined ? { by: j.by } : {}),
2042
+ ...(j.slip !== undefined ? { slip: j.slip } : {}),
2043
+ ...(j.measured !== undefined ? { measured: j.measured } : {}),
2044
+ }, undefined, {
2045
+ ...(options.now !== undefined ? { now: options.now } : {}),
2046
+ }))
2047
+ .sort((a, b) => (b.missed ? 1 : 0) - (a.missed ? 1 : 0) ||
2048
+ STAGE_RANK[a.eta.targetStage] - STAGE_RANK[b.eta.targetStage])
2049
+ .slice(0, 2)
2050
+ .map((ev) => ev.eta)
2051
+ : [];
2052
+ const titleCreatedAt = createdAtByAggregate.get(demand.id);
2053
+ const titleCapturedTitle = demand.captured === true ? (demand.ownerSummary ?? demand.raw.title) : undefined;
2054
+ rows.push({
2055
+ kind: 'demand-title',
2056
+ num: c.num,
2057
+ id: demand.id,
2058
+ ...(demand.requestedStage !== undefined ? { requestedStage: demand.requestedStage } : {}),
2059
+ etas: titleEtas,
2060
+ request: titleRequest,
2061
+ done: '—',
2062
+ todo: '—',
2063
+ decisionRefs: titleDecisionRefs,
2064
+ ...(titleSansObjetRefs.length > 0 ? { sansObjetDecisionRefs: titleSansObjetRefs } : {}),
2065
+ ...(titleBlockingRefs.length > 0 ? { blockingDecisionRefs: titleBlockingRefs } : {}),
2066
+ decisionIds: titleDecisionIds,
2067
+ ...(titleSansObjetIds.length > 0 ? { sansObjetDecisionIds: titleSansObjetIds } : {}),
2068
+ ...(titleBlockingIds.length > 0
2069
+ ? { blockingDecisionIds: titleBlockingIds, decisionBlocking: true }
2070
+ : {}),
2071
+ ...(titleCreatedAt !== undefined ? { createdAt: titleCreatedAt } : {}),
2072
+ ...(demand.captured === true
2073
+ ? {
2074
+ captured: true,
2075
+ ...(demand.captureOrigin !== undefined ? { captureOrigin: demand.captureOrigin } : {}),
2076
+ ...(titleCapturedTitle !== undefined && titleCapturedTitle.trim() !== ''
2077
+ ? { capturedTitle: cleanDisplayText(titleCapturedTitle) }
2078
+ : {}),
2079
+ capturedText: cleanDisplayText(demand.raw.text),
2080
+ ...(demand.maskedAtInscription === true ? { maskedAtInscription: true } : {}),
2081
+ }
2082
+ : {}),
2083
+ });
2084
+ c.items.forEach((lotItem, idx) => {
2085
+ const rawLotTitle = lotItem.report?.ownerSummary ?? lotItem.report?.ownerRequest ?? lotItem.title;
2086
+ const cleanedLotTitle = cleanDisplayText(rawLotTitle);
2087
+ const lotRequest = cleanedLotTitle === ''
2088
+ ? ''
2089
+ : /^↳ lot \d+ — /u.test(cleanedLotTitle)
2090
+ ? cleanedLotTitle
2091
+ : `↳ lot ${idx + 1} — ${cleanedLotTitle}`;
2092
+ rows.push(projectSingleOrLotRow({
2093
+ rowKind: 'lot',
2094
+ num: c.num,
2095
+ rowId: lotItem.id,
2096
+ parentDemandId: demand.id,
2097
+ item: lotItem,
2098
+ request: lotRequest,
2099
+ ...(lotItem.report?.requestedStage !== undefined
2100
+ ? { requestedStage: lotItem.report.requestedStage }
2101
+ : {}),
2102
+ }));
2103
+ });
2104
+ }
2105
+ else {
2106
+ const primaryItem = c.items[0];
2107
+ const report = primaryItem?.report;
2108
+ const rawRequest = c.kind === 'demand'
2109
+ ? (c.demand?.ownerSummary ??
2110
+ report?.ownerSummary ??
2111
+ report?.ownerRequest ??
2112
+ c.demand?.raw.title ??
2113
+ c.demand?.raw.text ??
2114
+ '')
2115
+ : (report?.ownerSummary ??
2116
+ report?.ownerRequest ??
2117
+ historicalItemRequests.get(primaryItem?.id ?? c.id) ??
2118
+ '');
2119
+ const request = cleanDisplayText(rawRequest);
2120
+ const requestedStage = c.demand?.requestedStage ?? report?.requestedStage;
2121
+ rows.push(projectSingleOrLotRow({
2122
+ rowKind: 'single',
2123
+ num: c.num,
2124
+ rowId: c.id,
2125
+ ...(c.demand !== undefined ? { demand: c.demand } : {}),
2126
+ ...(primaryItem !== undefined ? { item: primaryItem } : {}),
2127
+ request,
2128
+ ...(requestedStage !== undefined ? { requestedStage } : {}),
2129
+ }));
2130
+ }
2131
+ }
2132
+ const replyEligible = ownerDecisions
2133
+ .filter((d) => d.kind !== 'owner-gate' &&
2134
+ d.ref !== '' &&
2135
+ d.recommendedLetter !== '' &&
2136
+ d.recommendation !== '')
2137
+ .sort((a, b) => parseDecisionRefNumber(a.ref) - parseDecisionRefNumber(b.ref));
2138
+ const replyLine = replyEligible.length > 0
2139
+ ? `Réponse : ${replyEligible.map((d) => `${d.ref} ${d.recommendedLetter}`).join(' · ')}`
2140
+ : '';
2141
+ return {
2142
+ kind: 'owner-table-report',
2143
+ rows,
2144
+ decisions: ownerDecisions,
2145
+ replyLine,
2146
+ registeredNumbers: [...registeredNumbers].sort((a, b) => a - b),
2147
+ archivedNumbers: [...archivedNumbers].sort((a, b) => a - b),
2148
+ ...(options.policy !== undefined ? { policy: options.policy } : {}),
2149
+ ...(options.policyPath !== undefined ? { policyPath: options.policyPath } : {}),
2150
+ ...(options.defaultPolicyPath !== undefined ? { defaultPolicyPath: options.defaultPolicyPath } : {}),
2151
+ ...(options.statePolicyPath !== undefined ? { statePolicyPath: options.statePolicyPath } : {}),
2152
+ };
2153
+ }
2154
+ //# sourceMappingURL=owner-table.js.map