@things-factory/ops-master 10.1.31 → 10.1.34

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 (59) hide show
  1. package/dist-client/index.d.ts +1 -0
  2. package/dist-client/index.js +1 -0
  3. package/dist-client/index.js.map +1 -1
  4. package/dist-client/master-change-approval.d.ts +7 -0
  5. package/dist-client/master-change-approval.js +20 -0
  6. package/dist-client/master-change-approval.js.map +1 -0
  7. package/dist-client/pages/master/test-specification.d.ts +22 -85
  8. package/dist-client/pages/master/test-specification.js +190 -405
  9. package/dist-client/pages/master/test-specification.js.map +1 -1
  10. package/dist-client/tsconfig.tsbuildinfo +1 -1
  11. package/dist-server/service/asset/asset-master-resolver.js +38 -34
  12. package/dist-server/service/asset/asset-master-resolver.js.map +1 -1
  13. package/dist-server/service/equipment/equipment-master-resolver.js +54 -49
  14. package/dist-server/service/equipment/equipment-master-resolver.js.map +1 -1
  15. package/dist-server/service/index.d.ts +8 -2
  16. package/dist-server/service/index.js +8 -0
  17. package/dist-server/service/index.js.map +1 -1
  18. package/dist-server/service/location/location-master-resolver.js +34 -31
  19. package/dist-server/service/location/location-master-resolver.js.map +1 -1
  20. package/dist-server/service/master-change-policy.d.ts +23 -0
  21. package/dist-server/service/master-change-policy.js +129 -0
  22. package/dist-server/service/master-change-policy.js.map +1 -0
  23. package/dist-server/service/master-crud.js +6 -0
  24. package/dist-server/service/master-crud.js.map +1 -1
  25. package/dist-server/service/material/material-master-resolver.js +55 -51
  26. package/dist-server/service/material/material-master-resolver.js.map +1 -1
  27. package/dist-server/service/operation/operation-master-resolver.js +28 -25
  28. package/dist-server/service/operation/operation-master-resolver.js.map +1 -1
  29. package/dist-server/service/personnel/personnel-master-resolver.js +38 -34
  30. package/dist-server/service/personnel/personnel-master-resolver.js.map +1 -1
  31. package/dist-server/service/quality/nonconformance-cause-resolver.js +17 -14
  32. package/dist-server/service/quality/nonconformance-cause-resolver.js.map +1 -1
  33. package/dist-server/service/recipe/recipe-master-resolver.js +32 -28
  34. package/dist-server/service/recipe/recipe-master-resolver.js.map +1 -1
  35. package/dist-server/service/test-spec/index.d.ts +3 -2
  36. package/dist-server/service/test-spec/index.js +4 -2
  37. package/dist-server/service/test-spec/index.js.map +1 -1
  38. package/dist-server/service/test-spec/test-spec-effective-list.d.ts +32 -0
  39. package/dist-server/service/test-spec/test-spec-effective-list.js +40 -0
  40. package/dist-server/service/test-spec/test-spec-effective-list.js.map +1 -0
  41. package/dist-server/service/test-spec/test-spec-master-resolver.d.ts +4 -14
  42. package/dist-server/service/test-spec/test-spec-master-resolver.js +12 -83
  43. package/dist-server/service/test-spec/test-spec-master-resolver.js.map +1 -1
  44. package/dist-server/service/test-spec/test-spec-query.js +7 -1
  45. package/dist-server/service/test-spec/test-spec-query.js.map +1 -1
  46. package/dist-server/service/test-spec/test-spec-revision-resolver.d.ts +52 -0
  47. package/dist-server/service/test-spec/test-spec-revision-resolver.js +76 -0
  48. package/dist-server/service/test-spec/test-spec-revision-resolver.js.map +1 -0
  49. package/dist-server/service/test-spec/test-spec-revision-service.d.ts +117 -0
  50. package/dist-server/service/test-spec/test-spec-revision-service.js +519 -0
  51. package/dist-server/service/test-spec/test-spec-revision-service.js.map +1 -0
  52. package/dist-server/service/test-spec/test-spec-revision.d.ts +82 -0
  53. package/dist-server/service/test-spec/test-spec-revision.js +329 -0
  54. package/dist-server/service/test-spec/test-spec-revision.js.map +1 -0
  55. package/dist-server/service/test-spec/test-specification.d.ts +4 -0
  56. package/dist-server/service/test-spec/test-specification.js +11 -2
  57. package/dist-server/service/test-spec/test-specification.js.map +1 -1
  58. package/dist-server/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +9 -6
@@ -0,0 +1,519 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TestSpecificationRefusal = void 0;
4
+ exports.testSpecificationSubmissionHash = testSpecificationSubmissionHash;
5
+ exports.testSpecificationApprovalInput = testSpecificationApprovalInput;
6
+ exports.assertTestSpecificationApprovalInput = assertTestSpecificationApprovalInput;
7
+ exports.createTestSpecificationDraft = createTestSpecificationDraft;
8
+ exports.editTestSpecificationDraft = editTestSpecificationDraft;
9
+ exports.freezeTestSpecificationDraft = freezeTestSpecificationDraft;
10
+ exports.bindTestSpecificationApproval = bindTestSpecificationApproval;
11
+ exports.publishTestSpecificationRevision = publishTestSpecificationRevision;
12
+ exports.publishUnregulatedTestSpecification = publishUnregulatedTestSpecification;
13
+ exports.resolveTestSpecification = resolveTestSpecification;
14
+ exports.testSpecificationRevisionForBasis = testSpecificationRevisionForBasis;
15
+ exports.captureTestSpecificationBasis = captureTestSpecificationBasis;
16
+ exports.testSpecificationRevisionOverview = testSpecificationRevisionOverview;
17
+ exports.effectiveTestSpecification = effectiveTestSpecification;
18
+ const node_crypto_1 = require("node:crypto");
19
+ const typeorm_1 = require("typeorm");
20
+ const shell_1 = require("@things-factory/shell");
21
+ const master_change_policy_1 = require("../master-change-policy");
22
+ const criteria_check_1 = require("./criteria-check");
23
+ const test_specification_1 = require("./test-specification");
24
+ const test_spec_revision_1 = require("./test-spec-revision");
25
+ class TestSpecificationRefusal extends shell_1.Refusal {
26
+ constructor(code, detail) {
27
+ super(code, {}, detail ?? TEST_SPECIFICATION_REFUSALS[code] ?? 'The test specification change could not be applied.');
28
+ }
29
+ }
30
+ exports.TestSpecificationRefusal = TestSpecificationRefusal;
31
+ const TEST_SPECIFICATION_REFUSALS = {
32
+ TRANSACTION_REQUIRED: 'This change requires a transaction.',
33
+ INVALID_INSTANT: 'Enter a valid date and time including its time zone.',
34
+ INVALID_CONTENT: 'The proposed specification content is invalid.',
35
+ INVALID_CRITERIA: 'The proposed inspection criteria are invalid.',
36
+ SPECIFICATION_NOT_FOUND: 'The specification does not exist in this domain.',
37
+ REVISION_NOT_FOUND: 'The revision does not exist in this domain.',
38
+ INVALID_BASE_REVISION: 'The proposed change is based on a different revision.',
39
+ DRAFT_NOT_OWNED: 'Only the draft author can edit or submit it.',
40
+ REVISION_FROZEN: 'This submitted revision cannot be edited. Create another draft.',
41
+ DRAFT_CONFLICT: 'The draft changed. Reload it before saving.',
42
+ PLAN_CONFLICT: 'The approved schedule changed. Review and submit a new draft.',
43
+ INVALID_SUBMISSION: 'The submitted content does not match the frozen revision.',
44
+ AUTHOR_CANNOT_APPROVE: 'The author cannot approve their own change.',
45
+ RETROACTIVE_IMPACT: 'This change would alter criteria already used by recorded inspections.',
46
+ FUTURE_PLAN_CONFLICT: 'This change conflicts with an approved future schedule.',
47
+ NO_EFFECTIVE_REVISION: 'There is no published revision effective at the inspection time.',
48
+ AMBIGUOUS_EFFECTIVITY: 'More than one revision is effective at the inspection time.',
49
+ REVISION_INTEGRITY_FAILURE: 'The stored revision does not match its signed content.',
50
+ BASIS_CONFLICT: 'This inspection already has a different specification or inspection time.',
51
+ APPROVAL_LINE_REQUIRED: 'Configure an approval line before submitting this change.',
52
+ REVISION_REQUIRED: 'Change the specification through a revision draft.'
53
+ };
54
+ function refuse(code, detail) {
55
+ throw new TestSpecificationRefusal(code, detail);
56
+ }
57
+ function transaction(manager) {
58
+ if (!manager.queryRunner?.isTransactionActive)
59
+ refuse('TRANSACTION_REQUIRED');
60
+ }
61
+ /** Current reads are required after waiting for the subject lock, including MySQL REPEATABLE READ. */
62
+ function currentLock(manager) {
63
+ const driver = manager.connection.options.type;
64
+ return manager.queryRunner?.isTransactionActive && !['sqlite', 'better-sqlite3', 'sqljs'].includes(driver)
65
+ ? { lock: { mode: 'pessimistic_write' } }
66
+ : {};
67
+ }
68
+ function instant(value) {
69
+ if (!(value instanceof Date) && (typeof value !== 'string' || !/(Z|[+-]\d{2}:\d{2})$/.test(value)))
70
+ refuse('INVALID_INSTANT');
71
+ const result = new Date(value);
72
+ if (!Number.isFinite(result.getTime()))
73
+ refuse('INVALID_INSTANT');
74
+ return result;
75
+ }
76
+ function text(value, field) {
77
+ if (typeof value !== 'string' || !value.trim())
78
+ refuse('INVALID_CONTENT', field);
79
+ return value.trim();
80
+ }
81
+ /** Sorted object keys, ordered arrays, ISO instants. This is the v1 submission encoding. */
82
+ function canonical(value) {
83
+ if (value === null || typeof value !== 'object')
84
+ return JSON.stringify(value);
85
+ if (Array.isArray(value))
86
+ return '[' + value.map(canonical).join(',') + ']';
87
+ return ('{' +
88
+ Object.keys(value)
89
+ .sort()
90
+ .map(key => JSON.stringify(key) + ':' + canonical(value[key]))
91
+ .join(',') +
92
+ '}');
93
+ }
94
+ function testSpecificationSubmissionHash(revision) {
95
+ return (0, node_crypto_1.createHash)('sha256')
96
+ .update(canonical({
97
+ schemaVersion: 1,
98
+ policyId: revision.policyId,
99
+ domainId: revision.domainId,
100
+ specId: revision.specId,
101
+ baseRevisionId: revision.baseRevisionId,
102
+ baseGeneration: revision.baseGeneration,
103
+ version: revision.version,
104
+ description: revision.description,
105
+ criteria: revision.criteria,
106
+ effectiveFrom: revision.effectiveFrom.toISOString(),
107
+ reason: revision.reason
108
+ }))
109
+ .digest('hex');
110
+ }
111
+ /** Display values are a checked projection of the frozen revision, never a second editable source. */
112
+ async function testSpecificationApprovalInput(manager, domainId, revisionId) {
113
+ const draft = await revision(manager, domainId, revisionId);
114
+ if (!draft.frozenAt || draft.contentHash !== testSpecificationSubmissionHash(draft))
115
+ refuse('INVALID_SUBMISSION');
116
+ const spec = await subject(manager, domainId, draft.specId);
117
+ const base = draft.baseRevisionId ? await revision(manager, domainId, draft.baseRevisionId) : null;
118
+ const values = (row) => ({
119
+ version: row.version,
120
+ description: row.description,
121
+ criteria: row.criteria
122
+ });
123
+ return {
124
+ headline: spec.name,
125
+ reason: draft.reason,
126
+ effectiveFrom: draft.effectiveFrom.toISOString(),
127
+ before: base ? values(base) : null,
128
+ after: values(draft),
129
+ revision: {
130
+ revisionId: draft.id,
131
+ hash: draft.contentHash,
132
+ specId: draft.specId,
133
+ baseGeneration: draft.baseGeneration
134
+ }
135
+ };
136
+ }
137
+ async function assertTestSpecificationApprovalInput(manager, domainId, input) {
138
+ const reference = input?.revision;
139
+ if (typeof reference?.revisionId !== 'string')
140
+ refuse('INVALID_SUBMISSION');
141
+ const expected = await testSpecificationApprovalInput(manager, domainId, reference.revisionId);
142
+ for (const key of Object.keys(expected)) {
143
+ if (canonical(input[key]) !== canonical(expected[key]))
144
+ refuse('INVALID_SUBMISSION');
145
+ }
146
+ }
147
+ function content(input) {
148
+ const read = (0, criteria_check_1.readCriteria)(input.criteria);
149
+ if (read.read === 'failed')
150
+ refuse('INVALID_CRITERIA', read.detail);
151
+ const judged = (0, criteria_check_1.judgeCriteria)(read.criteria);
152
+ if (!judged.ok)
153
+ refuse('INVALID_CRITERIA', judged.problems.join('\n'));
154
+ // A JSON round trip makes the accepted value exactly the persisted value, not a caller-owned object.
155
+ const criteria = JSON.parse(JSON.stringify(read.criteria));
156
+ if (input.description != null && typeof input.description !== 'string')
157
+ refuse('INVALID_CONTENT', 'description');
158
+ return {
159
+ version: text(input.version, 'version'),
160
+ description: input.description ?? null,
161
+ criteria,
162
+ effectiveFrom: instant(input.effectiveFrom),
163
+ reason: text(input.reason, 'reason')
164
+ };
165
+ }
166
+ async function subject(manager, domainId, specId) {
167
+ const spec = await manager.findOne(test_specification_1.TestSpecification, {
168
+ where: { id: specId, domain: { id: domainId } },
169
+ ...currentLock(manager)
170
+ });
171
+ if (!spec)
172
+ refuse('SPECIFICATION_NOT_FOUND');
173
+ return spec;
174
+ }
175
+ async function revision(manager, domainId, revisionId, locked = true) {
176
+ const found = await manager.findOne(test_spec_revision_1.TestSpecificationRevision, {
177
+ where: { id: revisionId, domain: { id: domainId } },
178
+ ...(locked ? currentLock(manager) : {})
179
+ });
180
+ if (!found)
181
+ refuse('REVISION_NOT_FOUND');
182
+ return found;
183
+ }
184
+ /** A write lock valid on every supported SQL backend, including SQLite (no SELECT FOR UPDATE). */
185
+ async function lockSubject(manager, domainId, specId) {
186
+ transaction(manager);
187
+ const locked = await manager
188
+ .createQueryBuilder()
189
+ .update(test_specification_1.TestSpecification)
190
+ .set({ revisionLock: () => 'revision_lock + 1' })
191
+ .where({ id: specId, domain: { id: domainId } })
192
+ .execute();
193
+ if (locked.affected !== 1)
194
+ refuse('SPECIFICATION_NOT_FOUND');
195
+ return subject(manager, domainId, specId);
196
+ }
197
+ async function createTestSpecificationDraft(manager, domainId, creatorId, asked) {
198
+ transaction(manager);
199
+ const accepted = content(asked.content);
200
+ const policy = await (0, master_change_policy_1.masterChangePolicy)(manager, domainId, 'testSpecification');
201
+ let spec;
202
+ if (asked.specId) {
203
+ spec = await lockSubject(manager, domainId, asked.specId);
204
+ }
205
+ else {
206
+ spec = await manager.save(test_specification_1.TestSpecification, manager.create(test_specification_1.TestSpecification, {
207
+ domain: { id: domainId },
208
+ name: text(asked.name, 'name'),
209
+ planGeneration: 0,
210
+ revisionLock: 0,
211
+ creator: { id: creatorId },
212
+ updater: { id: creatorId }
213
+ }));
214
+ }
215
+ let baseRevisionId = null;
216
+ if (spec.planGeneration > 0) {
217
+ baseRevisionId = (await resolveTestSpecification(manager, domainId, spec.id, accepted.effectiveFrom)).revision.id;
218
+ }
219
+ if (asked.baseRevisionId && asked.baseRevisionId !== baseRevisionId)
220
+ refuse('INVALID_BASE_REVISION');
221
+ const saved = await manager.save(test_spec_revision_1.TestSpecificationRevision, manager.create(test_spec_revision_1.TestSpecificationRevision, {
222
+ ...accepted,
223
+ policy: { id: policy.id },
224
+ domain: { id: domainId },
225
+ spec: { id: spec.id },
226
+ baseRevision: baseRevisionId ? { id: baseRevisionId } : null,
227
+ baseGeneration: spec.planGeneration,
228
+ editGeneration: 0,
229
+ creator: { id: creatorId },
230
+ createdAt: new Date(),
231
+ frozenAt: null,
232
+ contentHash: null,
233
+ activityInstanceId: null
234
+ }));
235
+ return revision(manager, domainId, saved.id);
236
+ }
237
+ async function editTestSpecificationDraft(manager, domainId, actorId, revisionId, expectedEditGeneration, input) {
238
+ transaction(manager);
239
+ const accepted = content(input);
240
+ const initial = await revision(manager, domainId, revisionId, false);
241
+ const spec = await lockSubject(manager, domainId, initial.specId);
242
+ const draft = await revision(manager, domainId, revisionId);
243
+ if (draft.creatorId !== actorId)
244
+ refuse('DRAFT_NOT_OWNED');
245
+ if (draft.frozenAt)
246
+ refuse('REVISION_FROZEN');
247
+ if (draft.baseGeneration !== spec.planGeneration)
248
+ refuse('PLAN_CONFLICT');
249
+ // Moving the effective date across a scheduled boundary changes the before-image.
250
+ const baseRevisionId = spec.planGeneration > 0
251
+ ? (await resolveTestSpecification(manager, domainId, spec.id, accepted.effectiveFrom)).revision.id
252
+ : null;
253
+ const updated = await manager
254
+ .createQueryBuilder()
255
+ .update(test_spec_revision_1.TestSpecificationRevision)
256
+ .set({
257
+ ...accepted,
258
+ baseRevision: baseRevisionId ? { id: baseRevisionId } : null,
259
+ editGeneration: expectedEditGeneration + 1
260
+ })
261
+ .where({
262
+ id: revisionId,
263
+ domain: { id: domainId },
264
+ creator: { id: actorId },
265
+ editGeneration: expectedEditGeneration
266
+ })
267
+ .andWhere('frozen_at IS NULL')
268
+ .execute();
269
+ if (updated.affected !== 1)
270
+ refuse('DRAFT_CONFLICT');
271
+ return revision(manager, domainId, revisionId);
272
+ }
273
+ /** Product calls this in the same transaction as issuing its worklist approval. */
274
+ async function freezeTestSpecificationDraft(manager, domainId, actorId, revisionId, expectedEditGeneration) {
275
+ const initial = await revision(manager, domainId, revisionId, false);
276
+ const spec = await lockSubject(manager, domainId, initial.specId);
277
+ const draft = await revision(manager, domainId, revisionId);
278
+ if (draft.creatorId !== actorId)
279
+ refuse('DRAFT_NOT_OWNED');
280
+ if (draft.frozenAt)
281
+ refuse('REVISION_FROZEN');
282
+ if (draft.editGeneration !== expectedEditGeneration)
283
+ refuse('DRAFT_CONFLICT');
284
+ if (draft.baseGeneration !== spec.planGeneration)
285
+ refuse('PLAN_CONFLICT');
286
+ const policy = await (0, master_change_policy_1.masterChangePolicy)(manager, domainId, 'testSpecification');
287
+ if (draft.policyId !== policy.id)
288
+ refuse('PLAN_CONFLICT');
289
+ content(draft);
290
+ const contentHash = testSpecificationSubmissionHash(draft);
291
+ await manager.update(test_spec_revision_1.TestSpecificationRevision, { id: revisionId, domain: { id: domainId } }, { frozenAt: new Date(), contentHash });
292
+ return revision(manager, domainId, revisionId);
293
+ }
294
+ async function bindTestSpecificationApproval(manager, domainId, revisionId, activityInstanceId) {
295
+ transaction(manager);
296
+ const initial = await revision(manager, domainId, revisionId, false);
297
+ await lockSubject(manager, domainId, initial.specId);
298
+ const draft = await revision(manager, domainId, revisionId);
299
+ if (!draft.frozenAt || draft.activityInstanceId)
300
+ refuse('INVALID_SUBMISSION');
301
+ await manager.update(test_spec_revision_1.TestSpecificationRevision, { id: revisionId, domain: { id: domainId } }, { activityInstanceId: text(activityInstanceId, 'activityInstanceId') });
302
+ }
303
+ /** Internal completion callback only. Never expose this as an approved=true mutation. */
304
+ async function publishTestSpecificationRevision(manager, domainId, revisionId, decision) {
305
+ return publishRevision(manager, domainId, revisionId, {
306
+ kind: 'approved',
307
+ activityInstanceId: decision.activityInstanceId,
308
+ actorId: decision.approverId,
309
+ submissionHash: decision.submissionHash
310
+ });
311
+ }
312
+ async function publishUnregulatedTestSpecification(manager, domainId, actorId, revisionId, editGeneration) {
313
+ transaction(manager);
314
+ const initial = await revision(manager, domainId, revisionId, false);
315
+ await lockSubject(manager, domainId, initial.specId);
316
+ const policy = await (0, master_change_policy_1.masterChangePolicy)(manager, domainId, 'testSpecification');
317
+ if (policy.approvalRequired)
318
+ throw new shell_1.Refusal('MASTER_APPROVAL_REQUIRED', {}, 'This change requires product approval.');
319
+ const prior = await manager.findOneBy(test_spec_revision_1.TestSpecificationPlan, {
320
+ domain: { id: domainId },
321
+ publishedRevision: { id: revisionId },
322
+ releaseKind: 'policy'
323
+ });
324
+ if (prior) {
325
+ if (prior.publisherId !== actorId)
326
+ refuse('DRAFT_NOT_OWNED');
327
+ return prior;
328
+ }
329
+ const frozen = await freezeTestSpecificationDraft(manager, domainId, actorId, revisionId, editGeneration);
330
+ return publishRevision(manager, domainId, revisionId, { kind: 'policy', actorId, submissionHash: frozen.contentHash });
331
+ }
332
+ async function publishRevision(manager, domainId, revisionId, decision) {
333
+ const initial = await revision(manager, domainId, revisionId, false);
334
+ const spec = await lockSubject(manager, domainId, initial.specId);
335
+ const draft = await revision(manager, domainId, revisionId);
336
+ if (!draft.frozenAt ||
337
+ (decision.kind === 'approved'
338
+ ? draft.activityInstanceId !== decision.activityInstanceId
339
+ : !!draft.activityInstanceId) ||
340
+ draft.contentHash !== decision.submissionHash ||
341
+ testSpecificationSubmissionHash(draft) !== decision.submissionHash)
342
+ refuse('INVALID_SUBMISSION');
343
+ const policy = await (0, master_change_policy_1.masterChangePolicy)(manager, domainId, 'testSpecification');
344
+ if (draft.policyId !== policy.id)
345
+ refuse('PLAN_CONFLICT');
346
+ if (policy.approvalRequired !== (decision.kind === 'approved'))
347
+ throw new shell_1.Refusal('MASTER_APPROVAL_POLICY_MISMATCH', {}, 'Use the publication path required by the domain policy.');
348
+ if (decision.kind === 'approved' && draft.creatorId === decision.actorId)
349
+ refuse('AUTHOR_CANNOT_APPROVE');
350
+ text(decision.actorId, 'publisher');
351
+ const previousDecision = await manager.findOne(test_spec_revision_1.TestSpecificationPlan, {
352
+ where: { domain: { id: domainId }, publishedRevision: { id: revisionId } },
353
+ ...currentLock(manager)
354
+ });
355
+ if (previousDecision)
356
+ return previousDecision;
357
+ if (draft.baseGeneration !== spec.planGeneration)
358
+ refuse('PLAN_CONFLICT');
359
+ // Only replacement from effectiveFrom onward is supported in this slice, not arbitrary rescheduling.
360
+ if (await manager.findOne(test_spec_revision_1.TestSpecificationBasis, {
361
+ where: { domain: { id: domainId }, spec: { id: spec.id }, businessTime: (0, typeorm_1.MoreThanOrEqual)(draft.effectiveFrom) },
362
+ ...currentLock(manager)
363
+ }))
364
+ refuse('RETROACTIVE_IMPACT');
365
+ const oldPlan = await manager.findOne(test_spec_revision_1.TestSpecificationPlan, {
366
+ where: { domain: { id: domainId }, spec: { id: spec.id }, generation: spec.planGeneration },
367
+ ...currentLock(manager)
368
+ });
369
+ if (spec.planGeneration > 0 && !oldPlan)
370
+ refuse('PLAN_CONFLICT');
371
+ const oldSegments = oldPlan
372
+ ? await manager.find(test_spec_revision_1.TestSpecificationSegment, {
373
+ where: { domain: { id: domainId }, spec: { id: spec.id }, plan: { id: oldPlan.id } },
374
+ order: { validFrom: 'ASC' },
375
+ ...currentLock(manager)
376
+ })
377
+ : [];
378
+ // Do not silently erase an already approved future appointment.
379
+ if (oldSegments.some(segment => segment.validFrom >= draft.effectiveFrom))
380
+ refuse('FUTURE_PLAN_CONFLICT');
381
+ const recordedAt = new Date();
382
+ const plan = await manager.save(test_spec_revision_1.TestSpecificationPlan, manager.create(test_spec_revision_1.TestSpecificationPlan, {
383
+ domain: { id: domainId },
384
+ spec: { id: spec.id },
385
+ generation: spec.planGeneration + 1,
386
+ recordedAt,
387
+ activityInstanceId: decision.activityInstanceId ?? null,
388
+ submissionHash: decision.submissionHash,
389
+ approver: decision.kind === 'approved' ? { id: decision.actorId } : null,
390
+ publisher: { id: decision.actorId },
391
+ releaseKind: decision.kind,
392
+ publishedRevision: { id: revisionId },
393
+ policy: { id: policy.id }
394
+ }));
395
+ for (const old of oldSegments) {
396
+ await manager.save(test_spec_revision_1.TestSpecificationSegment, manager.create(test_spec_revision_1.TestSpecificationSegment, {
397
+ domain: { id: domainId },
398
+ spec: { id: spec.id },
399
+ plan: { id: plan.id },
400
+ revision: { id: old.revisionId },
401
+ validFrom: old.validFrom,
402
+ validTo: !old.validTo || old.validTo > draft.effectiveFrom ? draft.effectiveFrom : old.validTo
403
+ }));
404
+ }
405
+ await manager.save(test_spec_revision_1.TestSpecificationSegment, manager.create(test_spec_revision_1.TestSpecificationSegment, {
406
+ domain: { id: domainId },
407
+ spec: { id: spec.id },
408
+ plan: { id: plan.id },
409
+ revision: { id: revisionId },
410
+ validFrom: draft.effectiveFrom,
411
+ validTo: null
412
+ }));
413
+ const advanced = await manager.update(test_specification_1.TestSpecification, { id: spec.id, domain: { id: domainId }, planGeneration: spec.planGeneration }, { planGeneration: plan.generation });
414
+ if (advanced.affected !== 1)
415
+ refuse('PLAN_CONFLICT');
416
+ return plan;
417
+ }
418
+ async function resolveTestSpecification(manager, domainId, specId, businessTime, knownAt = new Date()) {
419
+ const at = instant(businessTime);
420
+ const known = instant(knownAt);
421
+ const plan = await manager.findOne(test_spec_revision_1.TestSpecificationPlan, {
422
+ where: { domain: { id: domainId }, spec: { id: specId }, recordedAt: (0, typeorm_1.LessThanOrEqual)(known) },
423
+ order: { generation: 'DESC' },
424
+ ...currentLock(manager)
425
+ });
426
+ if (!plan)
427
+ refuse('NO_EFFECTIVE_REVISION');
428
+ const query = manager
429
+ .createQueryBuilder(test_spec_revision_1.TestSpecificationSegment, 'segment')
430
+ .where({ domain: { id: domainId }, spec: { id: specId }, plan: { id: plan.id } })
431
+ .andWhere('segment.validFrom <= :at', { at })
432
+ .andWhere('(segment.validTo IS NULL OR segment.validTo > :at)', { at });
433
+ if (currentLock(manager).lock)
434
+ query.setLock('pessimistic_write');
435
+ const segments = await query.getMany();
436
+ if (segments.length !== 1)
437
+ refuse(segments.length ? 'AMBIGUOUS_EFFECTIVITY' : 'NO_EFFECTIVE_REVISION');
438
+ const selected = await revision(manager, domainId, segments[0].revisionId);
439
+ if (!selected.frozenAt || selected.contentHash !== testSpecificationSubmissionHash(selected))
440
+ refuse('REVISION_INTEGRITY_FAILURE');
441
+ return { revision: selected, plan, segment: segments[0] };
442
+ }
443
+ /** Replay reads verify the captured digest too, not only the currently effective schedule. */
444
+ async function testSpecificationRevisionForBasis(manager, domainId, basis) {
445
+ if (basis.domainId !== domainId)
446
+ refuse('BASIS_CONFLICT');
447
+ const selected = await revision(manager, domainId, basis.revisionId);
448
+ if (selected.specId !== basis.specId || !selected.frozenAt || selected.contentHash !== basis.contentHash || testSpecificationSubmissionHash(selected) !== basis.contentHash) {
449
+ refuse('REVISION_INTEGRITY_FAILURE');
450
+ }
451
+ return selected;
452
+ }
453
+ /** Must run inside the transaction that writes the inspection result. */
454
+ async function captureTestSpecificationBasis(manager, domainId, specId, recordKey, businessTime) {
455
+ const at = instant(businessTime);
456
+ await lockSubject(manager, domainId, specId);
457
+ const existing = await manager.findOne(test_spec_revision_1.TestSpecificationBasis, {
458
+ where: { domain: { id: domainId }, recordKey },
459
+ ...currentLock(manager)
460
+ });
461
+ if (existing) {
462
+ if (existing.specId !== specId || existing.businessTime.getTime() !== at.getTime())
463
+ refuse('BASIS_CONFLICT');
464
+ await testSpecificationRevisionForBasis(manager, domainId, existing);
465
+ return existing;
466
+ }
467
+ const resolvedAt = new Date();
468
+ const selected = await resolveTestSpecification(manager, domainId, specId, at, resolvedAt);
469
+ const saved = await manager.save(test_spec_revision_1.TestSpecificationBasis, manager.create(test_spec_revision_1.TestSpecificationBasis, {
470
+ domain: { id: domainId },
471
+ spec: { id: specId },
472
+ recordKey: text(recordKey, 'recordKey'),
473
+ businessTime: at,
474
+ resolvedAt,
475
+ revision: { id: selected.revision.id },
476
+ contentHash: selected.revision.contentHash,
477
+ plan: { id: selected.plan.id }
478
+ }));
479
+ return manager.findOneByOrFail(test_spec_revision_1.TestSpecificationBasis, { id: saved.id, domain: { id: domainId } });
480
+ }
481
+ async function testSpecificationRevisionOverview(manager, domainId, specId, at = new Date()) {
482
+ const spec = await subject(manager, domainId, specId);
483
+ const revisions = await manager.find(test_spec_revision_1.TestSpecificationRevision, {
484
+ where: { domain: { id: domainId }, spec: { id: specId } },
485
+ order: { createdAt: 'ASC', id: 'ASC' }
486
+ });
487
+ const plan = await manager.findOne(test_spec_revision_1.TestSpecificationPlan, {
488
+ where: { domain: { id: domainId }, spec: { id: specId }, generation: spec.planGeneration }
489
+ });
490
+ const schedule = plan
491
+ ? await manager.find(test_spec_revision_1.TestSpecificationSegment, {
492
+ where: { domain: { id: domainId }, spec: { id: specId }, plan: { id: plan.id } },
493
+ order: { validFrom: 'ASC' }
494
+ })
495
+ : [];
496
+ return {
497
+ specId,
498
+ name: spec.name,
499
+ generation: spec.planGeneration,
500
+ at: at.toISOString(),
501
+ schedule: schedule.map(segment => ({
502
+ ...segment,
503
+ state: segment.validFrom > at ? 'scheduled' : segment.validTo && segment.validTo <= at ? 'expired' : 'current'
504
+ })),
505
+ revisions: revisions.map(item => ({ ...item, state: item.frozenAt ? 'frozen' : 'draft' }))
506
+ };
507
+ }
508
+ /** Read-time projection, never a clock-driven rewrite of the identity row. */
509
+ async function effectiveTestSpecification(manager, domainId, spec, at = new Date()) {
510
+ const selected = await resolveTestSpecification(manager, domainId, spec.id, at);
511
+ return Object.assign(new test_specification_1.TestSpecification(), spec, {
512
+ version: selected.revision.version,
513
+ description: selected.revision.description,
514
+ criteria: selected.revision.criteria,
515
+ effectiveStart: selected.segment.validFrom,
516
+ effectiveEnd: selected.segment.validTo ?? undefined
517
+ });
518
+ }
519
+ //# sourceMappingURL=test-spec-revision-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-spec-revision-service.js","sourceRoot":"","sources":["../../../server/service/test-spec/test-spec-revision-service.ts"],"names":[],"mappings":";;;AAkFA,0EAkBC;AAGD,wEAuBC;AAED,oFAWC;AAsDD,oEAgDC;AAED,gEAuCC;AAGD,oEAwBC;AAED,sEAgBC;AAGD,4EAYC;AAED,kFAwBC;AAwGD,4DA2BC;AAGD,8EAOC;AAGD,sEAkCC;AAED,8EA+BC;AAGD,gEAcC;AAplBD,6CAAwC;AACxC,qCAAyE;AACzE,iDAA+C;AAC/C,kEAA4D;AAC5D,qDAA8D;AAC9D,6DAAwD;AACxD,6DAK6B;AAE7B,MAAa,wBAAyB,SAAQ,eAAO;IACnD,YAAY,IAAY,EAAE,MAAe;QACvC,KAAK,CACH,IAAI,EACJ,EAAE,EACF,MAAM,IAAI,2BAA2B,CAAC,IAAI,CAAC,IAAI,qDAAqD,CACrG,CAAA;IACH,CAAC;CACF;AARD,4DAQC;AACD,MAAM,2BAA2B,GAA2B;IAC1D,oBAAoB,EAAE,qCAAqC;IAC3D,eAAe,EAA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,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;SAC/G,CAAC,CAAC;QACH,SAAS,EAAE,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;KAC3F,CAAA;AACH,CAAC;AAED,8EAA8E;AACvE,KAAK,UAAU,0BAA0B,CAC9C,OAAsB,EACtB,QAAgB,EAChB,IAAuB,EACvB,EAAE,GAAG,IAAI,IAAI,EAAE;IAEf,MAAM,QAAQ,GAAG,MAAM,wBAAwB,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;IAC/E,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,sCAAiB,EAAE,EAAE,IAAI,EAAE;QAClD,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,OAAO;QAClC,WAAW,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW;QAC1C,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,QAAQ;QACpC,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,SAAS;QAC1C,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO,IAAI,SAAS;KACpD,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { createHash } from 'node:crypto'\nimport { EntityManager, LessThanOrEqual, MoreThanOrEqual } from 'typeorm'\nimport { Refusal } from '@things-factory/shell'\nimport { masterChangePolicy } from '../master-change-policy'\nimport { judgeCriteria, readCriteria } from './criteria-check'\nimport { TestSpecification } from './test-specification'\nimport {\n TestSpecificationBasis,\n TestSpecificationPlan,\n TestSpecificationRevision,\n TestSpecificationSegment\n} from './test-spec-revision'\n\nexport class TestSpecificationRefusal extends Refusal {\n constructor(code: string, detail?: string) {\n super(\n code,\n {},\n detail ?? TEST_SPECIFICATION_REFUSALS[code] ?? 'The test specification change could not be applied.'\n )\n }\n}\nconst TEST_SPECIFICATION_REFUSALS: Record<string, string> = {\n TRANSACTION_REQUIRED: 'This change requires a transaction.',\n INVALID_INSTANT: 'Enter a valid date and time including its time zone.',\n INVALID_CONTENT: 'The proposed specification content is invalid.',\n INVALID_CRITERIA: 'The proposed inspection criteria are invalid.',\n SPECIFICATION_NOT_FOUND: 'The specification does not exist in this domain.',\n REVISION_NOT_FOUND: 'The revision does not exist in this domain.',\n INVALID_BASE_REVISION: 'The proposed change is based on a different revision.',\n DRAFT_NOT_OWNED: 'Only the draft author can edit or submit it.',\n REVISION_FROZEN: 'This submitted revision cannot be edited. Create another draft.',\n DRAFT_CONFLICT: 'The draft changed. Reload it before saving.',\n PLAN_CONFLICT: 'The approved schedule changed. Review and submit a new draft.',\n INVALID_SUBMISSION: 'The submitted content does not match the frozen revision.',\n AUTHOR_CANNOT_APPROVE: 'The author cannot approve their own change.',\n RETROACTIVE_IMPACT: 'This change would alter criteria already used by recorded inspections.',\n FUTURE_PLAN_CONFLICT: 'This change conflicts with an approved future schedule.',\n NO_EFFECTIVE_REVISION: 'There is no published revision effective at the inspection time.',\n AMBIGUOUS_EFFECTIVITY: 'More than one revision is effective at the inspection time.',\n REVISION_INTEGRITY_FAILURE: 'The stored revision does not match its signed content.',\n BASIS_CONFLICT: 'This inspection already has a different specification or inspection time.',\n APPROVAL_LINE_REQUIRED: 'Configure an approval line before submitting this change.',\n REVISION_REQUIRED: 'Change the specification through a revision draft.'\n}\nfunction refuse(code: string, detail?: string): never {\n throw new TestSpecificationRefusal(code, detail)\n}\nfunction transaction(manager: EntityManager) {\n if (!manager.queryRunner?.isTransactionActive) refuse('TRANSACTION_REQUIRED')\n}\n/** Current reads are required after waiting for the subject lock, including MySQL REPEATABLE READ. */\nfunction currentLock(manager: EntityManager) {\n const driver = manager.connection.options.type\n return manager.queryRunner?.isTransactionActive && !['sqlite', 'better-sqlite3', 'sqljs'].includes(driver)\n ? { lock: { mode: 'pessimistic_write' as const } }\n : {}\n}\nfunction instant(value: Date | string): Date {\n if (!(value instanceof Date) && (typeof value !== 'string' || !/(Z|[+-]\\d{2}:\\d{2})$/.test(value)))\n refuse('INVALID_INSTANT')\n const result = new Date(value)\n if (!Number.isFinite(result.getTime())) refuse('INVALID_INSTANT')\n return result\n}\nfunction text(value: unknown, field: string): string {\n if (typeof value !== 'string' || !value.trim()) refuse('INVALID_CONTENT', field)\n return value.trim()\n}\n/** Sorted object keys, ordered arrays, ISO instants. This is the v1 submission encoding. */\nfunction canonical(value: any): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']'\n return (\n '{' +\n Object.keys(value)\n .sort()\n .map(key => JSON.stringify(key) + ':' + canonical(value[key]))\n .join(',') +\n '}'\n )\n}\nexport function testSpecificationSubmissionHash(revision: TestSpecificationRevision): string {\n return createHash('sha256')\n .update(\n canonical({\n schemaVersion: 1,\n policyId: revision.policyId,\n domainId: revision.domainId,\n specId: revision.specId,\n baseRevisionId: revision.baseRevisionId,\n baseGeneration: revision.baseGeneration,\n version: revision.version,\n description: revision.description,\n criteria: revision.criteria,\n effectiveFrom: revision.effectiveFrom.toISOString(),\n reason: revision.reason\n })\n )\n .digest('hex')\n}\n\n/** Display values are a checked projection of the frozen revision, never a second editable source. */\nexport async function testSpecificationApprovalInput(manager: EntityManager, domainId: string, revisionId: string) {\n const draft = await revision(manager, domainId, revisionId)\n if (!draft.frozenAt || draft.contentHash !== testSpecificationSubmissionHash(draft)) refuse('INVALID_SUBMISSION')\n const spec = await subject(manager, domainId, draft.specId)\n const base = draft.baseRevisionId ? await revision(manager, domainId, draft.baseRevisionId) : null\n const values = (row: TestSpecificationRevision) => ({\n version: row.version,\n description: row.description,\n criteria: row.criteria\n })\n return {\n headline: spec.name,\n reason: draft.reason,\n effectiveFrom: draft.effectiveFrom.toISOString(),\n before: base ? values(base) : null,\n after: values(draft),\n revision: {\n revisionId: draft.id,\n hash: draft.contentHash,\n specId: draft.specId,\n baseGeneration: draft.baseGeneration\n }\n }\n}\n\nexport async function assertTestSpecificationApprovalInput(\n manager: EntityManager,\n domainId: string,\n input: Record<string, unknown>\n) {\n const reference = input?.revision as { revisionId?: string }\n if (typeof reference?.revisionId !== 'string') refuse('INVALID_SUBMISSION')\n const expected = await testSpecificationApprovalInput(manager, domainId, reference.revisionId)\n for (const key of Object.keys(expected)) {\n if (canonical(input[key]) !== canonical(expected[key])) refuse('INVALID_SUBMISSION')\n }\n}\n\nexport interface TestSpecificationDraftContent {\n version: string\n description?: string\n criteria: unknown\n effectiveFrom: Date | string\n reason: string\n}\nfunction content(input: TestSpecificationDraftContent) {\n const read = readCriteria(input.criteria)\n if (read.read === 'failed') refuse('INVALID_CRITERIA', read.detail)\n const judged = judgeCriteria(read.criteria)\n if (!judged.ok) refuse('INVALID_CRITERIA', judged.problems.join('\\n'))\n // A JSON round trip makes the accepted value exactly the persisted value, not a caller-owned object.\n const criteria = JSON.parse(JSON.stringify(read.criteria))\n if (input.description != null && typeof input.description !== 'string') refuse('INVALID_CONTENT', 'description')\n return {\n version: text(input.version, 'version'),\n description: input.description ?? null,\n criteria,\n effectiveFrom: instant(input.effectiveFrom),\n reason: text(input.reason, 'reason')\n }\n}\nasync function subject(manager: EntityManager, domainId: string, specId: string) {\n const spec = await manager.findOne(TestSpecification, {\n where: { id: specId, domain: { id: domainId } },\n ...currentLock(manager)\n })\n if (!spec) refuse('SPECIFICATION_NOT_FOUND')\n return spec\n}\nasync function revision(manager: EntityManager, domainId: string, revisionId: string, locked = true) {\n const found = await manager.findOne(TestSpecificationRevision, {\n where: { id: revisionId, domain: { id: domainId } },\n ...(locked ? currentLock(manager) : {})\n })\n if (!found) refuse('REVISION_NOT_FOUND')\n return found\n}\n/** A write lock valid on every supported SQL backend, including SQLite (no SELECT FOR UPDATE). */\nasync function lockSubject(manager: EntityManager, domainId: string, specId: string) {\n transaction(manager)\n const locked = await manager\n .createQueryBuilder()\n .update(TestSpecification)\n .set({ revisionLock: () => 'revision_lock + 1' })\n .where({ id: specId, domain: { id: domainId } })\n .execute()\n if (locked.affected !== 1) refuse('SPECIFICATION_NOT_FOUND')\n return subject(manager, domainId, specId)\n}\n\nexport async function createTestSpecificationDraft(\n manager: EntityManager,\n domainId: string,\n creatorId: string,\n asked: { specId?: string; name?: string; baseRevisionId?: string; content: TestSpecificationDraftContent }\n) {\n transaction(manager)\n const accepted = content(asked.content)\n const policy = await masterChangePolicy(manager, domainId, 'testSpecification')\n let spec: TestSpecification\n if (asked.specId) {\n spec = await lockSubject(manager, domainId, asked.specId)\n } else {\n spec = await manager.save(\n TestSpecification,\n manager.create(TestSpecification, {\n domain: { id: domainId },\n name: text(asked.name, 'name'),\n planGeneration: 0,\n revisionLock: 0,\n creator: { id: creatorId },\n updater: { id: creatorId }\n })\n )\n }\n let baseRevisionId: string | null = null\n if (spec.planGeneration > 0) {\n baseRevisionId = (await resolveTestSpecification(manager, domainId, spec.id, accepted.effectiveFrom)).revision.id\n }\n if (asked.baseRevisionId && asked.baseRevisionId !== baseRevisionId) refuse('INVALID_BASE_REVISION')\n const saved = await manager.save(\n TestSpecificationRevision,\n manager.create(TestSpecificationRevision, {\n ...accepted,\n policy: { id: policy.id },\n domain: { id: domainId },\n spec: { id: spec.id },\n baseRevision: baseRevisionId ? { id: baseRevisionId } : null,\n baseGeneration: spec.planGeneration,\n editGeneration: 0,\n creator: { id: creatorId },\n createdAt: new Date(),\n frozenAt: null,\n contentHash: null,\n activityInstanceId: null\n })\n )\n return revision(manager, domainId, saved.id)\n}\n\nexport async function editTestSpecificationDraft(\n manager: EntityManager,\n domainId: string,\n actorId: string,\n revisionId: string,\n expectedEditGeneration: number,\n input: TestSpecificationDraftContent\n) {\n transaction(manager)\n const accepted = content(input)\n const initial = await revision(manager, domainId, revisionId, false)\n const spec = await lockSubject(manager, domainId, initial.specId)\n const draft = await revision(manager, domainId, revisionId)\n if (draft.creatorId !== actorId) refuse('DRAFT_NOT_OWNED')\n if (draft.frozenAt) refuse('REVISION_FROZEN')\n if (draft.baseGeneration !== spec.planGeneration) refuse('PLAN_CONFLICT')\n // Moving the effective date across a scheduled boundary changes the before-image.\n const baseRevisionId =\n spec.planGeneration > 0\n ? (await resolveTestSpecification(manager, domainId, spec.id, accepted.effectiveFrom)).revision.id\n : null\n const updated = await manager\n .createQueryBuilder()\n .update(TestSpecificationRevision)\n .set({\n ...accepted,\n baseRevision: baseRevisionId ? { id: baseRevisionId } : null,\n editGeneration: expectedEditGeneration + 1\n })\n .where({\n id: revisionId,\n domain: { id: domainId },\n creator: { id: actorId },\n editGeneration: expectedEditGeneration\n })\n .andWhere('frozen_at IS NULL')\n .execute()\n if (updated.affected !== 1) refuse('DRAFT_CONFLICT')\n return revision(manager, domainId, revisionId)\n}\n\n/** Product calls this in the same transaction as issuing its worklist approval. */\nexport async function freezeTestSpecificationDraft(\n manager: EntityManager,\n domainId: string,\n actorId: string,\n revisionId: string,\n expectedEditGeneration: number\n) {\n const initial = await revision(manager, domainId, revisionId, false)\n const spec = await lockSubject(manager, domainId, initial.specId)\n const draft = await revision(manager, domainId, revisionId)\n if (draft.creatorId !== actorId) refuse('DRAFT_NOT_OWNED')\n if (draft.frozenAt) refuse('REVISION_FROZEN')\n if (draft.editGeneration !== expectedEditGeneration) refuse('DRAFT_CONFLICT')\n if (draft.baseGeneration !== spec.planGeneration) refuse('PLAN_CONFLICT')\n const policy = await masterChangePolicy(manager, domainId, 'testSpecification')\n if (draft.policyId !== policy.id) refuse('PLAN_CONFLICT')\n content(draft)\n const contentHash = testSpecificationSubmissionHash(draft)\n await manager.update(\n TestSpecificationRevision,\n { id: revisionId, domain: { id: domainId } },\n { frozenAt: new Date(), contentHash }\n )\n return revision(manager, domainId, revisionId)\n}\n\nexport async function bindTestSpecificationApproval(\n manager: EntityManager,\n domainId: string,\n revisionId: string,\n activityInstanceId: string\n) {\n transaction(manager)\n const initial = await revision(manager, domainId, revisionId, false)\n await lockSubject(manager, domainId, initial.specId)\n const draft = await revision(manager, domainId, revisionId)\n if (!draft.frozenAt || draft.activityInstanceId) refuse('INVALID_SUBMISSION')\n await manager.update(\n TestSpecificationRevision,\n { id: revisionId, domain: { id: domainId } },\n { activityInstanceId: text(activityInstanceId, 'activityInstanceId') }\n )\n}\n\n/** Internal completion callback only. Never expose this as an approved=true mutation. */\nexport async function publishTestSpecificationRevision(\n manager: EntityManager,\n domainId: string,\n revisionId: string,\n decision: { activityInstanceId: string; approverId: string; submissionHash: string }\n) {\n return publishRevision(manager, domainId, revisionId, {\n kind: 'approved',\n activityInstanceId: decision.activityInstanceId,\n actorId: decision.approverId,\n submissionHash: decision.submissionHash\n })\n}\n\nexport async function publishUnregulatedTestSpecification(\n manager: EntityManager,\n domainId: string,\n actorId: string,\n revisionId: string,\n editGeneration: number\n) {\n transaction(manager)\n const initial = await revision(manager, domainId, revisionId, false)\n await lockSubject(manager, domainId, initial.specId)\n const policy = await masterChangePolicy(manager, domainId, 'testSpecification')\n if (policy.approvalRequired)\n throw new Refusal('MASTER_APPROVAL_REQUIRED', {}, 'This change requires product approval.')\n const prior = await manager.findOneBy(TestSpecificationPlan, {\n domain: { id: domainId },\n publishedRevision: { id: revisionId },\n releaseKind: 'policy'\n })\n if (prior) {\n if (prior.publisherId !== actorId) refuse('DRAFT_NOT_OWNED')\n return prior\n }\n const frozen = await freezeTestSpecificationDraft(manager, domainId, actorId, revisionId, editGeneration)\n return publishRevision(manager, domainId, revisionId, { kind: 'policy', actorId, submissionHash: frozen.contentHash })\n}\n\nasync function publishRevision(\n manager: EntityManager,\n domainId: string,\n revisionId: string,\n decision: { kind: 'approved' | 'policy'; activityInstanceId?: string; actorId: string; submissionHash: string }\n) {\n const initial = await revision(manager, domainId, revisionId, false)\n const spec = await lockSubject(manager, domainId, initial.specId)\n const draft = await revision(manager, domainId, revisionId)\n if (\n !draft.frozenAt ||\n (decision.kind === 'approved'\n ? draft.activityInstanceId !== decision.activityInstanceId\n : !!draft.activityInstanceId) ||\n draft.contentHash !== decision.submissionHash ||\n testSpecificationSubmissionHash(draft) !== decision.submissionHash\n )\n refuse('INVALID_SUBMISSION')\n const policy = await masterChangePolicy(manager, domainId, 'testSpecification')\n if (draft.policyId !== policy.id) refuse('PLAN_CONFLICT')\n if (policy.approvalRequired !== (decision.kind === 'approved'))\n throw new Refusal('MASTER_APPROVAL_POLICY_MISMATCH', {}, 'Use the publication path required by the domain policy.')\n if (decision.kind === 'approved' && draft.creatorId === decision.actorId) refuse('AUTHOR_CANNOT_APPROVE')\n text(decision.actorId, 'publisher')\n const previousDecision = await manager.findOne(TestSpecificationPlan, {\n where: { domain: { id: domainId }, publishedRevision: { id: revisionId } },\n ...currentLock(manager)\n })\n if (previousDecision) return previousDecision\n if (draft.baseGeneration !== spec.planGeneration) refuse('PLAN_CONFLICT')\n // Only replacement from effectiveFrom onward is supported in this slice, not arbitrary rescheduling.\n if (\n await manager.findOne(TestSpecificationBasis, {\n where: { domain: { id: domainId }, spec: { id: spec.id }, businessTime: MoreThanOrEqual(draft.effectiveFrom) },\n ...currentLock(manager)\n })\n )\n refuse('RETROACTIVE_IMPACT')\n const oldPlan = await manager.findOne(TestSpecificationPlan, {\n where: { domain: { id: domainId }, spec: { id: spec.id }, generation: spec.planGeneration },\n ...currentLock(manager)\n })\n if (spec.planGeneration > 0 && !oldPlan) refuse('PLAN_CONFLICT')\n const oldSegments = oldPlan\n ? await manager.find(TestSpecificationSegment, {\n where: { domain: { id: domainId }, spec: { id: spec.id }, plan: { id: oldPlan.id } },\n order: { validFrom: 'ASC' },\n ...currentLock(manager)\n })\n : []\n // Do not silently erase an already approved future appointment.\n if (oldSegments.some(segment => segment.validFrom >= draft.effectiveFrom)) refuse('FUTURE_PLAN_CONFLICT')\n const recordedAt = new Date()\n const plan = await manager.save(\n TestSpecificationPlan,\n manager.create(TestSpecificationPlan, {\n domain: { id: domainId },\n spec: { id: spec.id },\n generation: spec.planGeneration + 1,\n recordedAt,\n activityInstanceId: decision.activityInstanceId ?? null,\n submissionHash: decision.submissionHash,\n approver: decision.kind === 'approved' ? { id: decision.actorId } : null,\n publisher: { id: decision.actorId },\n releaseKind: decision.kind,\n publishedRevision: { id: revisionId },\n policy: { id: policy.id }\n })\n )\n for (const old of oldSegments) {\n await manager.save(\n TestSpecificationSegment,\n manager.create(TestSpecificationSegment, {\n domain: { id: domainId },\n spec: { id: spec.id },\n plan: { id: plan.id },\n revision: { id: old.revisionId },\n validFrom: old.validFrom,\n validTo: !old.validTo || old.validTo > draft.effectiveFrom ? draft.effectiveFrom : old.validTo\n })\n )\n }\n await manager.save(\n TestSpecificationSegment,\n manager.create(TestSpecificationSegment, {\n domain: { id: domainId },\n spec: { id: spec.id },\n plan: { id: plan.id },\n revision: { id: revisionId },\n validFrom: draft.effectiveFrom,\n validTo: null\n })\n )\n const advanced = await manager.update(\n TestSpecification,\n { id: spec.id, domain: { id: domainId }, planGeneration: spec.planGeneration },\n { planGeneration: plan.generation }\n )\n if (advanced.affected !== 1) refuse('PLAN_CONFLICT')\n return plan\n}\n\nexport async function resolveTestSpecification(\n manager: EntityManager,\n domainId: string,\n specId: string,\n businessTime: Date | string,\n knownAt: Date | string = new Date()\n) {\n const at = instant(businessTime)\n const known = instant(knownAt)\n const plan = await manager.findOne(TestSpecificationPlan, {\n where: { domain: { id: domainId }, spec: { id: specId }, recordedAt: LessThanOrEqual(known) },\n order: { generation: 'DESC' },\n ...currentLock(manager)\n })\n if (!plan) refuse('NO_EFFECTIVE_REVISION')\n const query = manager\n .createQueryBuilder(TestSpecificationSegment, 'segment')\n .where({ domain: { id: domainId }, spec: { id: specId }, plan: { id: plan.id } })\n .andWhere('segment.validFrom <= :at', { at })\n .andWhere('(segment.validTo IS NULL OR segment.validTo > :at)', { at })\n if (currentLock(manager).lock) query.setLock('pessimistic_write')\n const segments = await query.getMany()\n if (segments.length !== 1) refuse(segments.length ? 'AMBIGUOUS_EFFECTIVITY' : 'NO_EFFECTIVE_REVISION')\n const selected = await revision(manager, domainId, segments[0].revisionId)\n if (!selected.frozenAt || selected.contentHash !== testSpecificationSubmissionHash(selected))\n refuse('REVISION_INTEGRITY_FAILURE')\n return { revision: selected, plan, segment: segments[0] }\n}\n\n/** Replay reads verify the captured digest too, not only the currently effective schedule. */\nexport async function testSpecificationRevisionForBasis(manager: EntityManager, domainId: string, basis: TestSpecificationBasis) {\n if (basis.domainId !== domainId) refuse('BASIS_CONFLICT')\n const selected = await revision(manager, domainId, basis.revisionId)\n if (selected.specId !== basis.specId || !selected.frozenAt || selected.contentHash !== basis.contentHash || testSpecificationSubmissionHash(selected) !== basis.contentHash) {\n refuse('REVISION_INTEGRITY_FAILURE')\n }\n return selected\n}\n\n/** Must run inside the transaction that writes the inspection result. */\nexport async function captureTestSpecificationBasis(\n manager: EntityManager,\n domainId: string,\n specId: string,\n recordKey: string,\n businessTime: Date | string\n) {\n const at = instant(businessTime)\n await lockSubject(manager, domainId, specId)\n const existing = await manager.findOne(TestSpecificationBasis, {\n where: { domain: { id: domainId }, recordKey },\n ...currentLock(manager)\n })\n if (existing) {\n if (existing.specId !== specId || existing.businessTime.getTime() !== at.getTime()) refuse('BASIS_CONFLICT')\n await testSpecificationRevisionForBasis(manager, domainId, existing)\n return existing\n }\n const resolvedAt = new Date()\n const selected = await resolveTestSpecification(manager, domainId, specId, at, resolvedAt)\n const saved = await manager.save(\n TestSpecificationBasis,\n manager.create(TestSpecificationBasis, {\n domain: { id: domainId },\n spec: { id: specId },\n recordKey: text(recordKey, 'recordKey'),\n businessTime: at,\n resolvedAt,\n revision: { id: selected.revision.id },\n contentHash: selected.revision.contentHash,\n plan: { id: selected.plan.id }\n })\n )\n return manager.findOneByOrFail(TestSpecificationBasis, { id: saved.id, domain: { id: domainId } })\n}\n\nexport async function testSpecificationRevisionOverview(\n manager: EntityManager,\n domainId: string,\n specId: string,\n at = new Date()\n) {\n const spec = await subject(manager, domainId, specId)\n const revisions = await manager.find(TestSpecificationRevision, {\n where: { domain: { id: domainId }, spec: { id: specId } },\n order: { createdAt: 'ASC', id: 'ASC' }\n })\n const plan = await manager.findOne(TestSpecificationPlan, {\n where: { domain: { id: domainId }, spec: { id: specId }, generation: spec.planGeneration }\n })\n const schedule = plan\n ? await manager.find(TestSpecificationSegment, {\n where: { domain: { id: domainId }, spec: { id: specId }, plan: { id: plan.id } },\n order: { validFrom: 'ASC' }\n })\n : []\n return {\n specId,\n name: spec.name,\n generation: spec.planGeneration,\n at: at.toISOString(),\n schedule: schedule.map(segment => ({\n ...segment,\n state: segment.validFrom > at ? 'scheduled' : segment.validTo && segment.validTo <= at ? 'expired' : 'current'\n })),\n revisions: revisions.map(item => ({ ...item, state: item.frozenAt ? 'frozen' : 'draft' }))\n }\n}\n\n/** Read-time projection, never a clock-driven rewrite of the identity row. */\nexport async function effectiveTestSpecification(\n manager: EntityManager,\n domainId: string,\n spec: TestSpecification,\n at = new Date()\n) {\n const selected = await resolveTestSpecification(manager, domainId, spec.id, at)\n return Object.assign(new TestSpecification(), spec, {\n version: selected.revision.version,\n description: selected.revision.description,\n criteria: selected.revision.criteria,\n effectiveStart: selected.segment.validFrom,\n effectiveEnd: selected.segment.validTo ?? undefined\n })\n}\n"]}