Repository navigation
Expand file tree
/
Copy pathcli.test.mjs
More file actions
4791 lines (4447 loc) · 221 KB
/
Copy pathcli.test.mjs
File metadata and controls
4791 lines (4447 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { extractSvgs, parseXml } from './helpers/xml.mjs';
import { bipartiteArchitectureSpec } from './helpers/dense-fixture.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..', 'archify');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-cli-'));
const cli = path.join(skillRoot, 'bin/archify.mjs');
test.afterEach(() => {
fs.rmSync(path.join(tmp, '.archify-delivery-lock.json'), { force: true });
});
function run(args, options = {}) {
return spawnSync(process.execPath, [cli, ...args], {
cwd: options.cwd || skillRoot,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
env: options.env || process.env,
});
}
function sha256(file) {
return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
}
function deliverySidecarPath(file, suffix) {
let artifact = path.resolve(file);
try {
artifact = fs.realpathSync.native(artifact);
} catch (error) {
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
try {
artifact = path.join(fs.realpathSync.native(path.dirname(artifact)), path.basename(artifact));
} catch (directoryError) {
if (directoryError.code !== 'ENOENT' && directoryError.code !== 'ENOTDIR') throw directoryError;
}
}
return artifact.replace(/\.html?$/i, suffix);
}
function deliveryProvenancePath(file) {
return deliverySidecarPath(file, '.delivery.json');
}
function deliveryPendingPath(file) {
return deliverySidecarPath(file, '.delivery-pending.json');
}
function deliveryLockPath(file) {
const artifact = path.resolve(file);
let directory;
try {
directory = path.dirname(fs.realpathSync.native(artifact));
} catch (error) {
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error;
try {
directory = fs.realpathSync.native(path.dirname(artifact));
} catch (directoryError) {
if (directoryError.code !== 'ENOENT' && directoryError.code !== 'ENOTDIR') throw directoryError;
directory = path.dirname(artifact);
}
}
return path.join(directory, '.archify-delivery-lock.json');
}
function legacyDeliveryLockPath(file) {
return path.resolve(file).replace(/\.html?$/i, '.delivery-lock.json');
}
function deliveryStagingEntries(directory) {
return fs.readdirSync(directory, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && entry.name.startsWith('.archify-delivery-'))
.map((entry) => entry.name)
.sort();
}
function successorDeliveryState({ receiptId, input, output, pid = process.pid }) {
return {
artifact: '<!doctype html><title>successor artifact</title>\n',
lock: `${JSON.stringify({ schemaVersion: 1, receiptId, pid })}\n`,
pending: `${JSON.stringify({
schemaVersion: 1,
command: 'deliver',
status: 'pending',
receiptId,
input: path.resolve(input),
output: path.resolve(output),
}, null, 2)}\n`,
provenance: `${JSON.stringify({
schemaVersion: 1,
receiptId,
status: 'failed',
command: 'deliver',
stage: 'successor',
input: path.resolve(input),
output: path.resolve(output),
error: 'successor owns this failure record',
}, null, 2)}\n`,
};
}
function visualEvidencePaths(file) {
const base = file.replace(/\.html?$/i, '.visual-check');
return {
receipt: `${base}.json`,
contactSheet: `${base}.html`,
screenshots: [
`${base}.1440x900.light.png`,
`${base}.1440x900.dark.png`,
`${base}.2048x1320.light.png`,
`${base}.2048x1320.dark.png`,
],
};
}
function assertCheckFailureReceipt(receipt, file, codePattern) {
assert.equal(receipt.ok, false);
assert.equal(receipt.file, path.resolve(file));
assert.ok(Array.isArray(receipt.diagnostics));
assert.match(receipt.diagnostics[0].code, codePattern);
}
function makeFakeOpeners(name, { exitCode = 0 } = {}) {
const bin = path.join(tmp, name);
const log = path.join(bin, 'open-log.json');
fs.mkdirSync(bin, { recursive: true });
const source = `#!/usr/bin/env node
const fs = require('node:fs');
const target = process.argv[process.argv.length - 1];
fs.writeFileSync(process.env.ARCHIFY_TEST_OPEN_LOG, JSON.stringify({
argv: process.argv.slice(2),
target,
existed: fs.existsSync(target),
}));
process.exit(${exitCode});
`;
for (const command of ['open', 'xdg-open']) {
const executable = path.join(bin, command);
fs.writeFileSync(executable, source);
fs.chmodSync(executable, 0o755);
}
return {
log,
env: {
...process.env,
PATH: `${bin}${path.delimiter}${process.env.PATH || ''}`,
ARCHIFY_TEST_OPEN_LOG: log,
},
};
}
function copyInstalledSkill(target) {
fs.cpSync(skillRoot, target, {
recursive: true,
filter(source) {
const rel = path.relative(skillRoot, source);
return rel !== 'node_modules' && !rel.startsWith(`node_modules${path.sep}`)
&& rel !== 'test' && !rel.startsWith(`test${path.sep}`)
// Another test creates this short-lived directory under skillRoot so
// Ajv resolves from the checkout. Never copy a concurrently removed
// test fixture into an installed-skill simulation.
&& !rel.startsWith('.validator-check-');
},
});
}
test('cli: help lists commands and diagram types', () => {
const result = run(['--help']);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /archify render <type>/);
assert.match(result.stdout, /archify compare architecture <base\.json> <head\.json>/);
assert.match(result.stdout, /archify deliver <type>/);
assert.match(result.stdout, /archify finalize <type>/);
assert.match(result.stdout, /archify preview <diagram-type \(excludes explainer\)>/);
assert.match(result.stdout, /archify browser-check <output\.html>/);
assert.match(result.stdout, /archify visual-check <output\.html>/);
assert.match(result.stdout, /--open/);
assert.match(result.stdout, /archify validate <type> <input\.json> .*\[--repo-root path\]/);
assert.doesNotMatch(result.stdout, /architecture only/);
assert.match(result.stdout, /archify guide \[scenario or question\]/);
assert.match(result.stdout, /archify doctor/);
assert.match(result.stdout, /archify demo \[output-directory\]/);
assert.match(result.stdout, /architecture, workflow, sequence, dataflow, lifecycle/);
});
test('cli: sole subcommand --help returns canonical usage without operations', (t) => {
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-cli-help-'));
t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
const global = run(['--help'], { cwd: scratch });
assert.equal(global.status, 0, global.stderr);
const commands = ['render', 'compare', 'deliver', 'finalize', 'preview', 'validate',
'migrate', 'inspect', 'check', 'browser-check', 'visual-check', 'guide', 'brands',
'examples', 'doctor', 'demo'];
for (const command of commands) {
const result = run([command, '--help'], { cwd: scratch });
assert.equal(result.status, 0, `${command}: ${result.stderr}`);
assert.equal(result.stderr, '', command);
assert.equal(result.stdout, global.stdout, `${command} uses canonical help bytes`);
assert.deepEqual(fs.readdirSync(scratch), [], `${command} help creates no artifact or evidence`);
}
});
test('cli: subcommand help keeps unknown and mixed arguments failing', () => {
const unknown = run(['not-a-command', '--help']);
assert.equal(unknown.status, 2);
assert.equal(unknown.stdout, '');
assert.match(unknown.stderr, /Unknown command "not-a-command"/);
const mixed = run(['visual-check', '--help', 'missing.html']);
assert.equal(mixed.status, 1);
assert.equal(mixed.stdout, '');
assert.equal(mixed.stderr, 'Unknown visual-check option "--help".\n');
const json = run(['validate', '--help', '--json']);
assert.equal(json.status, 2);
assert.equal(json.stderr, '');
const receipt = JSON.parse(json.stdout);
assert.equal(receipt.ok, false);
assert.equal(receipt.stage, 'arguments');
assert.equal(receipt.diagnostics[0].code, 'cli/unknown-option');
assert.equal(receipt.diagnostics[0].subject.option, '--help');
const bogus = run(['visual-check', '--bogus']);
assert.equal(bogus.status, 1);
assert.equal(bogus.stdout, '');
assert.equal(bogus.stderr, 'Unknown visual-check option "--bogus".\n');
});
test('cli: doctor reports a complete installation is ready', () => {
const result = run(['doctor']);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /\[ok\] Node\.js v\d+/);
assert.match(result.stdout, /\[ok\] Core template/);
assert.match(result.stdout, /\[ok\] Example renderer/);
assert.match(result.stdout, /\[ok\] Live preview runtime/);
assert.match(result.stdout, /\[ok\] Atomic output safety runtime/);
assert.match(result.stdout, /\[ok\] Sidecar path naming runtime/);
assert.match(result.stdout, /\[ok\] Finalize runtime/);
assert.match(result.stdout, /\[ok\] Scenario recipe guide/);
assert.match(result.stdout, /\[ok\] Progressive authoring references/);
assert.match(result.stdout, /\[ok\] Architecture compare runtime and proof fixtures/);
assert.match(result.stdout, /\[ok\] Standalone schema validators/);
assert.match(result.stdout, /\[ok\] architecture renderer, schema, and example/);
assert.match(result.stdout, /\[ok\] lifecycle renderer, schema, and example/);
assert.match(result.stdout, /Archify is ready\./);
});
test('cli: doctor identifies an incomplete installation', () => {
const incompleteRoot = path.join(tmp, 'incomplete-skill');
const incompleteBin = path.join(incompleteRoot, 'bin');
fs.mkdirSync(incompleteBin, { recursive: true });
fs.copyFileSync(cli, path.join(incompleteBin, 'archify.mjs'));
const result = spawnSync(process.execPath, [path.join(incompleteBin, 'archify.mjs'), 'doctor'], {
cwd: incompleteRoot,
encoding: 'utf8',
});
assert.equal(result.status, 1);
assert.match(result.stdout, /\[missing\] Core template/);
assert.match(result.stdout, /\[missing\] Scenario recipe guide/);
assert.match(result.stdout, /\[missing\] workflow renderer, schema, and example/);
assert.match(result.stderr, /Archify is not ready: \d+ required files? missing\./);
});
test('cli: doctor rejects a corrupt standalone validator', () => {
const corruptRoot = path.join(tmp, 'corrupt-skill');
copyInstalledSkill(corruptRoot);
fs.writeFileSync(path.join(corruptRoot, 'renderers/shared/generated-validators.mjs'), 'export const workflow = ;\n');
const result = spawnSync(process.execPath, [path.join(corruptRoot, 'bin/archify.mjs'), 'doctor'], {
cwd: corruptRoot,
encoding: 'utf8',
});
assert.equal(result.status, 1);
assert.match(result.stdout, /\[invalid\] Standalone schema validators/);
assert.match(result.stderr, /Archify is not ready: 1 runtime check failed\./);
});
test('cli: examples renders from an installed skill', () => {
const installedRoot = path.join(tmp, 'installed-skill');
copyInstalledSkill(installedRoot);
const result = spawnSync(process.execPath, [path.join(installedRoot, 'bin/archify.mjs'), 'examples'], {
cwd: installedRoot,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
for (const output of [
'workflow-agent-tool-call-rendered.html',
'sequence-cache-miss-request.html',
'dataflow-product-analytics.html',
'lifecycle-agent-run.html',
'web-app-rendered.html',
]) {
assert.equal(fs.existsSync(path.join(installedRoot, 'examples', output)), true, output);
}
});
test('cli: argument-free commands reject trailing arguments', () => {
for (const command of ['examples', 'doctor']) {
const extra = run([command, 'ignored-extra']);
assert.equal(extra.status, 2, command);
assert.match(extra.stderr, /Usage:/, command);
const unknown = run([command, '--bogus']);
assert.equal(unknown.status, 2, command);
assert.match(unknown.stderr, new RegExp(`Unknown ${command} option "--bogus"`), command);
}
});
test('cli: guide lists all scenario recipes by diagram type', () => {
const result = run(['guide']);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /Archify scenario recipes \(13\)/);
for (const type of ['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle', 'erd']) {
assert.match(result.stdout, new RegExp(`\\[${type}\\]`));
}
});
test('cli: guide recommends a scenario as structured json', () => {
const result = run(['guide', 'Show an API request with Redis cache miss', '--json']);
assert.equal(result.status, 0, result.stderr);
const parsed = JSON.parse(result.stdout);
assert.equal(parsed.ok, true);
assert.equal(parsed.lang, 'en');
assert.equal(parsed.confidence, 'high');
assert.equal(parsed.recommendation.id, 'api-request');
assert.equal(parsed.recommendation.type, 'sequence');
});
test('cli: guide detects Chinese and explains the recommendation boundary', () => {
const result = run(['guide', '展示 Kafka topic 消费者组和死信队列']);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /推荐: 事件流拓扑 \[dataflow\]/);
assert.match(result.stdout, /不要这样用:/);
assert.match(result.stdout, /必须包含:/);
assert.match(result.stdout, /可直接复制的提示词:/);
});
test('cli: guide works from an installed skill without node_modules', () => {
const installedRoot = path.join(tmp, 'installed-guide-skill');
copyInstalledSkill(installedRoot);
const installedCli = path.join(installedRoot, 'bin/archify.mjs');
const result = spawnSync(process.execPath, [installedCli, 'guide', 'incident-runbook', '--json'], {
cwd: installedRoot,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).recommendation.id, 'incident-runbook');
});
test('cli: guide returns repair steps, via semantics, and viewport checks as JSON', () => {
const result = run(['guide', 'viewport overflow', '--json']);
assert.equal(result.status, 0, result.stderr);
const parsed = JSON.parse(result.stdout);
assert.equal(parsed.recommendation.id, 'layout-repair');
assert.equal(parsed.confidence, 'high');
assert.ok(parsed.matchedSignals.includes('viewport overflow'));
const prompt = parsed.recommendation.prompt;
assert.match(prompt, /schema.*overlap.*direction.*crossings.*labels/s);
assert.match(prompt, /\[start, \.\.\.via, end\]/);
assert.match(prompt, /absolute.*\[x, y\]/);
assert.match(prompt, /1440×900.*1600×1000.*1920×1080.*2048×1320/);
assert.match(prompt, /scrollWidth <= window\.innerWidth/);
assert.match(prompt, /Reader-declared readable vertical page scroll/);
assert.match(prompt, /validate.*diagnostics\[\].*supportedFixes/);
});
test('cli: guide prints localized repair advice, including an explicit language override', () => {
for (const args of [
['guide', '视口溢出,标签重叠,修复顺序'],
['guide', 'how do via waypoints work', '--lang', 'zh'],
]) {
const result = run(args);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /推荐: 布局修复/);
assert.match(result.stdout, /schema.*重叠.*方向.*交叉.*标签/s);
assert.match(result.stdout, /\[start, \.\.\.via, end\]/);
assert.match(result.stdout, /Reader 已达到投影文字下限并接受可读的页面纵向滚动/);
assert.match(result.stdout, /validate/);
}
});
test('cli: demo creates a ready-to-open diagram in a chosen directory', () => {
const outputDirectory = path.join(tmp, 'my-demo');
const output = path.join(outputDirectory, 'archify-demo.html');
const result = run(['demo', outputDirectory]);
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.existsSync(output), true);
assert.match(fs.readFileSync(output, 'utf8'), /Sample Web App Diagram/);
assert.match(result.stdout, new RegExp(`Demo ready: ${output.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`));
assert.match(result.stdout, /Next: open the HTML in your browser/);
assert.match(result.stdout, /archify render architecture/);
});
test('cli: demo defaults to the current directory', () => {
const workingDirectory = path.join(tmp, 'default-demo');
fs.mkdirSync(workingDirectory);
const result = run(['demo'], { cwd: workingDirectory });
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.existsSync(path.join(workingDirectory, 'archify-demo.html')), true);
});
test('cli: demo rejects a mistyped option without creating an output directory', () => {
const workingDirectory = path.join(tmp, 'demo-option-guard');
fs.mkdirSync(workingDirectory);
const result = run(['demo', '--typo'], { cwd: workingDirectory });
assert.equal(result.status, 2);
assert.match(result.stderr, /Unknown demo option "--typo"/);
assert.deepEqual(fs.readdirSync(workingDirectory), []);
});
test('cli: render writes a diagram html file', () => {
const out = path.join(tmp, 'workflow.html');
const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
const result = run(['render', 'workflow', input, out]);
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.existsSync(out), true);
assert.match(fs.readFileSync(out, 'utf8'), /Agent Tool Call Workflow/);
});
test('cli: visual-check returns a skipped receipt with exit 2 when Chrome is unavailable', () => {
const out = path.join(tmp, 'visual-check-skipped.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const missingChrome = path.join(tmp, 'missing-chrome');
const result = run(['visual-check', out, '--json'], {
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
assert.equal(result.status, 2, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.status, 'skipped');
assert.equal(receipt.evidenceKind, 'automated-browser');
assert.equal(receipt.visualReview, 'pending');
assert.equal(receipt.chrome.status, 'unavailable');
assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), true);
});
test('cli: browser-check returns deterministic evidence without requesting perceptual review', () => {
const out = path.join(tmp, 'browser-check-skipped.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const missingChrome = path.join(tmp, 'missing-browser-check-chrome');
const result = run(['browser-check', out, '--json'], {
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
assert.equal(result.status, 2, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.command, 'browser-check');
assert.equal(receipt.status, 'skipped');
assert.equal(receipt.evidenceKind, 'automated-browser');
assert.equal(receipt.visualReview, 'not-requested');
assert.equal(receipt.captures.status, 'not-requested');
assert.equal(receipt.chrome.status, 'unavailable');
assert.equal(fs.existsSync(out.replace(/\.html$/, '.browser-check.json')), true);
assert.equal(fs.existsSync(out.replace(/\.html$/, '.browser-check.contact.png')), false);
});
test('cli: finalize emits one compact receipt and keeps complete stage evidence in its sidecar', () => {
const input = path.join(skillRoot, 'examples/web-app.architecture.json');
const out = path.join(tmp, 'finalize-skipped.html');
const outDir = path.join(tmp, 'finalize-skipped-evidence');
const missingChrome = path.join(tmp, 'missing-finalize-chrome');
const result = run([
'finalize', 'architecture', input, out,
'--quality', 'showcase', '--json', '--out-dir', outDir,
], { env: { ...process.env, ARCHIFY_CHROME: missingChrome } });
assert.equal(result.status, 2, result.stderr || result.stdout);
assert.equal(result.stdout.trim().split('\n').length, 1, 'agent stdout stays compact');
const summary = JSON.parse(result.stdout);
assert.equal(summary.status, 'skipped');
assert.equal(summary.failedStage, 'browser-check');
assert.deepEqual(summary.gates, {
validate: 'pass', deliver: 'pass', check: 'pass', 'browser-check': 'skipped',
});
assert.equal(summary.visualReview, 'not-requested');
assert.equal(summary.evidence.receipt, path.join(outDir, 'finalize-skipped.finalize.json'));
assert.equal(summary.evidence.summaryReceipt, path.join(outDir, 'finalize-skipped.finalize-summary.json'));
assert.equal(summary.evidence.browserCheckReceipt, path.join(outDir, 'finalize-skipped.browser-check.json'));
const full = JSON.parse(fs.readFileSync(summary.evidence.receipt, 'utf8'));
assert.equal(full.stages.validate.receipt.validation.checkCount, 9);
assert.equal(full.stages['browser-check'].receipt.status, 'skipped');
const persistedSummary = JSON.parse(fs.readFileSync(summary.evidence.summaryReceipt, 'utf8'));
assert.deepEqual(persistedSummary, summary);
assert.equal('stages' in persistedSummary, false);
assert.equal(fs.existsSync(out), true, 'verified delivery remains available when browser evidence is skipped');
});
test('cli: visual-check summary preserves skipped and failed evidence without claiming image review', () => {
const out = path.join(tmp, 'visual-summary.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const outDir = path.join(tmp, 'visual-summary-evidence');
const result = run(['visual-check', out, '--summary', '--out-dir', outDir], {
env: { ...process.env, ARCHIFY_CHROME: path.join(tmp, 'summary-missing-chrome') },
});
assert.equal(result.status, 2, result.stderr || result.stdout);
assert.equal(result.stdout.trim().split('\n').length, 1);
const summary = JSON.parse(result.stdout);
assert.equal(summary.status, 'skipped');
assert.equal(summary.visualReview, 'pending');
assert.deepEqual(summary.evidence.screenshots, []);
const full = JSON.parse(fs.readFileSync(summary.evidence.receipt, 'utf8'));
assert.deepEqual(summary.artifact, full.artifact);
assert.deepEqual(summary.diagnostics, full.diagnostics);
assert.equal(summary.checks.containment, full.containment.status);
assert.equal(summary.evidence.receipt, path.join(outDir, 'visual-summary.visual-check.json'));
const failure = run(['visual-check', path.join(tmp, 'summary-missing.html'), '--summary']);
assert.equal(failure.status, 1);
const failedSummary = JSON.parse(failure.stdout);
assert.equal(failedSummary.status, 'fail');
assert.equal(failedSummary.visualReview, 'pending');
assert.ok(failedSummary.diagnostics.length > 0);
assert.deepEqual(failedSummary.evidence.screenshots, []);
assert.equal(failedSummary.evidence.receipt, undefined, 'an unpublished receipt must not be linked');
});
test('cli: visual-check --out-dir writes the receipt into that directory, not beside the artifact', () => {
const out = path.join(tmp, 'visual-check-outdir.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const missingChrome = path.join(tmp, 'missing-chrome-outdir');
const outDir = path.join(tmp, 'visual-check-outdir-evidence');
const result = run(['visual-check', out, '--json', '--out-dir', outDir], {
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
assert.equal(result.status, 2, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.status, 'skipped');
assert.equal(fs.existsSync(path.join(outDir, 'visual-check-outdir.visual-check.json')), true);
assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), false, 'no receipt should land beside the artifact when --out-dir is set');
});
test('cli: visual-check --out-dir redirects failed provenance evidence', () => {
const out = path.join(tmp, 'visual-check-outdir-provenance.html');
const outDir = path.join(tmp, 'visual-check-outdir-provenance-evidence');
fs.writeFileSync(out, '<!doctype html><html><body>not delivered</body></html>');
const result = run(['visual-check', out, '--json', '--require-provenance', '--out-dir', outDir]);
assert.equal(result.status, 1, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.status, 'fail');
assert.equal(receipt.sidecars.directory, outDir);
assert.match(receipt.diagnostics[0].code, /^delivery\/provenance-/);
assert.equal(fs.existsSync(path.join(outDir, 'visual-check-outdir-provenance.visual-check.json')), true);
assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), false);
});
test('cli: visual-check rejects an invalid raw --out-dir before filesystem mutation', () => {
const workingDirectory = path.join(tmp, 'visual-check-invalid-raw-outdir');
fs.mkdirSync(workingDirectory);
const out = path.join(workingDirectory, 'artifact.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const before = fs.readdirSync(workingDirectory).sort();
const invalidOutDir = process.platform === 'win32'
? `${path.parse(workingDirectory).root.slice(0, 2)}evidence`
: path.join(workingDirectory, 'x'.repeat(256));
const normalizedMutation = process.platform === 'win32'
? path.join(workingDirectory, 'evidence')
: invalidOutDir;
const missingChrome = path.join(workingDirectory, 'missing-chrome');
const result = run([
'visual-check', out, '--json', '--out-dir', invalidOutDir,
], {
cwd: workingDirectory,
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
assert.equal(result.status, 1, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.ok, false);
assert.equal(receipt.command, 'visual-check');
assert.equal(receipt.diagnostics[0].code, 'output/native-path-syntax');
assert.equal(receipt.diagnostics[0].subject.output, invalidOutDir);
assert.deepEqual(fs.readdirSync(workingDirectory).sort(), before);
assert.equal(fs.existsSync(normalizedMutation), false);
const evidence = visualEvidencePaths(out);
assert.equal(fs.existsSync(evidence.receipt), false);
assert.equal(fs.existsSync(evidence.contactSheet), false);
assert.equal(evidence.screenshots.every((file) => !fs.existsSync(file)), true);
});
test('cli: visual-check rejects --out-dir with no value', () => {
const out = path.join(tmp, 'visual-check-outdir-missing-value.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const result = run(['visual-check', out, '--out-dir']);
assert.notEqual(result.status, 0);
assert.match(result.stderr, /--out-dir requires a directory path/);
});
test('cli: visual-check describes human output as automated browser evidence, not visual approval', () => {
const out = path.join(tmp, 'visual-check-browser-evidence.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
const missingChrome = path.join(tmp, 'missing-browser-evidence-chrome');
const result = run(['visual-check', out], {
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
assert.equal(result.status, 2, result.stderr || result.stdout);
assert.match(result.stdout, /automated browser evidence skipped:/i);
assert.match(result.stdout, /perceptual visual review pending/i);
assert.doesNotMatch(result.stdout, /^visual-check skipped:/m);
});
test('cli: visual-check keeps automated and perceptual claims separate on input failure', () => {
const result = run(['visual-check', path.join(tmp, 'missing-browser-evidence.html')]);
assert.equal(result.status, 1);
assert.match(result.stderr, /automated browser evidence failed:/i);
assert.match(result.stderr, /perceptual visual review pending/i);
assert.doesNotMatch(result.stderr, /^visual-check failed:/m);
});
test('cli: deliver atomically writes a checked artifact and structured receipt', () => {
const out = path.join(tmp, 'delivered-workflow.html');
const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
const result = run(['deliver', 'workflow', input, out, '--quality', 'showcase', '--json']);
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.existsSync(out), true);
assert.match(fs.readFileSync(out, 'utf8'), /Agent Tool Call Workflow/);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.schemaVersion, 1);
assert.equal(receipt.ok, true);
assert.equal(receipt.command, 'deliver');
assert.equal(receipt.type, 'workflow');
assert.equal(receipt.input, input);
assert.equal(receipt.output, fs.realpathSync.native(out));
assert.deepEqual(receipt.specification, {
sha256: sha256(input),
bytes: fs.statSync(input).size,
});
assert.match(receipt.artifact.sha256, /^[a-f0-9]{64}$/);
assert.equal(receipt.artifact.sha256, sha256(out));
assert.equal(receipt.artifact.bytes, fs.statSync(out).size);
assert.deepEqual(receipt.validation, {
checksPassed: 9,
checkCount: 9,
compositionProfile: 'showcase',
compositionStatus: 'pass',
errors: 0,
warnings: 0,
});
assert.equal('open' in receipt, false);
});
test('cli: deliver --open launches only the committed absolute artifact as one argument', {
skip: process.platform === 'win32',
}, () => {
const fake = makeFakeOpeners('successful-open');
const out = path.join(tmp, `-复杂 path 'quoted'`, 'verified diagram.html');
const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
const result = run(['deliver', 'workflow', input, out, '--open', '--json'], { env: fake.env });
assert.equal(result.status, 0, result.stderr);
const receipt = JSON.parse(result.stdout);
const physicalOut = fs.realpathSync.native(out);
assert.deepEqual(receipt.open, {
requested: true,
status: 'opened',
target: physicalOut,
method: process.platform === 'darwin' ? 'open' : 'xdg-open',
});
const invocation = JSON.parse(fs.readFileSync(fake.log, 'utf8'));
assert.equal(invocation.existed, true, 'the opener must run after the atomic commit');
assert.deepEqual(invocation.argv, [physicalOut]);
assert.equal(invocation.target, physicalOut);
assert.equal(fs.existsSync(out), true);
});
test('cli: opener failure does not invalidate a verified delivery or pollute json stdout', {
skip: process.platform === 'win32',
}, () => {
const fake = makeFakeOpeners('failed-open', { exitCode: 17 });
const out = path.join(tmp, 'open-failure-preserves-delivery.html');
const input = path.join(skillRoot, 'examples/web-app.architecture.json');
const result = run(['deliver', 'architecture', input, out, '--open', '--json'], { env: fake.env });
assert.equal(result.status, 0, result.stderr);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.ok, true);
assert.equal(receipt.open.status, 'failed');
assert.equal(receipt.open.failure.code, 'opener/nonzero-exit');
assert.equal(receipt.open.target, fs.realpathSync.native(out));
assert.match(result.stderr, /Could not open the verified artifact/);
assert.match(result.stderr, /exited with status 17\. Open the target manually\./);
assert.match(result.stderr, new RegExp(out.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
assert.equal(fs.existsSync(out), true);
assert.equal(receipt.artifact.sha256, sha256(out));
});
test('cli: deliver failure never invokes the optional opener', {
skip: process.platform === 'win32',
}, () => {
const fake = makeFakeOpeners('never-open');
const input = path.join(tmp, 'invalid-open-delivery.json');
fs.writeFileSync(input, '{broken json');
const out = path.join(tmp, 'must-not-open.html');
const result = run(['deliver', 'architecture', input, out, '--open', '--json'], { env: fake.env });
assert.equal(result.status, 1);
assert.equal(JSON.parse(result.stdout).stage, 'input');
assert.equal(fs.existsSync(fake.log), false);
assert.equal(fs.existsSync(out), false);
});
test('cli: a missing optional opener module preserves verified delivery with a fallback receipt', () => {
const installedRoot = path.join(tmp, 'missing-open-module-skill');
copyInstalledSkill(installedRoot);
const installedCli = path.join(installedRoot, 'bin/archify.mjs');
fs.rmSync(path.join(installedRoot, 'bin/open-artifact.mjs'));
const input = path.join(installedRoot, 'examples/agent-tool-call.workflow.json');
const out = path.join(tmp, 'missing-open-module-delivery.html');
const result = spawnSync(process.execPath, [installedCli, 'deliver', 'workflow', input, out, '--open', '--json'], {
cwd: installedRoot,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.ok, true);
assert.deepEqual(receipt.open, {
requested: true,
status: 'unsupported',
target: fs.realpathSync.native(out),
method: null,
});
assert.match(result.stderr, /Open it manually/);
assert.equal(receipt.artifact.sha256, sha256(out));
});
test('cli: deliver preserves the renderer default output contract', () => {
const workingDirectory = path.join(tmp, 'delivery-default-output');
fs.mkdirSync(workingDirectory, { recursive: true });
const input = path.join(workingDirectory, 'source.architecture.json');
const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));
source.meta.output = 'verified-default.html';
fs.writeFileSync(input, JSON.stringify(source));
const result = run(['deliver', 'architecture', input, '--json'], { cwd: workingDirectory });
assert.equal(result.status, 0, result.stderr);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.output, path.join(fs.realpathSync(workingDirectory), 'verified-default.html'));
assert.equal(fs.existsSync(receipt.output), true);
});
test('cli: deliver works from an installed skill without node_modules', () => {
const installedRoot = path.join(tmp, 'installed-deliver-skill');
copyInstalledSkill(installedRoot);
const installedCli = path.join(installedRoot, 'bin/archify.mjs');
const cases = [
['architecture-boundaries', 'architecture', 'production-deployment.architecture.json'],
['architecture-issue-110', 'architecture', 'brand-aware-delivery.architecture.json'],
['workflow', 'workflow', 'agent-tool-call.workflow.json'],
['sequence', 'sequence', 'cache-miss-request.sequence.json'],
['dataflow', 'dataflow', 'product-analytics.dataflow.json'],
['lifecycle', 'lifecycle', 'agent-run.lifecycle.json'],
];
for (const [label, type, example] of cases) {
const input = path.join(installedRoot, 'examples', example);
const out = path.join(tmp, `installed-${label}-delivery.html`);
const result = spawnSync(process.execPath, [installedCli, 'deliver', type, input, out, '--json'], {
cwd: installedRoot,
encoding: 'utf8',
});
assert.equal(result.status, 0, `${label}: ${result.stderr}`);
assert.equal(JSON.parse(result.stdout).validation.checkCount, 9, label);
assert.equal(fs.existsSync(out), true, label);
const extracted = extractSvgs(fs.readFileSync(out, 'utf8'));
assert.equal(extracted.direct.length, 1, `${label}: expected one delivered SVG`);
assert.doesNotThrow(
() => parseXml(extracted.direct[0]),
`${label}: delivered SVG must be well-formed XML`,
);
}
});
test('cli: deliver XML guard parses markup instead of scanning attribute-like text', () => {
assert.doesNotThrow(() => parseXml(
'<svg xmlns="http://www.w3.org/2000/svg" aria-label="mentions data-node-label safely"/>',
));
assert.throws(
() => parseXml('<svg xmlns="http://www.w3.org/2000/svg" data-node-label></svg>'),
/attribute without value/i,
);
assert.throws(
() => parseXml('<svg xmlns="http://www.w3.org/2000/svg"><g></svg>'),
/unexpected close tag/i,
);
});
test('cli: preview runs from an installed skill without node_modules and exits cleanly', { timeout: 30000 }, async () => {
const installedRoot = path.join(tmp, 'installed-preview-skill');
copyInstalledSkill(installedRoot);
const installedCli = path.join(installedRoot, 'bin/archify.mjs');
const input = path.join(installedRoot, 'examples/web-app.architecture.json');
const output = path.join(tmp, 'installed-preview.html');
// Windows child.kill() terminates immediately, bypassing the signal handler.
const signalRelay = process.platform === 'win32'
? ['--import', 'data:text/javascript,process.once("message", () => { process.disconnect(); process.emit("SIGTERM"); });']
: [];
const child = spawn(process.execPath, [...signalRelay, installedCli, 'preview', 'architecture', input, output, '--quality', 'showcase', '--no-open'], {
cwd: installedRoot,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe', ...(process.platform === 'win32' ? ['ipc'] : [])],
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
let previewUrl;
const started = Date.now();
while (!previewUrl && Date.now() - started < 8000) {
previewUrl = stdout.match(/preview (http:\/\/127\.0\.0\.1:\d+\/)/)?.[1];
if (!previewUrl) await new Promise((resolve) => setTimeout(resolve, 40));
}
assert.ok(previewUrl, `preview URL missing; stdout=${stdout}; stderr=${stderr}`);
let state;
while (Date.now() - started < 15000) {
state = await fetch(new URL('/state', previewUrl)).then((response) => response.json());
if (state.status === 'verified') break;
await new Promise((resolve) => setTimeout(resolve, 50));
}
assert.equal(state?.status, 'verified', `preview did not verify; stdout=${stdout}; stderr=${stderr}`);
assert.equal(state.revision, 1);
assert.equal(fs.existsSync(output), true);
if (process.platform === 'win32') child.send('stop');
else child.kill('SIGTERM');
const exit = await new Promise((resolve) => child.once('close', (code, signal) => resolve({ code, signal })));
assert.deepEqual(exit, { code: 0, signal: null });
assert.match(stdout, /stopping preview/);
await assert.rejects(fetch(previewUrl));
assert.deepEqual(fs.readdirSync(path.dirname(output)).filter((name) => name.startsWith('.archify-preview-')), []);
});
test('cli: deliver preserves the previous artifact when the final check fails', () => {
const installedRoot = path.join(tmp, 'broken-deliver-skill');
copyInstalledSkill(installedRoot);
const installedCli = path.join(installedRoot, 'bin/archify.mjs');
const templatePath = path.join(installedRoot, 'assets/template.html');
const template = fs.readFileSync(templatePath, 'utf8');
fs.writeFileSync(templatePath, template.replace('</body>', '<svg aria-label="accidental second svg"></svg>\n</body>'));
const input = path.join(installedRoot, 'examples/web-app.architecture.json');
const out = path.join(tmp, 'preserved-delivery.html');
const trustedPriorArtifact = '<!doctype html><title>trusted prior artifact</title>\n';
fs.writeFileSync(out, trustedPriorArtifact);
const result = spawnSync(process.execPath, [installedCli, 'deliver', 'architecture', input, out, '--json'], {
cwd: installedRoot,
encoding: 'utf8',
});
assert.equal(result.status, 1);
const failure = JSON.parse(result.stdout);
assert.equal(failure.ok, false);
assert.equal(failure.stage, 'check');
assert.equal(failure.diagnostics[0].code, 'artifact/single-svg');
assert.equal(failure.diagnostics[0].subject.check, 'single_svg');
assert.ok(failure.diagnostics[0].supportedFixes.some((fix) => fix.includes('exactly one diagram SVG')));
assert.equal(failure.checker.checks.find((entry) => entry.name === 'single_svg').ok, false);
assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);
assert.deepEqual(
fs.readdirSync(path.dirname(out)).filter((name) => name.includes('.archify-delivery-')),
[],
);
});
// Dense-but-valid receipt fixtures live in helpers/dense-fixture.mjs.
test('cli: deliver accepts a dense artifact whose checker receipt exceeds the 1 MiB default buffer', { timeout: 60000 }, () => {
const input = path.join(tmp, 'dense-receipt.architecture.json');
fs.writeFileSync(input, JSON.stringify(bipartiteArchitectureSpec(8)));
const out = path.join(tmp, 'dense-receipt.html');
// Scrub the knob so this test exercises the default limit even when a
// developer or CI environment overrides it.
const env = { ...process.env };
delete env.ARCHIFY_CHECK_MAX_BUFFER;
const delivered = run(['deliver', 'architecture', input, out, '--json'], { env });
assert.equal(delivered.status, 0, delivered.stderr);
const receipt = JSON.parse(delivered.stdout);
assert.equal(receipt.ok, true);
assert.equal(receipt.command, 'deliver');
const provenance = JSON.parse(fs.readFileSync(deliveryProvenancePath(out), 'utf8'));
assert.equal(provenance.status, 'current');
const checked = spawnSync(process.execPath, [path.join(skillRoot, 'scripts/check-render-output.mjs'), out], {
cwd: skillRoot,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
});
assert.equal(checked.status, 0, checked.stderr);
const bytes = Buffer.byteLength(checked.stdout, 'utf8');
assert.ok(bytes > 1024 * 1024, `checker receipt was only ${bytes} bytes; the fixture no longer overflows the 1 MiB default`);
assert.equal(JSON.parse(checked.stdout).ok, true);
});
test('cli: deliver reports an output-limit failure distinctly and preserves the previous artifact', () => {
const input = path.join(skillRoot, 'examples/web-app.architecture.json');
const out = path.join(tmp, 'output-limit-preserved.html');
const trustedPriorArtifact = '<!doctype html><title>trusted prior artifact</title>\n';
fs.writeFileSync(out, trustedPriorArtifact);
const result = run(['deliver', 'architecture', input, out, '--json'], {
env: { ...process.env, ARCHIFY_CHECK_MAX_BUFFER: '1024' },
});
assert.equal(result.status, 1);
const failure = JSON.parse(result.stdout);
assert.equal(failure.ok, false);
assert.equal(failure.stage, 'check');
assert.equal(failure.diagnostics.length, 1);
assert.equal(failure.diagnostics[0].code, 'artifact/check-output-limit');
assert.notEqual(failure.diagnostics[0].code, 'artifact/check-failed');
assert.equal(failure.diagnostics[0].evidence.systemCode, 'ENOBUFS');
assert.equal(failure.diagnostics[0].evidence.limitBytes, 1024);
assert.ok(failure.diagnostics[0].evidence.receivedBytes >= 1024);
assert.ok(failure.diagnostics[0].supportedFixes.some((fix) => fix.includes('ARCHIFY_CHECK_MAX_BUFFER')));
assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);
const provenance = JSON.parse(fs.readFileSync(deliveryProvenancePath(out), 'utf8'));
assert.equal(provenance.status, 'failed');
assert.equal(provenance.stage, 'check');
assert.deepEqual(
fs.readdirSync(path.dirname(out)).filter((name) => name.includes('.archify-delivery-')),
[],
);
});
test('cli: deliver records the output-limit failure before it releases the delivery', () => {
const input = path.join(skillRoot, 'examples/web-app.architecture.json');
const out = path.join(tmp, 'output-limit-order.html');
const trustedPriorArtifact = '<!doctype html><title>trusted prior artifact</title>\n';
fs.writeFileSync(out, trustedPriorArtifact);
// The failure receipt must be recorded before the delivery releases its
// staging. Both steps are observable from the CLI process: the receipt is
// published as the `.delivery.json` sidecar (linked into place), and the
// staging directory is retired through an `.archify-staging-remove-` quarantine.
const orderLog = path.join(tmp, 'output-limit-order.log');
const probe = path.join(tmp, 'output-limit-order-probe.mjs');
fs.writeFileSync(
probe,
`import fs from 'node:fs';
const log = process.env.ARCHIFY_ORDER_LOG;
// Instrumentation must never change CLI behavior, so a log write failure is ignored.
const note = (event) => { try { if (log) fs.appendFileSync(log, event + '\\n'); } catch {} };
const publishesReceipt = (to) => typeof to === 'string' && to.endsWith('.delivery.json');
const linkSync = fs.linkSync;
fs.linkSync = function (from, to) {
if (publishesReceipt(to)) note('record-failure');
return linkSync.apply(this, arguments);
};
const renameSync = fs.renameSync;
fs.renameSync = function (from, to) {
if (publishesReceipt(to)) note('record-failure');
if (typeof to === 'string' && to.includes('.archify-staging-remove-')) {
const retired = String(from).split(/[\\\\/]/).pop();
note('release-staging:' + retired);
}
return renameSync.apply(this, arguments);
};
`,
);
fs.writeFileSync(orderLog, '');
const nodeOptions = `${process.env.NODE_OPTIONS ? `${process.env.NODE_OPTIONS} ` : ''}--import=${pathToFileURL(probe).href}`;
const result = run(['deliver', 'architecture', input, out, '--json'], {
env: { ...process.env, ARCHIFY_CHECK_MAX_BUFFER: '1024', ARCHIFY_ORDER_LOG: orderLog, NODE_OPTIONS: nodeOptions },
});