oc-harness-setup 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/.docs/unwired-routing.md +16 -15
  2. package/AGENTS.md +105 -68
  3. package/CHANGELOG.md +91 -0
  4. package/GLOSSARY.md +46 -0
  5. package/LICENSE +1 -1
  6. package/README.md +48 -60
  7. package/agents/cleaner.md +86 -0
  8. package/agents/critic.md +79 -0
  9. package/agents/historian.md +92 -0
  10. package/agents/maintainer.md +106 -0
  11. package/agents/ops.md +69 -0
  12. package/agents/orchestrator.md +48 -18
  13. package/agents/researcher.md +72 -0
  14. package/agents/verifier.md +84 -0
  15. package/agents/worker.md +87 -0
  16. package/bin/cli.js +349 -133
  17. package/commands/close.md +11 -0
  18. package/commands/evolve.md +11 -0
  19. package/commands/fast.md +11 -0
  20. package/commands/goal.md +11 -0
  21. package/commands/search.md +11 -0
  22. package/commands/swarm.md +11 -0
  23. package/opencode.jsonc +39 -79
  24. package/package.json +13 -6
  25. package/reference/README.md +12 -14
  26. package/reference/canon.md +71 -0
  27. package/reference/context.md +35 -0
  28. package/reference/enforcement.md +6 -0
  29. package/reference/flow.md +19 -0
  30. package/reference/gates.md +23 -0
  31. package/reference/harness.md +15 -0
  32. package/reference/hygiene.md +13 -0
  33. package/reference/memory.md +13 -0
  34. package/reference/models.md +19 -24
  35. package/reference/phases.md +23 -0
  36. package/reference/repos.md +49 -0
  37. package/reference/tools.md +35 -0
  38. package/scripts/harness-doctor.ps1 +83 -0
  39. package/skills/close/SKILL.md +36 -0
  40. package/skills/evolve/SKILL.md +76 -0
  41. package/skills/fast/SKILL.md +36 -0
  42. package/skills/goal/SKILL.md +65 -0
  43. package/skills/search/SKILL.md +68 -0
  44. package/skills/swarm/SKILL.md +69 -0
  45. package/state-seed/lessons.md +22 -0
  46. package/state-seed/template.md +12 -0
  47. package/agents/build.md +0 -20
  48. package/agents/explore.md +0 -26
  49. package/agents/general.md +0 -19
  50. package/agents/plan.md +0 -29
  51. package/agents/reviewer.md +0 -22
  52. package/agents/vault.md +0 -73
  53. package/commands/build.md +0 -7
  54. package/commands/checkpoint.md +0 -7
  55. package/commands/code-simplify.md +0 -7
  56. package/commands/gauntlet.md +0 -7
  57. package/commands/handoff.md +0 -7
  58. package/commands/keeper.md +0 -7
  59. package/commands/kill.md +0 -11
  60. package/commands/plan.md +0 -7
  61. package/commands/retro.md +0 -15
  62. package/commands/review.md +0 -7
  63. package/commands/ship.md +0 -7
  64. package/commands/spec.md +0 -7
  65. package/commands/test.md +0 -7
  66. package/commands/webperf.md +0 -7
  67. package/reference/auto-mandate.md +0 -11
  68. package/reference/backup-convention.md +0 -9
  69. package/reference/clean-mandate.md +0 -13
  70. package/reference/editor-parity.md +0 -7
  71. package/reference/gc-scripts.md +0 -8
  72. package/reference/intent-routing.md +0 -14
  73. package/reference/lifecycle.md +0 -15
  74. package/reference/model-keeper.md +0 -46
  75. package/reference/model-test.md +0 -176
  76. package/reference/oc-source-map.md +0 -162
  77. package/reference/owner-pin.md +0 -31
  78. package/reference/roster.md +0 -15
  79. package/reference/session-scope.md +0 -9
  80. package/reference/session-state.md +0 -13
  81. package/reference/swarm.md +0 -32
  82. package/scripts/backup-config.ps1 +0 -42
  83. package/scripts/gc-branch.ps1 +0 -196
  84. package/scripts/gc-bump.ps1 +0 -198
  85. package/scripts/gc-clean.ps1 +0 -648
  86. package/scripts/gc-commit.ps1 +0 -143
  87. package/scripts/gc-merge.ps1 +0 -272
  88. package/scripts/gc-pr.ps1 +0 -190
  89. package/scripts/gc-push.ps1 +0 -111
  90. package/scripts/gc-read.ps1 +0 -150
  91. package/scripts/gc-rebase.ps1 +0 -162
  92. package/scripts/gc-release.ps1 +0 -225
  93. package/scripts/gc-stage.ps1 +0 -103
  94. package/scripts/gc-status.ps1 +0 -127
  95. package/scripts/gc-sync.ps1 +0 -65
  96. package/scripts/gc.core.ps1 +0 -715
  97. package/scripts/gc.smoke.ps1 +0 -779
  98. package/scripts/interrupt-session.ps1 +0 -65
  99. package/scripts/logbook/README.md +0 -108
  100. package/scripts/logbook/logbook.test.ts +0 -440
  101. package/scripts/logbook/logbook.ts +0 -797
  102. package/scripts/pirep/README.md +0 -147
  103. package/scripts/pirep/pirep.test.ts +0 -735
  104. package/scripts/pirep/pirep.ts +0 -836
  105. package/scripts/testflight/README.md +0 -112
  106. package/scripts/testflight/testflight.test.ts +0 -512
  107. package/scripts/testflight/testflight.ts +0 -806
  108. package/skills/_shared/SOURCES.md +0 -26
  109. package/skills/_shared/references/accessibility-checklist.md +0 -160
  110. package/skills/_shared/references/definition-of-done.md +0 -67
  111. package/skills/_shared/references/observability-checklist.md +0 -92
  112. package/skills/_shared/references/orchestration-patterns.md +0 -155
  113. package/skills/_shared/references/performance-checklist.md +0 -236
  114. package/skills/_shared/references/security-checklist.md +0 -245
  115. package/skills/_shared/references/testing-patterns.md +0 -235
  116. package/skills/api-and-interface-design/SKILL.md +0 -14
  117. package/skills/browser-testing-with-devtools/SKILL.md +0 -303
  118. package/skills/code-simplification/SKILL.md +0 -14
  119. package/skills/creative-writing/SKILL.md +0 -96
  120. package/skills/debugging-and-error-recovery/SKILL.md +0 -15
  121. package/skills/flight-deck/SKILL.md +0 -17
  122. package/skills/frontend-ui-engineering/SKILL.md +0 -16
  123. package/skills/gauntlet/SKILL.md +0 -21
  124. package/skills/git-ceremony/SKILL.md +0 -27
  125. package/skills/grilling/SKILL.md +0 -18
  126. package/skills/observability-and-instrumentation/SKILL.md +0 -18
  127. package/skills/performance-optimization/SKILL.md +0 -16
  128. package/skills/pilot-report/SKILL.md +0 -18
  129. package/skills/planning-and-task-breakdown/SKILL.md +0 -16
  130. package/skills/security-and-hardening/SKILL.md +0 -18
  131. package/skills/source-driven-development/SKILL.md +0 -16
  132. package/skills/spec-driven-development/SKILL.md +0 -26
  133. package/skills/test-driven-development/SKILL.md +0 -18
  134. package/skills/test-flight/SKILL.md +0 -14
  135. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  136. package/skills/writing-for-agents/SKILL.md +0 -89
@@ -1,806 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * testflight — check the artifact you are about to publish, not the checkout you
4
- * built it in.
5
- *
6
- * Twice in this project the working copy passed and the *published* package
7
- * failed, because the checkout's node_modules satisfied imports that npm would
8
- * never install for a user:
9
- *
10
- * - a peer marked optional via `peerDependenciesMeta`: npm skipped it, and the
11
- * package died on `Cannot find package '@opentui/solid'`;
12
- * - a plugin that resolved its own copy of `solid-js` while the host binary
13
- * carried a different instance entirely.
14
- *
15
- * `npm pack --dry-run` catches neither. It lists files; it does not install them
16
- * and it does not resolve them.
17
- *
18
- * What this does:
19
- * 1. packs the real tarball
20
- * 2. extracts it and reads the *published* manifest, not the checkout's
21
- * 3. verifies every declared entry point is actually inside the tarball
22
- * 4. flags required peers marked optional, and peers duplicated as runtime deps
23
- * 5. greps the packed bytes for machine-specific paths
24
- * 6. installs into a throwaway project and confirms each peer resolved
25
- *
26
- * Honest limit: this proves packaging, contents, and resolution. It cannot
27
- * reproduce modules the host injects at runtime, so a plugin can still load here
28
- * and fail inside a bundled host binary. That failure has a different cause and
29
- * needs a different test — do not read a green run as "it works in the host".
30
- *
31
- * Usage:
32
- * testflight . check the package in this directory
33
- * testflight ./pkg-1.0.0.tgz check an existing tarball
34
- * testflight . --json machine-readable
35
- * testflight . --no-install static checks only (no network, fast)
36
- * testflight . --import also import the declared entry points
37
- * testflight . --keep keep the sandbox, print its path
38
- */
39
-
40
- import { spawnSync } from "node:child_process";
41
- import {
42
- existsSync,
43
- mkdirSync,
44
- mkdtempSync,
45
- readFileSync,
46
- readdirSync,
47
- rmSync,
48
- statSync,
49
- writeFileSync,
50
- } from "node:fs";
51
- import { tmpdir } from "node:os";
52
- import { extname, join, resolve } from "node:path";
53
- import { pathToFileURL } from "node:url";
54
-
55
- // ---------------------------------------------------------------------------
56
- // Findings
57
- // ---------------------------------------------------------------------------
58
-
59
- export type Severity = "error" | "warn" | "info";
60
-
61
- export interface Finding {
62
- /** Stable identifier, e.g. `TF001`. Printed so a failure can be cited. */
63
- code: string;
64
- severity: Severity;
65
- title: string;
66
- detail: string;
67
- evidence?: string[];
68
- }
69
-
70
- export interface PackedFile {
71
- /** Path inside the tarball, POSIX separators, relative to the package root. */
72
- path: string;
73
- size: number;
74
- abs: string;
75
- }
76
-
77
- const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warn: 1, info: 2 };
78
-
79
- export function sortFindings(findings: Finding[]): Finding[] {
80
- return [...findings].sort(
81
- (a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.code.localeCompare(b.code),
82
- );
83
- }
84
-
85
- export function summarise(findings: Finding[]): { errors: number; warnings: number; infos: number } {
86
- return {
87
- errors: findings.filter((f) => f.severity === "error").length,
88
- warnings: findings.filter((f) => f.severity === "warn").length,
89
- infos: findings.filter((f) => f.severity === "info").length,
90
- };
91
- }
92
-
93
- // ---------------------------------------------------------------------------
94
- // Running external tools
95
- // ---------------------------------------------------------------------------
96
-
97
- /**
98
- * `shell: true` because npm and tar are `.cmd` shims on Windows and
99
- * CreateProcess cannot execute those directly. Arguments are quoted here, and
100
- * they come from the user's own command line, so there is no untrusted input.
101
- */
102
- export function run(
103
- cmd: string,
104
- args: string[],
105
- opts: { cwd?: string; timeoutMs?: number } = {},
106
- ): { code: number; stdout: string; stderr: string; timedOut: boolean } {
107
- const quote = (s: string) => (/[\s"]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s);
108
- const line = [cmd, ...args].map(quote).join(" ");
109
- const r = spawnSync(line, {
110
- cwd: opts.cwd,
111
- encoding: "utf8",
112
- shell: true,
113
- windowsHide: true,
114
- timeout: opts.timeoutMs ?? 180_000,
115
- });
116
- return {
117
- code: r.status ?? 1,
118
- stdout: r.stdout ?? "",
119
- stderr: r.stderr ?? "",
120
- timedOut: r.error?.code === "ETIMEDOUT" || r.signal === "SIGTERM",
121
- };
122
- }
123
-
124
- /** npm buries the useful line; surface the first few non-empty ones. */
125
- export function firstLines(text: string, count: number): string {
126
- return text
127
- .split(/\r?\n/)
128
- .map((l) => l.trim())
129
- .filter(Boolean)
130
- .slice(0, count)
131
- .join("\n");
132
- }
133
-
134
- // ---------------------------------------------------------------------------
135
- // Walking the packed tree
136
- // ---------------------------------------------------------------------------
137
-
138
- const TEXT_EXT = new Set([
139
- ".js", ".mjs", ".cjs", ".mts", ".cts", ".ts", ".tsx", ".jsx",
140
- ".json", ".md", ".txt", ".sh", ".ps1", ".cmd", ".bat",
141
- ".toml", ".yml", ".yaml", ".css", ".html",
142
- ]);
143
-
144
- const MAX_SCAN_FILE = 1_000_000;
145
- const MAX_SCAN_TOTAL = 40_000_000;
146
-
147
- /** Every file in the extracted tarball, POSIX-relative paths. */
148
- export function walkFiles(root: string): PackedFile[] {
149
- const out: PackedFile[] = [];
150
- const visit = (dir: string, prefix: string) => {
151
- let entries: string[];
152
- try {
153
- entries = readdirSync(dir);
154
- } catch {
155
- return;
156
- }
157
- for (const name of entries) {
158
- const abs = join(dir, name);
159
- const rel = prefix ? `${prefix}/${name}` : name;
160
- let st;
161
- try {
162
- st = statSync(abs);
163
- } catch {
164
- continue;
165
- }
166
- if (st.isDirectory()) {
167
- if (name === ".git") continue;
168
- visit(abs, rel);
169
- } else if (st.isFile()) {
170
- out.push({ path: rel, size: st.size, abs });
171
- }
172
- }
173
- };
174
- visit(root, "");
175
- return out.sort((a, b) => a.path.localeCompare(b.path));
176
- }
177
-
178
- // ---------------------------------------------------------------------------
179
- // Entry points
180
- // ---------------------------------------------------------------------------
181
-
182
- export interface EntryRef {
183
- /** Relative path as declared, with any leading `./` stripped. */
184
- path: string;
185
- /** Which manifest field declared it, for the report. */
186
- field: string;
187
- }
188
-
189
- const STRING_ENTRY_FIELDS = [
190
- "main", "module", "browser", "types", "typings", "unpkg", "jsdelivr", "style",
191
- ] as const;
192
-
193
- function normaliseEntry(value: string): string {
194
- return value.replace(/^\.\//, "").replace(/^[/\\]+/, "").replace(/\\/g, "/").replace(/\/+$/, "");
195
- }
196
-
197
- /**
198
- * Every file the package promises to ship, from `main`/`types`/`bin`/`exports`.
199
- * Wildcard patterns are skipped: they are a promise about shape, not a file.
200
- */
201
- export function collectEntryPaths(manifest: Record<string, unknown>): EntryRef[] {
202
- const out: EntryRef[] = [];
203
- const push = (value: unknown, field: string) => {
204
- if (typeof value !== "string" || !value) return;
205
- if (value.includes("*")) return;
206
- const path = normaliseEntry(value);
207
- if (!path || path === "." || path === "./") return;
208
- if (!out.some((e) => e.path === path && e.field === field)) out.push({ path, field });
209
- };
210
-
211
- for (const field of STRING_ENTRY_FIELDS) push(manifest[field], field);
212
-
213
- const bin = manifest["bin"];
214
- if (typeof bin === "string") push(bin, "bin");
215
- else if (bin && typeof bin === "object") {
216
- for (const [name, value] of Object.entries(bin as Record<string, unknown>)) push(value, `bin.${name}`);
217
- }
218
-
219
- const walkExports = (value: unknown, field: string) => {
220
- if (typeof value === "string") push(value, field);
221
- else if (Array.isArray(value)) value.forEach((v) => walkExports(v, field));
222
- else if (value && typeof value === "object") {
223
- for (const child of Object.values(value as Record<string, unknown>)) walkExports(child, field);
224
- }
225
- };
226
- if (manifest["exports"] !== undefined) walkExports(manifest["exports"], "exports");
227
-
228
- // `files` is the third input npm uses, after `.npmignore` and `.gitignore`.
229
- // A missing entry point is usually a `files` entry that forgot the build dir.
230
- return out;
231
- }
232
-
233
- /** An entry point is satisfied by the file itself, or by a directory with that prefix. */
234
- function entryExists(path: string, files: PackedFile[]): boolean {
235
- if (files.some((f) => f.path === path)) return true;
236
- return files.some((f) => f.path.startsWith(`${path}/`));
237
- }
238
-
239
- function findCaseMismatch(path: string, files: PackedFile[]): string | undefined {
240
- const lower = path.toLowerCase();
241
- return files.find((f) => f.path.toLowerCase() === lower)?.path;
242
- }
243
-
244
- /** Text files worth scanning, read once and shared by the analysers. */
245
- export function readTexts(files: PackedFile[]): Map<string, string> {
246
- const texts = new Map<string, string>();
247
- let budget = MAX_SCAN_TOTAL;
248
- for (const file of files) {
249
- if (!TEXT_EXT.has(extname(file.path).toLowerCase())) continue;
250
- if (file.path.endsWith(".map")) continue;
251
- if (file.size > MAX_SCAN_FILE || file.size > budget) continue;
252
- try {
253
- texts.set(file.path, readFileSync(file.abs, "utf8"));
254
- budget -= file.size;
255
- } catch {
256
- /* an unreadable file is not a finding */
257
- }
258
- }
259
- return texts;
260
- }
261
-
262
- /**
263
- * The first version of this file *claimed* "the package imports it" without
264
- * ever looking. These are the patterns that make that claim true.
265
- */
266
- function peerUsage(
267
- peer: string,
268
- texts: Map<string, string>,
269
- ): { static: string[]; dynamic: string[] } {
270
- const escaped = peer.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
271
- const suffix = `(?:/[^"'\`]*)?`;
272
- const staticRe = new RegExp(
273
- `(?:\\bfrom\\s*|\\brequire\\(\\s*)["'\`]${escaped}${suffix}["'\`]`,
274
- );
275
- const dynamicRe = new RegExp(`\\bimport\\(\\s*["'\`]${escaped}${suffix}["'\`]`);
276
-
277
- const found = { static: [] as string[], dynamic: [] as string[] };
278
- for (const [path, text] of texts) {
279
- const lines = text.split(/\r?\n/);
280
- for (let i = 0; i < lines.length; i++) {
281
- const where = `${path}:${i + 1}: ${lines[i].trim().slice(0, 140)}`;
282
- if (staticRe.test(lines[i])) {
283
- if (found.static.length < 5) found.static.push(where);
284
- } else if (dynamicRe.test(lines[i])) {
285
- if (found.dynamic.length < 5) found.dynamic.push(where);
286
- }
287
- }
288
- }
289
- return found;
290
- }
291
-
292
- // ---------------------------------------------------------------------------
293
- // Static analysis of the published manifest and bytes
294
- // ---------------------------------------------------------------------------
295
-
296
- export function analyseManifest(
297
- manifest: Record<string, unknown>,
298
- files: PackedFile[],
299
- texts: Map<string, string> = new Map(),
300
- ): Finding[] {
301
- const findings: Finding[] = [];
302
- const pkgName = typeof manifest["name"] === "string" ? manifest["name"] : "(unnamed)";
303
-
304
- // TF001 — an entry point the manifest promises is not in the tarball.
305
- for (const entry of collectEntryPaths(manifest)) {
306
- if (entryExists(entry.path, files)) continue;
307
- const mismatch = findCaseMismatch(entry.path, files);
308
- findings.push({
309
- code: "TF001",
310
- severity: "error",
311
- title: `Declared entry point is missing from the tarball: ${entry.path}`,
312
- detail: mismatch
313
- ? `"${entry.field}" points at "${entry.path}" but the tarball ships "${mismatch}". The case differs and the publish will break on a case-sensitive filesystem.`
314
- : `"${entry.field}" points at "${entry.path}", which is not in the packed tarball. Check the "files" whitelist — a build directory left out of it ships a package that cannot be imported.`,
315
- evidence: [`package.json → ${entry.field}: ${entry.path}`],
316
- });
317
- }
318
-
319
- // TF002 — a required peer marked optional. This is the oc-flight-deck@0.1.0 bug.
320
- const peers = (manifest["peerDependencies"] ?? {}) as Record<string, unknown>;
321
- const peerMeta = (manifest["peerDependenciesMeta"] ?? {}) as Record<string, Record<string, unknown>>;
322
- const deps = (manifest["dependencies"] ?? {}) as Record<string, unknown>;
323
- const optionalPeers = Object.entries(peerMeta)
324
- .filter(([, meta]) => meta && meta["optional"] === true)
325
- .map(([name]) => name);
326
-
327
- for (const peer of optionalPeers) {
328
- if (!(peer in peers)) continue;
329
- const usage = peerUsage(peer, texts);
330
- const declared = `package.json → peerDependenciesMeta["${peer}"].optional: true`;
331
-
332
- if (usage.static.length) {
333
- findings.push({
334
- code: "TF002",
335
- severity: "error",
336
- title: `Peer marked optional, but shipped code imports it: ${peer}`,
337
- detail:
338
- "npm skips optional peers during install. The package installs cleanly, then dies at import time with \"Cannot find package\". This is exactly how oc-flight-deck@0.1.0 shipped broken. Remove it from peerDependenciesMeta, or make the import dynamic and guarded.",
339
- evidence: [declared, ...usage.static],
340
- });
341
- } else if (usage.dynamic.length) {
342
- findings.push({
343
- code: "TF002",
344
- severity: "warn",
345
- title: `Peer marked optional and only imported dynamically: ${peer}`,
346
- detail:
347
- "npm skips optional peers. A dynamic import fails only if that code path runs, so this is safe only if the failure is handled. Confirm the call site catches the missing module.",
348
- evidence: [declared, ...usage.dynamic],
349
- });
350
- } else {
351
- findings.push({
352
- code: "TF002",
353
- severity: "info",
354
- title: `Peer marked optional and never referenced in shipped code: ${peer}`,
355
- detail:
356
- "Consistent: npm will skip it, and nothing in the tarball asks for it. Fine — but if the host is expected to provide it, plain peerDependencies documents that better.",
357
- evidence: [declared],
358
- });
359
- }
360
- }
361
-
362
- // TF003 — a peer also declared as a runtime dependency: two instances at runtime.
363
- for (const peer of Object.keys(peers)) {
364
- if (!(peer in deps)) continue;
365
- findings.push({
366
- code: "TF003",
367
- severity: "error",
368
- title: `Peer is also a runtime dependency: ${peer}`,
369
- detail:
370
- "The package will install its own copy of a module the host also provides. Both copies load, module identity differs, and state shared across the boundary silently stops working. Keep it in peerDependencies only.",
371
- evidence: [
372
- `package.json → peerDependencies["${peer}"]: ${peers[peer]}`,
373
- `package.json → dependencies["${peer}"]: ${deps[peer]}`,
374
- ],
375
- });
376
- }
377
-
378
- // TF004 — bin entries that are not shipped.
379
- const bin = manifest["bin"];
380
- if (bin && typeof bin === "object") {
381
- for (const [name, value] of Object.entries(bin as Record<string, unknown>)) {
382
- if (typeof value !== "string") continue;
383
- const path = normaliseEntry(value);
384
- if (path && !entryExists(path, files)) {
385
- findings.push({
386
- code: "TF004",
387
- severity: "error",
388
- title: `Declared bin is missing from the tarball: ${name}`,
389
- detail: `"bin.${name}" points at "${path}", which is not packed. The installed command will fail on every run.`,
390
- });
391
- }
392
- }
393
- }
394
-
395
- // TF005 — a peer symlinked in *as a bundled dependency*.
396
- const bundledPeers = Object.keys(peers).filter((peer) =>
397
- files.some((f) => f.path.startsWith(`node_modules/${peer}/`)),
398
- );
399
- if (bundledPeers.length) {
400
- findings.push({
401
- code: "TF005",
402
- severity: "warn",
403
- title: `Peer bundled inside the tarball: ${bundledPeers.join(", ")}`,
404
- detail:
405
- "A peer that ships in the tarball is a second copy of something the host already provides. If the host loads the peer itself, module identity differs across the boundary.",
406
- evidence: bundledPeers.map((p) => `node_modules/${p}/`),
407
- });
408
- }
409
-
410
- if (findings.length === 0) {
411
- findings.push({
412
- code: "TF000",
413
- severity: "info",
414
- title: `Manifest and contents look consistent (${pkgName})`,
415
- detail: `Checked ${collectEntryPaths(manifest).length} declared entry point(s) against ${files.length} packed file(s).`,
416
- });
417
- }
418
-
419
- return findings;
420
- }
421
-
422
- /**
423
- * Machine-specific paths. A package that hardcodes an absolute path works on
424
- * exactly one machine, and the README is the most common place for it to hide.
425
- *
426
- * URL-shaped text is stripped before the bare-path patterns run, so a
427
- * `https://github.com/...` link is not mistaken for a `C:` drive — the first
428
- * version of this file did exactly that. `file://` is only ever a host path, so
429
- * it is matched against the raw line.
430
- */
431
- const PATH_PATTERNS: ReadonlyArray<{
432
- re: RegExp;
433
- label: string;
434
- severity: Severity;
435
- ignoreUrls: boolean;
436
- }> = [
437
- { re: /file:\/\/\/[A-Za-z]:[\\/]/, label: "an absolute Windows path in a file:// URL", severity: "error", ignoreUrls: false },
438
- { re: /file:\/\/(?:\/)?(?:Users|home)\/[A-Za-z0-9._-]+\//, label: "an absolute home path in a file:// URL", severity: "error", ignoreUrls: false },
439
- { re: /file:\/\//, label: "a file:// URL", severity: "warn", ignoreUrls: false },
440
- { re: /(?<![\w:/])[A-Za-z]:[\\/]/, label: "an absolute Windows path", severity: "warn", ignoreUrls: true },
441
- { re: /(?<![\w.-])\/(?:Users|home)\/[A-Za-z0-9._-]+\//, label: "an absolute POSIX home path", severity: "warn", ignoreUrls: true },
442
- ];
443
-
444
- const URL_SHAPED = /https?:\/\/\S+/gi;
445
-
446
- export function scanContents(texts: Map<string, string>): Finding[] {
447
- const findings: Finding[] = [];
448
- const hits = new Map<string, { label: string; severity: Severity; evidence: string[] }>();
449
-
450
- for (const [path, text] of texts) {
451
- const lines = text.split(/\r?\n/);
452
- for (let i = 0; i < lines.length; i++) {
453
- const line = lines[i];
454
- const withoutUrls = line.replace(URL_SHAPED, "");
455
- for (const { re, label, severity, ignoreUrls } of PATH_PATTERNS) {
456
- if (!re.test(ignoreUrls ? withoutUrls : line)) continue;
457
- const bucket = hits.get(label) ?? { label, severity, evidence: [] };
458
- if (bucket.evidence.length < 5) {
459
- bucket.evidence.push(`${path}:${i + 1}: ${line.trim().slice(0, 140)}`);
460
- }
461
- hits.set(label, bucket);
462
- break;
463
- }
464
- }
465
- }
466
-
467
- let index = 0;
468
- for (const bucket of hits.values()) {
469
- findings.push({
470
- code: `TF${(10 + index++).toString().padStart(3, "0")}`,
471
- severity: bucket.severity,
472
- title: `Packaged files reference ${bucket.label}`,
473
- detail:
474
- "A path that names one machine is a package that works on one machine. It usually means a default value, a config, or an example was written for a local checkout and packed as-is.",
475
- evidence: bucket.evidence,
476
- });
477
- }
478
-
479
- return findings;
480
- }
481
-
482
- // ---------------------------------------------------------------------------
483
- // Pack, extract, install
484
- // ---------------------------------------------------------------------------
485
-
486
- export function packPackage(dir: string, dest: string): { tgz?: string; error?: string } {
487
- const r = run("npm", ["pack", "--pack-destination", dest, "--loglevel=error"], {
488
- cwd: dir,
489
- timeoutMs: 180_000,
490
- });
491
- if (r.timedOut) return { error: "npm pack timed out" };
492
- if (r.code !== 0) return { error: firstLines(r.stderr || r.stdout, 6) || "npm pack failed" };
493
-
494
- const tgzs = readdirSync(dest).filter((f) => f.endsWith(".tgz"));
495
- if (!tgzs.length) return { error: "npm pack reported success but produced no tarball" };
496
- return { tgz: join(dest, tgzs[0]) };
497
- }
498
-
499
- export function extractTarball(tgz: string, dest: string): { root?: string; error?: string } {
500
- mkdirSync(dest, { recursive: true });
501
- const r = run("tar", ["-xzf", tgz, "-C", dest], { timeoutMs: 120_000 });
502
- if (r.timedOut) return { error: "tar timed out" };
503
- if (r.code !== 0) return { error: firstLines(r.stderr || r.stdout, 6) || "tar failed" };
504
-
505
- // npm tarballs nest everything under `package/`.
506
- const nested = join(dest, "package");
507
- return { root: existsSync(nested) ? nested : dest };
508
- }
509
-
510
- /**
511
- * A real install in a throwaway project. This is the step `npm pack --dry-run`
512
- * cannot do, and the step that would have caught the 0.1.0 release.
513
- */
514
- export function installAndCheck(
515
- manifest: Record<string, unknown>,
516
- tgz: string,
517
- sandbox: string,
518
- ): Finding[] {
519
- const findings: Finding[] = [];
520
- const project = join(sandbox, "project");
521
- mkdirSync(project, { recursive: true });
522
- writeFileSync(
523
- join(project, "package.json"),
524
- JSON.stringify({ name: "testflight-sandbox", version: "0.0.0", private: true }, null, 2),
525
- );
526
-
527
- const r = run(
528
- "npm",
529
- ["install", tgz, "--no-audit", "--no-fund", "--ignore-scripts", "--loglevel=error"],
530
- { cwd: project, timeoutMs: 300_000 },
531
- );
532
-
533
- if (r.timedOut || r.code !== 0) {
534
- const message = firstLines(r.stderr || r.stdout, 8);
535
- const network = /\b(ENOTFOUND|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|network|offline)\b/i.test(message);
536
- findings.push({
537
- code: "TF020",
538
- severity: network ? "warn" : "error",
539
- title: network ? "Install could not reach the registry" : "Install failed in a clean project",
540
- detail: network
541
- ? "The install could not resolve against the registry, so peer resolution was not verified. Re-run with a network connection to complete the check."
542
- : "Installing the packed tarball into an empty project failed. This is the error a user sees on `npm install`.",
543
- evidence: message ? message.split("\n") : [],
544
- });
545
- return findings;
546
- }
547
-
548
- const modules = join(project, "node_modules");
549
- const peers = (manifest["peerDependencies"] ?? {}) as Record<string, unknown>;
550
- const peerMeta = (manifest["peerDependenciesMeta"] ?? {}) as Record<string, Record<string, unknown>>;
551
-
552
- for (const [peer, range] of Object.entries(peers)) {
553
- const installed = existsSync(join(modules, ...peer.split("/"), "package.json"));
554
- const optional = peerMeta[peer]?.["optional"] === true;
555
- if (installed) continue;
556
- if (optional) {
557
- findings.push({
558
- code: "TF021",
559
- severity: "info",
560
- title: `Optional peer was skipped, as marked: ${peer}`,
561
- detail: "Correct npm behaviour. It is only a bug if shipped code imports it — TF002 covers that.",
562
- });
563
- } else {
564
- findings.push({
565
- code: "TF022",
566
- severity: "error",
567
- title: `Required peer did not resolve after install: ${peer}`,
568
- detail: `The manifest requires "${peer}@${range}" but a clean install did not provide it. Users will hit the same failure.`,
569
- });
570
- }
571
- }
572
-
573
- const installedName =
574
- typeof manifest["name"] === "string" ? manifest["name"] : "";
575
- if (installedName && !existsSync(join(modules, ...installedName.split("/"), "package.json"))) {
576
- findings.push({
577
- code: "TF023",
578
- severity: "error",
579
- title: `The package itself is missing after install: ${installedName}`,
580
- detail: "npm install succeeded but the package is not in node_modules. The tarball manifest is inconsistent.",
581
- });
582
- }
583
-
584
- return findings;
585
- }
586
-
587
- /** `--import`: load the declared entry points from the *installed* package. */
588
- export async function importEntries(
589
- manifest: Record<string, unknown>,
590
- sandbox: string,
591
- ): Promise<Finding[]> {
592
- const findings: Finding[] = [];
593
- const name = typeof manifest["name"] === "string" ? manifest["name"] : "";
594
- if (!name) return findings;
595
-
596
- const root = join(sandbox, "project", "node_modules", ...name.split("/"));
597
- const entries = collectEntryPaths(manifest).filter((e) => e.field !== "types" && e.field !== "typings");
598
- const seen = new Set<string>();
599
-
600
- for (const entry of entries) {
601
- const target = join(root, ...entry.path.split("/"));
602
- if (seen.has(target) || !existsSync(target)) continue;
603
- seen.add(target);
604
- if (!/\.[cm]?js$/.test(target)) continue;
605
- try {
606
- await import(pathToFileURL(target).href);
607
- } catch (error) {
608
- const message = error instanceof Error ? error.message : String(error);
609
- const missingPeer = /Cannot find (?:package|module)\s+'?([^'\s]+)'?/.exec(message);
610
- findings.push({
611
- code: "TF030",
612
- severity: missingPeer ? "error" : "warn",
613
- title: `Import failed: ${entry.field} → ${entry.path}`,
614
- detail: missingPeer
615
- ? `Loading the installed entry point could not resolve "${missingPeer[1]}". This is the failure a user gets on first run.`
616
- : "Loading the installed entry point threw. If the package expects a host runtime this may be expected — read the message before treating it as a packaging fault.",
617
- evidence: [`${entry.path}: ${message.split(/\r?\n/)[0].slice(0, 200)}`],
618
- });
619
- }
620
- }
621
-
622
- return findings;
623
- }
624
-
625
- // ---------------------------------------------------------------------------
626
- // Orchestration
627
- // ---------------------------------------------------------------------------
628
-
629
- export interface Options {
630
- json: boolean;
631
- keep: boolean;
632
- noInstall: boolean;
633
- doImport: boolean;
634
- }
635
-
636
- export async function check(target: string, opts: Options): Promise<{
637
- findings: Finding[];
638
- sandbox: string | null;
639
- packageName: string;
640
- packageVersion: string;
641
- fileCount: number;
642
- failed: boolean;
643
- fatal?: string;
644
- }> {
645
- const sandbox = mkdtempSync(join(tmpdir(), "testflight-"));
646
- const empty = { findings: [] as Finding[], sandbox: null, packageName: "", packageVersion: "", fileCount: 0, failed: false };
647
-
648
- try {
649
- // 1. pack — always from a real tarball, never from the checkout.
650
- let tgz: string;
651
- const resolved = resolve(target);
652
- if (!existsSync(resolved)) {
653
- return { ...empty, fatal: `no such file or directory: ${target}`, failed: true };
654
- }
655
-
656
- if (resolved.toLowerCase().endsWith(".tgz")) {
657
- tgz = resolved;
658
- } else {
659
- const packed = packPackage(resolved, sandbox);
660
- if (!packed.tgz) {
661
- return { ...empty, fatal: `npm pack failed: ${packed.error}`, failed: true };
662
- }
663
- tgz = packed.tgz;
664
- }
665
-
666
- // 2. extract — read the published bytes, not the working copy.
667
- const extracted = extractTarball(tgz, join(sandbox, "pkg"));
668
- if (!extracted.root) {
669
- return { ...empty, fatal: `could not extract tarball: ${extracted.error}`, failed: true };
670
- }
671
-
672
- const manifestPath = join(extracted.root, "package.json");
673
- if (!existsSync(manifestPath)) {
674
- return { ...empty, fatal: "the tarball has no package.json", failed: true };
675
- }
676
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as Record<string, unknown>;
677
- const files = walkFiles(extracted.root);
678
- const texts = readTexts(files);
679
-
680
- // 3. static checks
681
- const findings: Finding[] = [];
682
- findings.push(...analyseManifest(manifest, files, texts));
683
- findings.push(...scanContents(texts));
684
-
685
- // 4. install + peers
686
- if (!opts.noInstall) {
687
- findings.push(...installAndCheck(manifest, tgz, sandbox));
688
- }
689
-
690
- // 5. optional import
691
- if (opts.doImport && !opts.noInstall) {
692
- findings.push(...(await importEntries(manifest, sandbox)));
693
- }
694
-
695
- // TF000 is the "everything checked out" marker. It is only worth printing
696
- // when there is nothing else to say.
697
- const reportable = findings.filter((f) => f.code !== "TF000");
698
- const finalFindings = reportable.length ? sortFindings(reportable) : findings;
699
-
700
- return {
701
- findings: finalFindings,
702
- sandbox: opts.keep ? sandbox : null,
703
- packageName: typeof manifest["name"] === "string" ? manifest["name"] : "(unnamed)",
704
- packageVersion: typeof manifest["version"] === "string" ? manifest["version"] : "(unversioned)",
705
- fileCount: files.length,
706
- failed: finalFindings.some((f) => f.severity === "error"),
707
- };
708
- } catch (error) {
709
- return { ...empty, fatal: error instanceof Error ? error.message : String(error), failed: true };
710
- } finally {
711
- if (!opts.keep) {
712
- try {
713
- rmSync(sandbox, { recursive: true, force: true });
714
- } catch {
715
- /* the sandbox is in the OS temp dir; leaving it is harmless */
716
- }
717
- }
718
- }
719
- }
720
-
721
- // ---------------------------------------------------------------------------
722
- // CLI
723
- // ---------------------------------------------------------------------------
724
-
725
- const USAGE = `testflight — verify the artifact you are about to publish.
726
-
727
- testflight <dir|tarball> pack, extract, inspect, install, resolve
728
- testflight . --no-install static checks only (fast, no network)
729
- testflight . --import also load the declared entry points
730
- testflight . --json machine-readable output
731
- testflight . --keep keep the sandbox and print its path
732
- testflight --help
733
-
734
- Exit codes: 0 clean (warnings allowed), 1 findings, 2 could not run.
735
- `;
736
-
737
- const SEVERITY_LABEL: Record<Severity, string> = { error: "FAIL", warn: "WARN", info: "ok " };
738
-
739
- export function formatReport(result: Awaited<ReturnType<typeof check>>): string {
740
- const lines: string[] = [];
741
- const { errors, warnings } = summarise(result.findings);
742
-
743
- lines.push(`${result.packageName}@${result.packageVersion} — ${result.fileCount} packed file(s)`);
744
- lines.push("");
745
-
746
- if (result.fatal) {
747
- lines.push(` FAIL ${result.fatal}`);
748
- lines.push("");
749
- lines.push("Could not run the check.");
750
- return lines.join("\n");
751
- }
752
-
753
- for (const finding of result.findings) {
754
- lines.push(` ${SEVERITY_LABEL[finding.severity]} ${finding.code} ${finding.title}`);
755
- lines.push(` ${finding.detail}`);
756
- for (const line of finding.evidence ?? []) lines.push(` · ${line}`);
757
- lines.push("");
758
- }
759
-
760
- if (result.sandbox) lines.push(`sandbox kept: ${result.sandbox}`);
761
- if (errors) lines.push(`${errors} failure(s), ${warnings} warning(s). The package is not safe to publish.`);
762
- else if (warnings) lines.push(`Clean on failures, ${warnings} warning(s) worth reading.`);
763
- else lines.push("Clean. Packaged bytes, manifest, and peer resolution all check out.");
764
- lines.push("");
765
- lines.push("Does not prove host-runtime behaviour: modules the host injects are not reproduced here.");
766
-
767
- return lines.join("\n");
768
- }
769
-
770
- function parseArgs(argv: string[]): { target?: string; opts: Options; help: boolean } {
771
- const opts: Options = { json: false, keep: false, noInstall: false, doImport: false };
772
- let target: string | undefined;
773
- for (const arg of argv) {
774
- if (arg === "--help" || arg === "-h") return { opts, help: true };
775
- else if (arg === "--json") opts.json = true;
776
- else if (arg === "--keep") opts.keep = true;
777
- else if (arg === "--no-install") opts.noInstall = true;
778
- else if (arg === "--import") opts.doImport = true;
779
- else if (arg.startsWith("-")) return { opts, help: false };
780
- else if (!target) target = arg;
781
- }
782
- return { target, opts, help: false };
783
- }
784
-
785
- export async function main(argv: string[]): Promise<number> {
786
- const { target, opts, help } = parseArgs(argv);
787
- if (help || !target) {
788
- process.stdout.write(USAGE);
789
- return help ? 0 : 2;
790
- }
791
-
792
- const result = await check(target, opts);
793
-
794
- if (opts.json) {
795
- process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
796
- } else {
797
- process.stdout.write(`${formatReport(result)}\n`);
798
- }
799
-
800
- if (result.fatal) return 2;
801
- return result.failed ? 1 : 0;
802
- }
803
-
804
- if (import.meta.main) {
805
- process.exit(await main(process.argv.slice(2)));
806
- }