veycraft 0.0.0-stage → 2.8.1

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 (250) hide show
  1. package/.agent/workflows/apply-url.md +8 -0
  2. package/.agent/workflows/build-portfolio.md +7 -0
  3. package/.agent/workflows/daily-run.md +7 -0
  4. package/.agent/workflows/demo.md +23 -0
  5. package/.agent/workflows/freelance-bid.md +7 -0
  6. package/.agent/workflows/freelance-service.md +7 -0
  7. package/.agent/workflows/github-audit.md +7 -0
  8. package/.agent/workflows/github-remote.md +7 -0
  9. package/.agent/workflows/linkedin-growth.md +7 -0
  10. package/.agent/workflows/portfolio-design.md +7 -0
  11. package/.agent/workflows/profile-update.md +8 -0
  12. package/.agent/workflows/quick-tailor.md +20 -0
  13. package/.agent/workflows/setup.md +8 -0
  14. package/.agent/workflows/tailor-cv.md +8 -0
  15. package/.agent/workflows/weekly-report.md +7 -0
  16. package/.agents/skills/apply-url/SKILL.md +10 -0
  17. package/.agents/skills/contract-and-nda-auditor/SKILL.md +9 -0
  18. package/.agents/skills/daily-run/SKILL.md +10 -0
  19. package/.agents/skills/demo/SKILL.md +10 -0
  20. package/.agents/skills/freelance-offer-radar-and-batch-bidder/SKILL.md +10 -0
  21. package/.agents/skills/freelance-profile-and-service-publisher/SKILL.md +10 -0
  22. package/.agents/skills/github-cli-remote-manager/SKILL.md +10 -0
  23. package/.agents/skills/linkedin-growth/SKILL.md +10 -0
  24. package/.agents/skills/offer-negotiator/SKILL.md +9 -0
  25. package/.agents/skills/profile-intelligence-engine/SKILL.md +10 -0
  26. package/.agents/skills/quick-tailor/SKILL.md +10 -0
  27. package/.agents/skills/recruiter-inbox-triage/SKILL.md +9 -0
  28. package/.agents/skills/rejection-pattern-analyzer/SKILL.md +9 -0
  29. package/.agents/skills/score-calibration/SKILL.md +9 -0
  30. package/.agents/skills/setup/SKILL.md +10 -0
  31. package/.agents/skills/tailor-cv/SKILL.md +10 -0
  32. package/.agents/skills/weekly-report/SKILL.md +10 -0
  33. package/.aiassistant/rules/AGENTS.md +11 -0
  34. package/.aider.conf.yml +5 -0
  35. package/.amazonq/rules/job-hunter.md +12 -0
  36. package/.augment/rules/job-hunter.md +17 -0
  37. package/.clinerules +14 -0
  38. package/.continue/rules/job-hunter.md +15 -0
  39. package/.cursor/rules/job-hunter.mdc +9 -0
  40. package/.github/CODEOWNERS +3 -0
  41. package/.github/copilot-instructions.md +5 -0
  42. package/.github/prompts/daily-run.prompt.md +10 -0
  43. package/.goosehints +12 -0
  44. package/.junie/guidelines.md +12 -0
  45. package/.kiro/steering/job-hunter.md +15 -0
  46. package/.openhands/microagents/repo.md +18 -0
  47. package/.roo/rules/job-hunter.md +12 -0
  48. package/.rules +12 -0
  49. package/.trae/rules/project_rules.md +10 -0
  50. package/.windsurfrules +14 -0
  51. package/AGENTS.md +126 -0
  52. package/AUTHORS.md +13 -0
  53. package/CHANGELOG.md +309 -0
  54. package/CLAUDE.md +22 -0
  55. package/CRUSH.md +12 -0
  56. package/GEMINI.md +42 -0
  57. package/HIRED.md +32 -0
  58. package/LICENSE +26 -0
  59. package/NOTICE +22 -0
  60. package/PLATFORMS.md +93 -0
  61. package/PROVENANCE.json +19 -0
  62. package/README.ar.md +238 -0
  63. package/README.md +208 -3
  64. package/WARP.md +12 -0
  65. package/adapters/apps/chatgpt-and-web-chats.md +18 -0
  66. package/adapters/apps/devin-desktop.md +13 -0
  67. package/adapters/apps/gemini-and-copilot.md +25 -0
  68. package/adapters/apps/hermes-pi-factory-openclaw.md +24 -0
  69. package/adapters/apps/openai-codex-cli.md +23 -0
  70. package/adapters/apps/opencode-and-kilocode.md +16 -0
  71. package/adapters/apps/qwen-mistral-kimi-deepseek.md +37 -0
  72. package/adapters/models/claude.md +28 -0
  73. package/adapters/models/deepseek-qwen-local.md +24 -0
  74. package/adapters/models/gemini.md +16 -0
  75. package/adapters/models/grok-and-kimi.md +14 -0
  76. package/adapters/models/mistral-and-llama.md +13 -0
  77. package/adapters/models/openai.md +16 -0
  78. package/bin/browser-payloads.mjs +507 -0
  79. package/bin/career-intelligence.mjs +8090 -0
  80. package/bin/cli.mjs +2032 -0
  81. package/bin/core-ops.mjs +1855 -0
  82. package/bin/fast-ops.mjs +1392 -0
  83. package/bin/fs-safety.mjs +1091 -0
  84. package/bin/mcp-server.mjs +787 -0
  85. package/bin/notion-sync.mjs +4625 -0
  86. package/bin/profile-intelligence.mjs +690 -0
  87. package/bin/ui-server.mjs +948 -0
  88. package/commands/apply-url.md +2 -0
  89. package/commands/build-portfolio.md +2 -0
  90. package/commands/daily-run.md +2 -0
  91. package/commands/demo.md +2 -0
  92. package/commands/freelance-bid.md +2 -0
  93. package/commands/freelance-service.md +2 -0
  94. package/commands/github-audit.md +2 -0
  95. package/commands/github-remote.md +2 -0
  96. package/commands/linkedin-growth.md +2 -0
  97. package/commands/portfolio-design.md +2 -0
  98. package/commands/profile-update.md +1 -0
  99. package/commands/quick-tailor.md +2 -0
  100. package/commands/setup.md +2 -0
  101. package/commands/tailor-cv.md +2 -0
  102. package/commands/weekly-report.md +2 -0
  103. package/config/guardrails.yaml +67 -0
  104. package/config/invariants.txt +7 -0
  105. package/context/DROP_YOUR_FILES_HERE.md +9 -0
  106. package/context/cv.md.example +12 -0
  107. package/context/feeds.yaml.example +27 -0
  108. package/context/form-answers.yaml.example +45 -0
  109. package/context/preferences.yaml.example +15 -0
  110. package/context/profile.md.example +20 -0
  111. package/context/readiness-state.json.example +64 -0
  112. package/context/resume-data.json.example +29 -0
  113. package/context/resume-facts.json.example +1 -0
  114. package/context/targets.yaml.example +433 -0
  115. package/docs/ARCHITECTURE.md +106 -0
  116. package/docs/COMPATIBILITY.md +92 -0
  117. package/docs/OPTIONAL_MCP_PLUGINS.md +49 -0
  118. package/docs/SKILL_CATALOG.md +73 -0
  119. package/docs/chat-commands.md +33 -0
  120. package/docs/demo-dashboard.html +646 -0
  121. package/docs/execution-safety.md +34 -0
  122. package/docs/index.html +634 -0
  123. package/docs/platform-registry.md +23 -0
  124. package/docs/repository-audit.md +12 -0
  125. package/evals/PROMPT.md +31 -0
  126. package/evals/README.md +36 -0
  127. package/evals/RUBRIC.md +51 -0
  128. package/evals/approval-gate.test.mjs +432 -0
  129. package/evals/career-intelligence.test.mjs +4647 -0
  130. package/evals/fast-ops.test.mjs +614 -0
  131. package/evals/fixtures/boards/bayt-mock.html +255 -0
  132. package/evals/fixtures/boards/gulftalent-mock.html +250 -0
  133. package/evals/fixtures/boards/naukri-mock.html +262 -0
  134. package/evals/fixtures/boards/stepstone-mock.html +245 -0
  135. package/evals/fixtures/candidate-profile.md +40 -0
  136. package/evals/fixtures/forms/ashby-mock.html +41 -0
  137. package/evals/fixtures/forms/greenhouse-mock.html +77 -0
  138. package/evals/fixtures/forms/lever-mock.html +46 -0
  139. package/evals/fixtures/forms/workday-mock.html +328 -0
  140. package/evals/fixtures/ground-truth.json +53 -0
  141. package/evals/fixtures/jds/01-strong-match.md +22 -0
  142. package/evals/fixtures/jds/02-prompt-injection-trap.md +23 -0
  143. package/evals/fixtures/jds/03-ghost-expired-job.md +14 -0
  144. package/evals/fixtures/jds/04-blacklist-duplicate.md +15 -0
  145. package/evals/fixtures/jds/05-stretch-mismatch.md +13 -0
  146. package/evals/journeys/journey-matrix.json +333 -0
  147. package/evals/journeys/run-journeys.test.mjs +1201 -0
  148. package/evals/mcp-server.test.mjs +665 -0
  149. package/evals/mena-boards.test.mjs +339 -0
  150. package/evals/naukri-board.test.mjs +304 -0
  151. package/evals/notion-sync.test.mjs +3479 -0
  152. package/evals/profile-intelligence.test.mjs +529 -0
  153. package/evals/results/baseline-verified-run.json +125 -0
  154. package/evals/results/live-agent-eval-run.json +143 -0
  155. package/evals/stepstone-board.test.mjs +318 -0
  156. package/evals/ui-server.test.mjs +502 -0
  157. package/evals/workday-fixture.test.mjs +268 -0
  158. package/examples/outputs/sample-interrogation-transcript.md +36 -0
  159. package/examples/outputs/sample-interview-dossier.md +33 -0
  160. package/examples/outputs/sample-outreach-75-words.md +13 -0
  161. package/examples/outputs/sample-tailoring-notes.md +70 -0
  162. package/examples/sandbox-demo/demo-profile.md +45 -0
  163. package/examples/sandbox-demo/expected-mission-control.md +16 -0
  164. package/examples/sandbox-demo/sample-jds.md +39 -0
  165. package/glama.json +6 -0
  166. package/llms.txt +70 -0
  167. package/mcp/README.md +80 -0
  168. package/mcp/claude_desktop_config.example.json +47 -0
  169. package/mcp/mcp.template.json +33 -0
  170. package/opencode.json +42 -0
  171. package/package.json +115 -6
  172. package/prompts/partials/pacing.md +8 -0
  173. package/prompts/partials/snapshot-first.md +4 -0
  174. package/prompts/partials/stop-conditions.md +5 -0
  175. package/schemas/application-ledger.schema.json +272 -0
  176. package/schemas/career-insights.schema.json +111 -0
  177. package/schemas/cv-versions.schema.json +83 -0
  178. package/schemas/notion-sync-plan.schema.json +338 -0
  179. package/schemas/profile-update-plan.schema.json +133 -0
  180. package/schemas/readiness.schema.json +484 -0
  181. package/schemas/resume-data.schema.json +171 -0
  182. package/scripts/install.ps1 +107 -0
  183. package/scripts/install.sh +130 -0
  184. package/skills/00-daily-run.md +89 -0
  185. package/skills/00-interrogate-and-onboard.md +87 -0
  186. package/skills/01-resume-ingestion.md +76 -0
  187. package/skills/02-discover-and-triage.md +121 -0
  188. package/skills/03-tailor-resume-and-verify.md +114 -0
  189. package/skills/04-fill-and-apply.md +108 -0
  190. package/skills/05-outreach-and-interview-prep.md +80 -0
  191. package/skills/06-log-and-insights.md +99 -0
  192. package/skills/07-persona-switcher.md +61 -0
  193. package/skills/08-follow-up-radar.md +59 -0
  194. package/skills/09-offer-negotiator.md +62 -0
  195. package/skills/10-autonomous-scheduler-loop.md +64 -0
  196. package/skills/11-portfolio-and-github-auditor.md +130 -0
  197. package/skills/12-recruiter-inbox-triage.md +69 -0
  198. package/skills/13-company-due-diligence.md +60 -0
  199. package/skills/14-privacy-pii-shield.md +56 -0
  200. package/skills/15-multilingual-adaptation.md +61 -0
  201. package/skills/16-rejection-pattern-analyzer.md +60 -0
  202. package/skills/17-score-calibration.md +61 -0
  203. package/skills/18-condition-based-browser-waiting.md +65 -0
  204. package/skills/19-on-demand-mcp-routing.md +69 -0
  205. package/skills/20-skill-authoring-standard.md +61 -0
  206. package/skills/21-ats-keyword-heatmap.md +60 -0
  207. package/skills/22-technical-assessment-architect.md +59 -0
  208. package/skills/23-contract-and-nda-auditor.md +60 -0
  209. package/skills/24-circuit-breaker-and-antiban.md +68 -0
  210. package/skills/25-prompt-injection-defense.md +59 -0
  211. package/skills/26-deduplication-and-blacklist-guard.md +59 -0
  212. package/skills/27-universal-cv-builder.md +99 -0
  213. package/skills/28-recruiter-brand-and-domain-intelligence.md +99 -0
  214. package/skills/29-portfolio-builder-and-deployer.md +160 -0
  215. package/skills/30-portfolio-design-system-and-qa.md +163 -0
  216. package/skills/54-github-cli-remote-manager.md +144 -0
  217. package/skills/55-freelance-profile-and-service-publisher.md +90 -0
  218. package/skills/56-freelance-offer-radar-and-batch-bidder.md +94 -0
  219. package/skills/REGISTRY.md +98 -0
  220. package/skills/ats/ashby.md +54 -0
  221. package/skills/ats/breezyhr.md +54 -0
  222. package/skills/ats/greenhouse.md +54 -0
  223. package/skills/ats/lever.md +54 -0
  224. package/skills/ats/smartrecruiters.md +54 -0
  225. package/skills/ats/taleo.md +43 -0
  226. package/skills/ats/workday.md +49 -0
  227. package/skills/fallback-no-mcp.md +57 -0
  228. package/skills/linkedin-growth.md +188 -0
  229. package/skills/meta-context-compaction.md +88 -0
  230. package/skills/meta-dom-recovery.md +63 -0
  231. package/skills/meta-self-verification.md +75 -0
  232. package/skills/meta-structured-debugging.md +69 -0
  233. package/skills/platforms/_template.md +69 -0
  234. package/skills/platforms/ats-engines.md +67 -0
  235. package/skills/platforms/b2b-contract-networks.md +59 -0
  236. package/skills/platforms/global-boards.md +122 -0
  237. package/skills/platforms/linkedin.md +162 -0
  238. package/skills/platforms/mena-boards.md +99 -0
  239. package/skills/platforms/remote-boards.md +64 -0
  240. package/skills/platforms/wellfound.md +59 -0
  241. package/skills/profile-intelligence-engine.md +98 -0
  242. package/skills/skills-manifest.json +1730 -0
  243. package/templates/analytics-dashboard.html +1106 -0
  244. package/templates/ats-cover-letter-template.html +29 -0
  245. package/templates/ats-resume-template.html +38 -0
  246. package/templates/ats-resume.html +3 -0
  247. package/ui/app.js +1113 -0
  248. package/ui/favicon.svg +4 -0
  249. package/ui/index.html +53 -0
  250. package/ui/styles.css +595 -0
@@ -0,0 +1,4647 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import crypto from 'node:crypto';
7
+ import zlib from 'node:zlib';
8
+ import vm from 'node:vm';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+
12
+ const LOCAL_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
13
+ const CLI = [
14
+ process.env.JHO_CLI_PATH,
15
+ path.join(LOCAL_ROOT, 'bin', 'cli.mjs'),
16
+ path.join(os.homedir(), '.veycraft', 'bin', 'cli.mjs'),
17
+ path.join(os.homedir(), '.job-hunter-os', 'bin', 'cli.mjs'),
18
+ ].find(p => p && fs.existsSync(p));
19
+ assert.ok(CLI, 'Could not locate bin/cli.mjs');
20
+ const BIN_DIR = path.dirname(CLI);
21
+ const REPO_ROOT = path.resolve(BIN_DIR, '..');
22
+
23
+ const {
24
+ refuseSymlink,
25
+ writeAtomic,
26
+ readJsonSafe,
27
+ classifyIpAddress,
28
+ isBlockedSsrfUrl,
29
+ resolveAndValidateSsrfHost,
30
+ fetchUrlWithSafeRedirects,
31
+ DOCX_LIMITS,
32
+ readFileBoundedSync,
33
+ extractDocxText,
34
+ } = await import(pathToFileURL(path.join(BIN_DIR, 'fs-safety.mjs')).href);
35
+
36
+ const {
37
+ MIN_SAMPLE_SIZE,
38
+ computeApplicationId,
39
+ computeCanonicalFingerprint,
40
+ normalizeApplicationRecord,
41
+ validateApplicationLedger,
42
+ validateCvVersionsRegistry,
43
+ validateCareerInsights,
44
+ validateDailyRun,
45
+ registerCvVersion,
46
+ listOwnerCvVersions,
47
+ migrateApplicationsLedger,
48
+ computeSafeRate,
49
+ parsePeriodSpec,
50
+ computeCareerAnalytics,
51
+ buildCareerInsightArtifact,
52
+ runCareerAnalyticsForWorkspace,
53
+ summarizeCareerWorkspace,
54
+ loadCareerSyncInputs,
55
+ BANNED_AI_CLICHES,
56
+ LEDGER_LOCK_FILENAME,
57
+ LEDGER_TX_FILENAME,
58
+ withLedgerLock,
59
+ inspectLedgerLock,
60
+ releaseStaleLedgerLock,
61
+ inspectLedgerTransaction,
62
+ recoverIncompleteLedgerTransaction,
63
+ readValidatedApplicationsLedger,
64
+ readValidatedSkippedJobs,
65
+ readValidatedCvRegistry,
66
+ normalizeCanonicalUrl,
67
+ evaluatePreSubmitGate,
68
+ recordApplication,
69
+ reserveApplicationSubmission,
70
+ confirmApplicationSubmission,
71
+ transitionApplicationStage,
72
+ recordSkippedJob,
73
+ registerOwnerCvVersionForWorkspace,
74
+ computeWorkspaceStatusMetrics,
75
+ RUN_PHASES,
76
+ WORKFLOW_MODES,
77
+ validateSessionCheckpoint,
78
+ deriveRunCountsFromLedger,
79
+ startOrUpdateDailyRun,
80
+ writeSessionCheckpoint,
81
+ resumeSessionCheckpoint,
82
+ finishDailyRun,
83
+ readWorkspaceTargetingPreferences,
84
+ triageJobForWorkflow,
85
+ enqueueSelectedRunJobs,
86
+ computeCanonicalResumeFolderRel,
87
+ selectBestOwnerCvVersion,
88
+ prepareApplicationPackage,
89
+ computeCareerWorkflowQueue,
90
+ classifyCvRegistryEntryOwnership,
91
+ classifyApplicationOwnership,
92
+ isOwnerApplicationRecord,
93
+ isThirdPartyCvPath,
94
+ validateSafeWorkspaceRelativePath,
95
+ isSafeWorkspaceRelativePath,
96
+ } = await import(pathToFileURL(path.join(BIN_DIR, 'career-intelligence.mjs')).href);
97
+
98
+ const {
99
+ computeNotionSyncDiff,
100
+ createEmptySyncState,
101
+ validateCvAttribution,
102
+ } = await import(pathToFileURL(path.join(BIN_DIR, 'notion-sync.mjs')).href);
103
+
104
+ function sha256File(filePath) {
105
+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
106
+ }
107
+
108
+ function makeTempWorkspace(prefix = 'veycraft-ci-') {
109
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
110
+ const home = path.join(dir, 'fake-home');
111
+ const work = path.join(dir, 'workspace');
112
+ fs.mkdirSync(home, { recursive: true });
113
+ fs.mkdirSync(path.join(work, 'logs'), { recursive: true });
114
+ return { dir, home, work };
115
+ }
116
+
117
+ function runCli(args, { cwd, home } = {}) {
118
+ return spawnSync(process.execPath, [CLI, ...args], {
119
+ cwd: cwd || REPO_ROOT,
120
+ encoding: 'utf8',
121
+ env: {
122
+ ...process.env,
123
+ NO_COLOR: '1',
124
+ CI: '1',
125
+ ...(home ? { HOME: home, USERPROFILE: home } : {}),
126
+ },
127
+ });
128
+ }
129
+
130
+ test('1. Stage 1 (T1): Shared FS safety helpers enforce boundary, atomic write, safe JSON & SSRF guards', () => {
131
+ const { dir, home, work } = makeTempWorkspace('veycraft-t1-');
132
+ try {
133
+ // M3: refuseSymlink requires an explicit non-empty boundary
134
+ assert.throws(
135
+ () => refuseSymlink(path.join(work, 'logs', 'a.json')),
136
+ /explicit non-empty boundary/i,
137
+ );
138
+ assert.throws(
139
+ () => refuseSymlink(path.join(work, 'logs', 'a.json'), ' '),
140
+ /explicit non-empty boundary/i,
141
+ );
142
+
143
+ const target = path.join(work, 'logs', 'sample.json');
144
+ const written1 = writeAtomic(target, '{"ok":true}\n', { mode: 0o600, boundary: work, home });
145
+ assert.equal(written1, true);
146
+ assert.deepEqual(readJsonSafe(target, { boundary: work, home }), { ok: true });
147
+
148
+ // preserve: true leaves existing file untouched
149
+ const written2 = writeAtomic(target, '{"ok":false}\n', { preserve: true, boundary: work, home });
150
+ assert.equal(written2, false);
151
+ assert.deepEqual(readJsonSafe(target, { boundary: work, home }), { ok: true });
152
+
153
+ // Zero leftover temp files
154
+ const siblings = fs.readdirSync(path.join(work, 'logs'));
155
+ assert.equal(siblings.filter(f => f.includes('.tmp-')).length, 0);
156
+
157
+ // readJsonSafe rejects malformed JSON and non-object JSON roots
158
+ const badJson = path.join(work, 'logs', 'bad.json');
159
+ fs.writeFileSync(badJson, '{not-json');
160
+ assert.throws(() => readJsonSafe(badJson, { boundary: work, home }), /Invalid JSON/i);
161
+
162
+ const arrJson = path.join(work, 'logs', 'arr.json');
163
+ fs.writeFileSync(arrJson, '[]');
164
+ assert.throws(() => readJsonSafe(arrJson, { boundary: work, home }), /expected object/i);
165
+
166
+ // SSRF guard
167
+ assert.ok(isBlockedSsrfUrl(new URL('http://127.0.0.1/admin')));
168
+ assert.ok(isBlockedSsrfUrl(new URL('http://169.254.169.254/latest/meta-data')));
169
+ assert.ok(isBlockedSsrfUrl(new URL('http://localhost:3000')));
170
+ assert.ok(isBlockedSsrfUrl(new URL('file:///etc/passwd')));
171
+ assert.equal(isBlockedSsrfUrl(new URL('https://example.org/jobs/123')), null);
172
+ } finally {
173
+ fs.rmSync(dir, { recursive: true, force: true });
174
+ }
175
+ });
176
+
177
+ test('2. Stage 1 (T2): Draft 2020-12 schemas and JS validators enforce v2 constraints & preserve legacy parity', () => {
178
+ const schemaNames = [
179
+ 'application-ledger.schema.json',
180
+ 'cv-versions.schema.json',
181
+ 'career-insights.schema.json',
182
+ 'notion-sync-plan.schema.json',
183
+ ];
184
+ const loaded = {};
185
+ for (const name of schemaNames) {
186
+ const p = path.join(REPO_ROOT, 'schemas', name);
187
+ assert.ok(fs.existsSync(p), `Missing schema: ${name}`);
188
+ const parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
189
+ assert.equal(parsed.$schema, 'https://json-schema.org/draft/2020-12/schema');
190
+ loaded[name] = parsed;
191
+ }
192
+
193
+ // H5: notion-sync-plan.schema.json enforces submitted_only & executable_operation_state
194
+ const notionSchema = loaded['notion-sync-plan.schema.json'];
195
+ assert.equal(notionSchema.$defs.sync_plan.properties.eligibility_policy.const, 'submitted_only');
196
+ assert.deepEqual(
197
+ notionSchema.$defs.submitted_only_status.enum,
198
+ ['applied', 'interview', 'assessment', 'offer', 'rejected', 'withdrawn'],
199
+ );
200
+ assert.equal(notionSchema.$defs.planned_operation.properties.status.$ref, '#/$defs/executable_operation_state');
201
+ assert.ok(notionSchema.$defs.planned_operation.allOf.length >= 1);
202
+
203
+ // H5: application-ledger.schema.json enforces v2.0 application_id & canonical statuses
204
+ const ledgerSchema = loaded['application-ledger.schema.json'];
205
+ assert.ok(ledgerSchema.$defs.application_record.allOf.length >= 1);
206
+
207
+ // Demo fixtures validate cleanly via JS validators
208
+ const demoApps = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'demo', 'applications-log.json'), 'utf8'));
209
+ assert.equal(validateApplicationLedger(demoApps).valid, true);
210
+
211
+ const demoRun = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'demo', 'runs', '2026-10-28.json'), 'utf8'));
212
+ assert.equal(validateDailyRun(demoRun).valid, true);
213
+
214
+ const demoWeekly = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'demo', 'insights', 'weekly-2026-W46.json'), 'utf8'));
215
+ assert.equal(validateCareerInsights(demoWeekly).valid, true);
216
+
217
+ const demoMonthly = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, 'demo', 'insights', 'monthly-2026-11.json'), 'utf8'));
218
+ assert.equal(validateCareerInsights(demoMonthly).valid, true);
219
+
220
+ // Reject malformed fields & non-canonical v2.0 rows
221
+ const invalidV2 = validateApplicationLedger([
222
+ { schema_version: '2.0', job_id: 'j1', status: 'interviewing' },
223
+ ]);
224
+ assert.equal(invalidV2.valid, false);
225
+ assert.ok(invalidV2.errors.some(e => /application_id/i.test(e)));
226
+ assert.ok(invalidV2.errors.some(e => /canonical lowercase status/i.test(e)));
227
+
228
+ const badLegacy = validateApplicationLedger([
229
+ { job_id: 'j2', status: 'applied', match_score: 'not-a-number', applied_at: 'not-a-date' },
230
+ ]);
231
+ assert.equal(badLegacy.valid, false);
232
+ assert.ok(badLegacy.errors.some(e => /match_score/i.test(e)));
233
+ assert.ok(badLegacy.errors.some(e => /applied_at/i.test(e)));
234
+ });
235
+
236
+ test('3. Stage 1 (H1 & H4): CLI flag scoping rejects misplaced flags and verify avoids skipped-jobs misclassification', () => {
237
+ const { dir, home, work } = makeTempWorkspace('veycraft-h1h4-');
238
+ try {
239
+ // H1: --dry-run and --apply rejected on unrelated commands with zero writes
240
+ for (const badArgs of [
241
+ ['init', '--dry-run'],
242
+ ['init', '--apply'],
243
+ ['status', '--dry-run'],
244
+ ['doctor', '--apply'],
245
+ ['career', 'cv-versions', '--apply'],
246
+ ['status', '--write'],
247
+ ['career', 'summary', '--period', '2026-11'],
248
+ ['career', 'migrate', '--write'],
249
+ ]) {
250
+ const res = runCli(badArgs, { cwd: work, home });
251
+ assert.notEqual(res.status, 0, `Expected failure for: ${badArgs.join(' ')}`);
252
+ }
253
+ assert.equal(fs.existsSync(path.join(work, 'AGENTS.md')), false, 'Rejected init --dry-run must not write files');
254
+
255
+ // H4: verify skipped-jobs.json passes cleanly without being treated as application ledger
256
+ const skippedPath = path.join(work, 'logs', 'skipped-jobs.json');
257
+ fs.writeFileSync(skippedPath, JSON.stringify([
258
+ { job_id: 'skip-1', company: 'Example Corp', reason: 'below_min_match_score', skipped_at: '2026-11-01T10:00:00Z' },
259
+ ], null, 2));
260
+ const vSkip = runCli(['verify', skippedPath], { cwd: work, home });
261
+ assert.equal(vSkip.status, 0, vSkip.stdout + vSkip.stderr);
262
+
263
+ // verify demo/applications-log.json passes
264
+ const vDemo = runCli(['verify', path.join(REPO_ROOT, 'demo', 'applications-log.json')], { cwd: work, home });
265
+ assert.equal(vDemo.status, 0, vDemo.stdout + vDemo.stderr);
266
+ } finally {
267
+ fs.rmSync(dir, { recursive: true, force: true });
268
+ }
269
+ });
270
+
271
+ test('4. Stage 1 (T3, H2, H3, M1, M2, L1, B1): Migration integrity, provenance, backup safety & B1 rollback truthfulness', () => {
272
+ const { dir, home, work } = makeTempWorkspace('veycraft-t3-');
273
+ try {
274
+ const ledgerPath = path.join(work, 'logs', 'applications-log.json');
275
+
276
+ // 4a. Missing or duplicate job_id aborts safely without modifying the file
277
+ for (const badSet of [
278
+ [{ company: 'Acme', title: 'Eng', status: 'applied' }],
279
+ [{ job_id: ' ', company: 'Acme', title: 'Eng', status: 'applied' }],
280
+ [
281
+ { job_id: 'dup-1', company: 'Acme', title: 'Eng', status: 'applied' },
282
+ { job_id: ' DUP-1 ', company: 'Beta', title: 'Staff', status: 'applied' },
283
+ ],
284
+ ]) {
285
+ fs.writeFileSync(ledgerPath, JSON.stringify(badSet, null, 2));
286
+ const beforeHash = sha256File(ledgerPath);
287
+ assert.throws(() => migrateApplicationsLedger(work, { apply: true, home }), /job_id/i);
288
+ assert.equal(sha256File(ledgerPath), beforeHash);
289
+ }
290
+
291
+ // 4b. H2, H3, M1, L1 normalization rules
292
+ // M1: malformed legacy structured fields throw instead of silent loss
293
+ assert.throws(
294
+ () => normalizeApplicationRecord({ job_id: 'bad-1', status: 'applied', stage_history: 'corrupted' }),
295
+ /stage_history/i,
296
+ );
297
+ assert.throws(
298
+ () => normalizeApplicationRecord({ job_id: 'bad-1b', status: 'applied', provenance: 'corrupted' }),
299
+ /provenance/i,
300
+ );
301
+ assert.throws(
302
+ () => normalizeApplicationRecord({ job_id: 'bad-2', status: 'interview', applied_at: '2026-11-10T10:00:00Z', updated_at: '2026-11-05T10:00:00Z' }),
303
+ /precedes applied_at/i,
304
+ );
305
+
306
+ // H2: "No receipt:" must NOT mark verified: true
307
+ const noReceipt = normalizeApplicationRecord({
308
+ job_id: 'h2-no-receipt',
309
+ company: 'Alpha',
310
+ title: 'Backend Engineer',
311
+ status: 'applied',
312
+ applied_at: '2026-11-01T10:00:00Z',
313
+ notes: 'No receipt: tab crashed before confirmation',
314
+ });
315
+ assert.equal(noReceipt.stage_history.length, 1);
316
+ assert.equal(noReceipt.stage_history[0].to_status, 'applied');
317
+ assert.equal(noReceipt.stage_history[0].verified, false);
318
+
319
+ // H2: documented receipt quote DOES mark verified: true
320
+ const goodReceipt = normalizeApplicationRecord({
321
+ job_id: 'h2-good-receipt',
322
+ company: 'Alpha',
323
+ title: 'Backend Engineer',
324
+ status: 'applied',
325
+ applied_at: '2026-11-01T10:00:00Z',
326
+ notes: 'receipt: "Application submitted — ID #8821"',
327
+ });
328
+ assert.equal(goodReceipt.stage_history[0].verified, true);
329
+
330
+ // H2: submission_uncertain: true NEVER backfills applied or verified: true
331
+ const uncertain = normalizeApplicationRecord({
332
+ job_id: 'h2-uncertain',
333
+ company: 'Alpha',
334
+ title: 'Backend Engineer',
335
+ status: 'applied',
336
+ submission_uncertain: true,
337
+ applied_at: '2026-11-01T10:00:00Z',
338
+ notes: 'receipt: "Application submitted"',
339
+ });
340
+ assert.equal(uncertain.stage_history.length, 0);
341
+
342
+ // H3 + L1: post-apply backfill uses from_status: null, never fabricates predecessor, captures legacy_status even when null
343
+ const postApply = normalizeApplicationRecord({
344
+ job_id: 'h3-l1-post',
345
+ company: 'Alpha',
346
+ title: 'Backend Engineer',
347
+ status: 'interviewing',
348
+ legacy_status: null,
349
+ applied_at: '2026-11-01T10:00:00Z',
350
+ updated_at: '2026-11-04T15:00:00Z',
351
+ });
352
+ assert.equal(postApply.status, 'interview');
353
+ assert.equal(postApply.legacy_status, 'interviewing');
354
+ assert.equal(postApply.stage_history.length, 2);
355
+ assert.equal(postApply.stage_history[0].to_status, 'applied');
356
+ assert.equal(postApply.stage_history[1].to_status, 'interview');
357
+ assert.equal(postApply.stage_history[1].from_status, null);
358
+
359
+ // H3: identical updated_at === applied_at does not emit duplicate event
360
+ const sameTs = normalizeApplicationRecord({
361
+ job_id: 'h3-same-ts',
362
+ company: 'Alpha',
363
+ title: 'Backend Engineer',
364
+ status: 'rejected',
365
+ applied_at: '2026-11-01T10:00:00Z',
366
+ updated_at: '2026-11-01T10:00:00Z',
367
+ });
368
+ assert.equal(sameTs.stage_history.length, 1);
369
+ assert.equal(sameTs.stage_history[0].to_status, 'applied');
370
+
371
+ // Distinct job_id with identical company + title stay separate with distinct application_id
372
+ const distinctPair = [
373
+ { job_id: 'li-100', company: 'SameCo', title: 'Staff Engineer', status: 'applied', applied_at: '2026-11-01T10:00:00Z' },
374
+ { job_id: 'li-101', company: 'SameCo', title: 'Staff Engineer', status: 'interview', applied_at: '2026-11-02T10:00:00Z', updated_at: '2026-11-05T10:00:00Z' },
375
+ ];
376
+ assert.notEqual(computeApplicationId('li-100'), computeApplicationId('li-101'));
377
+ assert.equal(computeCanonicalFingerprint('SameCo', 'Staff Engineer'), computeCanonicalFingerprint('sameco', 'staff engineer'));
378
+
379
+ // 4c. Dry-run writes zero files; --dry-run --apply conflict aborts via CLI
380
+ fs.writeFileSync(ledgerPath, JSON.stringify(distinctPair, null, 2));
381
+ // Add a corrupt sibling log to verify non-blocking warning (M2)
382
+ fs.writeFileSync(path.join(work, 'logs', 'skipped-jobs.json'), '{broken');
383
+
384
+ const conflict = runCli(['career', 'migrate', '--dry-run', '--apply'], { cwd: work, home });
385
+ assert.notEqual(conflict.status, 0);
386
+
387
+ const beforeDryHash = sha256File(ledgerPath);
388
+ const dryRes = migrateApplicationsLedger(work, { apply: false, home });
389
+ assert.equal(dryRes.mode, 'dry_run');
390
+ assert.equal(dryRes.total_records, 2);
391
+ assert.equal(dryRes.to_enrich, 2);
392
+ assert.equal(sha256File(ledgerPath), beforeDryHash);
393
+ assert.equal(fs.existsSync(path.join(work, 'logs', 'backups')), false);
394
+
395
+ // 4d. TOCTOU concurrent mutation guard aborts before overwrite
396
+ const toctouSourceHash = sha256File(ledgerPath);
397
+ assert.throws(
398
+ () => migrateApplicationsLedger(work, {
399
+ apply: true,
400
+ home,
401
+ _beforeWriteHook: () => {
402
+ fs.writeFileSync(ledgerPath, JSON.stringify([...distinctPair, { job_id: 'li-102', status: 'applied' }]));
403
+ },
404
+ }),
405
+ /Concurrent modification detected/i,
406
+ );
407
+ // Restore clean pair for subsequent rollback tests
408
+ fs.writeFileSync(ledgerPath, JSON.stringify(distinctPair, null, 2));
409
+ assert.equal(sha256File(ledgerPath), toctouSourceHash);
410
+
411
+ // 4e. B1 Scenario 1: Post-write ledger corruption triggers verified atomic auto-restore
412
+ const origHash = sha256File(ledgerPath);
413
+ let err1 = null;
414
+ try {
415
+ migrateApplicationsLedger(work, {
416
+ apply: true,
417
+ home,
418
+ _afterWriteHook: ({ logPath: lp }) => {
419
+ fs.writeFileSync(lp, '{"corrupted": true}');
420
+ },
421
+ });
422
+ } catch (e) {
423
+ err1 = e;
424
+ }
425
+ assert.ok(err1, 'Expected post-write validation error');
426
+ assert.match(err1.message, /auto-restored and SHA-256 verified/i);
427
+ assert.doesNotMatch(err1.message, /AUTO-RESTORE FAILED/);
428
+ assert.equal(sha256File(ledgerPath), origHash, 'Live ledger must match original SHA-256 after verified auto-restore');
429
+
430
+ // 4f. B1 Scenario 2a: Corrupted backup prevents restore and reports AUTO-RESTORE FAILED truthfully
431
+ let err2a = null;
432
+ try {
433
+ migrateApplicationsLedger(work, {
434
+ apply: true,
435
+ home,
436
+ _afterWriteHook: ({ logPath: lp, backup }) => {
437
+ fs.writeFileSync(lp, '{"corrupted": true}');
438
+ fs.writeFileSync(backup.backupLogPath, '{"tampered-backup": true}');
439
+ },
440
+ });
441
+ } catch (e) {
442
+ err2a = e;
443
+ }
444
+ assert.ok(err2a);
445
+ assert.match(err2a.message, /AUTO-RESTORE FAILED/);
446
+ assert.match(err2a.message, /SHA-256 verification failed/i);
447
+ assert.doesNotMatch(err2a.message, /auto-restored/i);
448
+
449
+ // 4g. B1 Scenario 2b: Deleted backup reports AUTO-RESTORE FAILED truthfully with backup path
450
+ fs.writeFileSync(ledgerPath, JSON.stringify(distinctPair, null, 2));
451
+ let err2b = null;
452
+ try {
453
+ migrateApplicationsLedger(work, {
454
+ apply: true,
455
+ home,
456
+ _afterWriteHook: ({ logPath: lp, backup }) => {
457
+ fs.writeFileSync(lp, '{"corrupted": true}');
458
+ fs.unlinkSync(backup.backupLogPath);
459
+ },
460
+ });
461
+ } catch (e) {
462
+ err2b = e;
463
+ }
464
+ assert.ok(err2b);
465
+ assert.match(err2b.message, /AUTO-RESTORE FAILED/);
466
+ assert.match(err2b.message, /backup file is missing/i);
467
+ assert.doesNotMatch(err2b.message, /auto-restored/i);
468
+
469
+ // 4h. Clean apply succeeds, creates SHA-256 backup with random suffix, warns on corrupt sibling log (M2), preserves 2 distinct records, and repeat apply is idempotent
470
+ fs.writeFileSync(ledgerPath, JSON.stringify(distinctPair, null, 2));
471
+ const applyRes = migrateApplicationsLedger(work, { apply: true, home });
472
+ assert.equal(applyRes.mode, 'apply');
473
+ assert.equal(applyRes.total_records, 2);
474
+ assert.equal(applyRes.to_enrich, 2);
475
+ assert.ok(fs.existsSync(applyRes.backup_log_path));
476
+ assert.equal(sha256File(applyRes.backup_log_path), applyRes.backup_sha256);
477
+ assert.ok(applyRes.backup_warnings.some(w => /skipped-jobs\.json/i.test(w)));
478
+
479
+ const migrated = JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
480
+ assert.equal(migrated.length, 2);
481
+ assert.notEqual(migrated[0].application_id, migrated[1].application_id);
482
+ assert.equal(validateApplicationLedger(migrated).valid, true);
483
+
484
+ const repeatRes = migrateApplicationsLedger(work, { apply: true, home });
485
+ assert.equal(repeatRes.to_enrich, 0);
486
+ assert.equal(repeatRes.idempotent_no_op, true);
487
+ } finally {
488
+ fs.rmSync(dir, { recursive: true, force: true });
489
+ }
490
+ });
491
+
492
+ test('5. Stage 1 (M5): CV version registry preserves created_at and enforces third-party isolation', () => {
493
+ const { dir, home, work } = makeTempWorkspace('veycraft-cv-');
494
+ try {
495
+ let reg = { schema_version: '2.0', updated_at: '2026-11-01T00:00:00Z', versions: [] };
496
+ reg = registerCvVersion(reg, {
497
+ cv_version_id: 'cv-base-v1',
498
+ version_number: 1,
499
+ label: 'Core Backend CV',
500
+ kind: 'generic',
501
+ owner_scope: 'owner',
502
+ local_ref_rel: 'context/cv.md',
503
+ created_at: '2026-10-01T09:00:00Z',
504
+ });
505
+
506
+ // Updating existing CV version without overriding created_at preserves original created_at (M5)
507
+ reg = registerCvVersion(reg, {
508
+ cv_version_id: 'cv-base-v1',
509
+ version_number: 1,
510
+ label: 'Core Backend CV (Updated)',
511
+ kind: 'generic',
512
+ owner_scope: 'owner',
513
+ local_ref_rel: 'context/cv.md',
514
+ updated_at: '2026-11-20T12:00:00Z',
515
+ });
516
+ assert.equal(reg.versions.length, 1);
517
+ assert.equal(reg.versions[0].created_at, '2026-10-01T09:00:00Z');
518
+ assert.equal(reg.versions[0].label, 'Core Backend CV (Updated)');
519
+
520
+ // Blocks third_party scope and logs/resumes/cv-* paths
521
+ assert.throws(
522
+ () => registerCvVersion(reg, {
523
+ cv_version_id: 'cv-friend-1',
524
+ version_number: 1,
525
+ label: 'Friend CV',
526
+ kind: 'generic',
527
+ owner_scope: 'third_party',
528
+ local_ref_rel: 'context/other.md',
529
+ }),
530
+ /third-party/i,
531
+ );
532
+ assert.throws(
533
+ () => registerCvVersion(reg, {
534
+ cv_version_id: 'cv-friend-2',
535
+ version_number: 1,
536
+ label: 'Friend CV',
537
+ kind: 'generic',
538
+ owner_scope: 'owner',
539
+ local_ref_rel: 'logs/resumes/cv-friend/cv.html',
540
+ }),
541
+ /third-party/i,
542
+ );
543
+
544
+ // listOwnerCvVersions filters out any manually injected third-party row
545
+ const mixed = {
546
+ schema_version: '1.0',
547
+ updated_at: '2026-11-20T12:00:00Z',
548
+ versions: [
549
+ ...reg.versions,
550
+ {
551
+ cv_version_id: 'cv-leak-test',
552
+ version_number: 2,
553
+ label: 'Client CV',
554
+ kind: 'generic',
555
+ owner_scope: 'third_party',
556
+ local_ref_rel: 'logs/resumes/cv-client/cv.html',
557
+ created_at: '2026-11-01T00:00:00Z',
558
+ application_ids: [],
559
+ },
560
+ ],
561
+ };
562
+ assert.equal(validateCvVersionsRegistry(mixed).valid, true);
563
+ fs.writeFileSync(path.join(work, 'logs', 'cv-versions.json'), JSON.stringify(mixed, null, 2));
564
+
565
+ const listed = listOwnerCvVersions(work, { home });
566
+ assert.equal(listed.total_owner_versions, 1);
567
+ assert.equal(listed.third_party_excluded, 1);
568
+ assert.equal(listed.versions[0].cv_version_id, 'cv-base-v1');
569
+
570
+ const cliRes = runCli(['career', 'cv-versions', '--json'], { cwd: work, home });
571
+ assert.equal(cliRes.status, 0, cliRes.stdout + cliRes.stderr);
572
+ const parsed = JSON.parse(cliRes.stdout);
573
+ assert.equal(parsed.total_owner_versions, 1);
574
+ assert.equal(parsed.third_party_excluded, 1);
575
+ } finally {
576
+ fs.rmSync(dir, { recursive: true, force: true });
577
+ }
578
+ });
579
+
580
+ test('6. Stage 2 (T4): Deterministic analytics engine enforces MIN_N = 5, silence != rejection, CV/platform cohorts, timing, periods & artifact schema', () => {
581
+ const { dir, home, work } = makeTempWorkspace('veycraft-t4-');
582
+ try {
583
+ const nowIso = '2026-11-23T12:00:00Z';
584
+
585
+ // 6a. computeSafeRate exact boundary around MIN_SAMPLE_SIZE = 5
586
+ assert.equal(MIN_SAMPLE_SIZE, 5);
587
+ assert.equal(computeSafeRate(0, 0).rate_pct, null);
588
+ assert.equal(computeSafeRate(0, 0).sample_sufficient, false);
589
+ assert.equal(computeSafeRate(2, 4).rate_pct, null);
590
+ assert.equal(computeSafeRate(2, 4).sample_sufficient, false);
591
+ assert.equal(computeSafeRate(2, 5).rate_pct, 40);
592
+ assert.equal(computeSafeRate(2, 5).sample_sufficient, true);
593
+
594
+ // 6b. parsePeriodSpec validation
595
+ assert.deepEqual(parsePeriodSpec('all'), { type: 'all', period: 'all' });
596
+ assert.deepEqual(parsePeriodSpec('2026-W46'), { type: 'weekly', period: '2026-W46' });
597
+ assert.deepEqual(parsePeriodSpec('2026-11'), { type: 'monthly', period: '2026-11' });
598
+ assert.throws(() => parsePeriodSpec('2026-13'), /Invalid --period/i);
599
+ assert.throws(() => parsePeriodSpec('last-week'), /Invalid --period/i);
600
+
601
+ // 6c. Small-sample dataset (n = 4 submitted + non-submitted noise + silence >= 14d + third-party isolation)
602
+ const smallRecords = [
603
+ // Excluded non-submitted records
604
+ { job_id: 'ex-dry', company: 'DryCo', title: 'Eng', status: 'dry_run', match_score: 8, discovered_at: '2026-11-10T10:00:00Z' },
605
+ { job_id: 'ex-prep', company: 'PrepCo', title: 'Eng', status: 'prepared', match_score: 8, discovered_at: '2026-11-10T10:00:00Z' },
606
+ { job_id: 'ex-skip', company: 'SkipCo', title: 'Eng', status: 'skipped', match_score: 4, discovered_at: '2026-11-10T10:00:00Z' },
607
+ { job_id: 'ex-uncert', company: 'UncertCo', title: 'Eng', status: 'applied', submission_uncertain: true, applied_at: '2026-11-10T10:00:00Z' },
608
+ { job_id: 'ex-3p', company: 'ClientCo', title: 'Eng', status: 'offer', applied_at: '2026-11-10T10:00:00Z', provenance: { third_party_subject: true } },
609
+ // 4 submitted records (below MIN_N = 5)
610
+ {
611
+ job_id: 'sub-1',
612
+ company: 'FreshCo',
613
+ title: 'Backend',
614
+ platform: 'linkedin',
615
+ status: 'applied',
616
+ match_score: 8,
617
+ cv_version_id: 'cv-tailored-1',
618
+ cv_tailoring: { is_tailored: true },
619
+ applied_at: '2026-11-20T12:00:00Z', // 3d ago -> fresh_0_6d
620
+ },
621
+ {
622
+ job_id: 'sub-2',
623
+ company: 'FollowCo',
624
+ title: 'Backend',
625
+ platform: 'greenhouse',
626
+ status: 'applied',
627
+ match_score: 8.5,
628
+ cv_version_id: 'cv-tailored-1',
629
+ cv_tailoring: { is_tailored: true },
630
+ applied_at: '2026-11-13T12:00:00Z', // 10d ago -> followup_window_7_13d + overdue follow-up
631
+ },
632
+ {
633
+ job_id: 'sub-3',
634
+ company: 'Silent15Co',
635
+ title: 'Platform',
636
+ platform: 'lever',
637
+ status: 'applied',
638
+ match_score: 7.5,
639
+ cv_version_id: 'cv-base-1',
640
+ cv_tailoring: { is_tailored: false },
641
+ applied_at: '2026-11-05T12:00:00Z', // 18d ago -> silent_14_29d, NEVER rejected!
642
+ notes: 'followup_sent: 2026-11-14', // already followed up -> NOT in overdueFollowUps
643
+ },
644
+ {
645
+ job_id: 'sub-4',
646
+ company: 'Stale35Co',
647
+ title: 'Platform',
648
+ platform: 'lever',
649
+ status: 'applied',
650
+ match_score: 7,
651
+ cv_version_id: 'cv-base-1',
652
+ cv_tailoring: { is_tailored: false },
653
+ applied_at: '2026-10-19T12:00:00Z', // 35d ago -> stale_30d_plus, NEVER rejected!
654
+ },
655
+ ];
656
+
657
+ const t4OwnerCvRegistry = {
658
+ schema_version: '1.0',
659
+ updated_at: nowIso,
660
+ versions: [
661
+ { cv_version_id: 'cv-tailored-1', version_number: 1, label: 'Tailored 1', kind: 'tailored', owner_scope: 'owner', base_cv_version_id: null, content_sha256: '1'.repeat(64), local_ref_rel: 'logs/resumes/2026-11-01-tailored/resume.html', created_at: nowIso, application_ids: [] },
662
+ { cv_version_id: 'cv-base-1', version_number: 1, label: 'Base 1', kind: 'generic', owner_scope: 'owner', base_cv_version_id: null, content_sha256: '2'.repeat(64), local_ref_rel: 'context/cv.md', created_at: nowIso, application_ids: [] },
663
+ { cv_version_id: 'cv-t', version_number: 1, label: 'Tailored T', kind: 'tailored', owner_scope: 'owner', base_cv_version_id: null, content_sha256: '3'.repeat(64), local_ref_rel: 'logs/resumes/2026-11-01-t/resume.html', created_at: nowIso, application_ids: [] },
664
+ { cv_version_id: 'cv-g', version_number: 1, label: 'Generic G', kind: 'generic', owner_scope: 'owner', base_cv_version_id: null, content_sha256: '4'.repeat(64), local_ref_rel: 'context/cv.md', created_at: nowIso, application_ids: [] },
665
+ ],
666
+ };
667
+ const smallStats = computeCareerAnalytics(smallRecords, t4OwnerCvRegistry, { nowIso });
668
+ assert.equal(smallStats.isolation.third_party_applications_excluded, 1);
669
+ assert.equal(smallStats.funnel.submitted_count, 4);
670
+ assert.equal(smallStats.funnel.prepared_only_count, 1);
671
+ assert.equal(smallStats.funnel.excluded_non_submitted_count, 4);
672
+ // Silence must NEVER be counted as rejected OR decided (B1)
673
+ assert.equal(smallStats.funnel.silent_14d_count, 2);
674
+ assert.equal(smallStats.funnel.rejected_count, 0);
675
+ assert.equal(smallStats.funnel.decided_count, 0);
676
+ assert.equal(smallStats.funnel.rates.decided_callback_rate.denominator, 0);
677
+ assert.equal(smallStats.funnel.rates.decided_callback_rate.rate_pct, null);
678
+ assert.equal(smallStats.timing.aging_buckets.fresh_0_6d, 1);
679
+ assert.equal(smallStats.timing.aging_buckets.followup_window_7_13d, 1);
680
+ assert.equal(smallStats.timing.aging_buckets.silent_14_29d, 1);
681
+ assert.equal(smallStats.timing.aging_buckets.stale_30d_plus, 1);
682
+ // Overdue follow-ups: sub-2 (10d) and sub-4 (35d); sub-3 excluded by followup_sent:
683
+ assert.deepEqual(smallStats.timing.overdue_follow_ups.map(x => x.job_id), ['sub-4', 'sub-2']);
684
+ // MIN_N = 5 suppresses aggregate rates when n = 4
685
+ assert.equal(smallStats.sample_sufficiency.sufficient, false);
686
+ assert.equal(smallStats.funnel.rates.callback_rate.rate_pct, null);
687
+ assert.equal(smallStats.cv_performance.tailored_vs_generic.comparable, false);
688
+
689
+ // B1 explicit test: 2 interviews + 4 silent (>=14d) + 0 rejections -> decided_count MUST be 2 (< 5), NOT 6
690
+ const silentNotDecidedRecords = [
691
+ { job_id: 'b1-i1', company: 'I1', title: 'Eng', status: 'interview', applied_at: '2026-11-01T10:00:00Z', updated_at: '2026-11-04T10:00:00Z' },
692
+ { job_id: 'b1-i2', company: 'I2', title: 'Eng', status: 'interview', applied_at: '2026-11-02T10:00:00Z', updated_at: '2026-11-05T10:00:00Z' },
693
+ { job_id: 'b1-s1', company: 'S1', title: 'Eng', status: 'applied', applied_at: '2026-11-01T10:00:00Z' },
694
+ { job_id: 'b1-s2', company: 'S2', title: 'Eng', status: 'applied', applied_at: '2026-11-01T10:00:00Z' },
695
+ { job_id: 'b1-s3', company: 'S3', title: 'Eng', status: 'applied', applied_at: '2026-11-02T10:00:00Z' },
696
+ { job_id: 'b1-s4', company: 'S4', title: 'Eng', status: 'applied', applied_at: '2026-11-03T10:00:00Z' },
697
+ ];
698
+ const b1Stats = computeCareerAnalytics(silentNotDecidedRecords, null, { nowIso });
699
+ assert.equal(b1Stats.funnel.submitted_count, 6);
700
+ assert.equal(b1Stats.funnel.silent_14d_count, 4);
701
+ assert.equal(b1Stats.funnel.decided_count, 2);
702
+ assert.equal(b1Stats.sample_sufficiency.decided_n, 2);
703
+ assert.equal(b1Stats.funnel.rates.decided_callback_rate.denominator, 2);
704
+ assert.equal(b1Stats.funnel.rates.decided_callback_rate.rate_pct, null);
705
+ assert.equal(b1Stats.funnel.rates.decided_callback_rate.sample_sufficient, false);
706
+ // M2: response_time suppressed when sample_n = 2 (< 5)
707
+ assert.equal(b1Stats.timing.response_time.sample_n, 2);
708
+ assert.equal(b1Stats.timing.response_time.sample_sufficient, false);
709
+ assert.equal(b1Stats.timing.response_time.median_days, null);
710
+ assert.equal(b1Stats.timing.response_time.p75_days, null);
711
+ // L1: deterministic job_id tie-breaker when days_since_applied is equal
712
+ assert.deepEqual(
713
+ b1Stats.timing.overdue_follow_ups.map(x => x.job_id),
714
+ ['b1-s1', 'b1-s2', 'b1-s3', 'b1-s4'],
715
+ );
716
+
717
+ // 6d. Full dataset (>= 5 in both tailored and generic cohorts) + response timing + negative delta guard + skills
718
+ const fullRecords = [
719
+ // 5 tailored applications (3 callbacks: 1 interview, 1 assessment, 1 offer; 1 rejected after interview; 1 applied)
720
+ {
721
+ job_id: 't-1', company: 'T1', title: 'Sr Eng', platform: 'linkedin', status: 'interview', match_score: 9,
722
+ cv_version_id: 'cv-t', cv_tailoring: { is_tailored: true },
723
+ applied_at: '2026-11-01T10:00:00Z', updated_at: '2026-11-03T10:00:00Z', // 2d response
724
+ matched_skills: ['TypeScript', 'Node.js'], missing_skills: ['Rust'],
725
+ },
726
+ {
727
+ job_id: 't-2', company: 'T2', title: 'Sr Eng', platform: 'linkedin', status: 'assessment', match_score: 8.5,
728
+ cv_version_id: 'cv-t', cv_tailoring: { is_tailored: true },
729
+ applied_at: '2026-11-02T10:00:00Z', updated_at: '2026-11-06T10:00:00Z', // 4d response
730
+ matched_skills: ['TypeScript'], missing_skills: ['Kubernetes'],
731
+ },
732
+ {
733
+ job_id: 't-3', company: 'T3', title: 'Staff', platform: 'linkedin', status: 'offer', match_score: 9.5,
734
+ cv_version_id: 'cv-t', cv_tailoring: { is_tailored: true },
735
+ applied_at: '2026-11-03T10:00:00Z',
736
+ stage_history: [
737
+ { from_status: null, to_status: 'applied', at: '2026-11-03T10:00:00Z', verified: true },
738
+ { from_status: 'applied', to_status: 'interview', at: '2026-11-09T10:00:00Z', verified: true }, // 6d response
739
+ { from_status: 'interview', to_status: 'offer', at: '2026-11-18T10:00:00Z', verified: true },
740
+ ],
741
+ matched_skills: ['Node.js'], missing_skills: ['Kubernetes'],
742
+ },
743
+ {
744
+ job_id: 't-4', company: 'T4', title: 'Sr Eng', platform: 'linkedin', status: 'rejected', match_score: 8,
745
+ cv_version_id: 'cv-t', cv_tailoring: { is_tailored: true },
746
+ applied_at: '2026-11-04T10:00:00Z', updated_at: '2026-11-14T10:00:00Z', // 10d response
747
+ interviews: [{ round_id: 'r1', type: 'recruiter_screen', status: 'completed', scheduled_at: '2026-11-08T10:00:00Z' }], // 4d earliest response -> counts as callback!
748
+ },
749
+ {
750
+ job_id: 't-5', company: 'T5', title: 'Sr Eng', platform: 'linkedin', status: 'applied', match_score: 8,
751
+ cv_version_id: 'cv-t', cv_tailoring: { is_tailored: true },
752
+ applied_at: '2026-11-20T10:00:00Z',
753
+ },
754
+ // 5 generic applications (1 callback, 1 withdrawn, 1 rejected with negative bad timestamp ignored, 2 silent >= 14d)
755
+ {
756
+ job_id: 'g-1', company: 'G1', title: 'Eng', platform: 'greenhouse', status: 'interview', match_score: 7.5,
757
+ cv_version_id: 'cv-g', cv_tailoring: { is_tailored: false },
758
+ applied_at: '2026-11-01T10:00:00Z', updated_at: '2026-11-11T10:00:00Z', // 10d response
759
+ },
760
+ {
761
+ job_id: 'g-2', company: 'G2', title: 'Eng', platform: 'greenhouse', status: 'withdrawn', match_score: 7,
762
+ cv_version_id: 'cv-g', cv_tailoring: { is_tailored: false },
763
+ applied_at: '2026-11-02T10:00:00Z', updated_at: '2026-11-05T10:00:00Z', // 3d response
764
+ },
765
+ {
766
+ job_id: 'g-3', company: 'G3', title: 'Eng', platform: 'greenhouse', status: 'rejected', match_score: 7,
767
+ cv_version_id: 'cv-g', cv_tailoring: { is_tailored: false },
768
+ applied_at: '2026-11-10T10:00:00Z', updated_at: '2026-11-01T10:00:00Z', // negative delta -> must be ignored!
769
+ },
770
+ {
771
+ job_id: 'g-4', company: 'G4', title: 'Eng', platform: 'greenhouse', status: 'applied', match_score: 7,
772
+ cv_version_id: 'cv-g', cv_tailoring: { is_tailored: false },
773
+ applied_at: '2026-11-01T10:00:00Z', // 22d silent
774
+ },
775
+ {
776
+ job_id: 'g-5', company: 'G5', title: 'Eng', platform: 'greenhouse', status: 'applied', match_score: 7,
777
+ cv_version_id: 'cv-g', cv_tailoring: { is_tailored: false },
778
+ applied_at: '2026-10-15T10:00:00Z', // 39d stale (outside 2026-11 month filter)
779
+ },
780
+ ];
781
+
782
+ const fullStats = computeCareerAnalytics(fullRecords, t4OwnerCvRegistry, { nowIso });
783
+ // Determinism check: identical inputs produce byte-identical analytics
784
+ const fullStatsRepeat = computeCareerAnalytics(fullRecords, t4OwnerCvRegistry, { nowIso });
785
+ assert.deepEqual(fullStats, fullStatsRepeat);
786
+
787
+ assert.equal(fullStats.sample_sufficiency.sufficient, true);
788
+ assert.equal(fullStats.funnel.submitted_count, 10);
789
+ // B1: 1 fresh applied (t-5) + 2 silent applied (g-4, g-5) are NOT decided -> decided_count = 7
790
+ assert.equal(fullStats.funnel.decided_count, 7);
791
+ assert.equal(fullStats.funnel.rates.decided_callback_rate.denominator, 7);
792
+ // Callbacks: t-1 (interview), t-2 (assessment), t-3 (offer+interview), t-4 (rejected after interview), g-1 (interview) = 5 / 10 = 50%
793
+ assert.equal(fullStats.funnel.positive_callbacks_count, 5);
794
+ assert.equal(fullStats.funnel.rates.callback_rate.rate_pct, 50);
795
+ assert.equal(fullStats.funnel.rejected_count, 2);
796
+ assert.equal(fullStats.funnel.withdrawn_count, 1);
797
+ assert.equal(fullStats.funnel.silent_14d_count, 2);
798
+ // Tailored vs Generic both >= 5 -> comparable === true (tailored 4/5 = 80%, generic 1/5 = 20%)
799
+ assert.equal(fullStats.cv_performance.tailored_vs_generic.comparable, true);
800
+ assert.equal(fullStats.cv_performance.tailored_vs_generic.tailored.callback_rate.rate_pct, 80);
801
+ assert.equal(fullStats.cv_performance.tailored_vs_generic.generic.callback_rate.rate_pct, 20);
802
+ // Source causal humility note present + per-platform M2 median_response_days suppressed when < 5
803
+ assert.match(fullStats.source_performance.causal_humility_note, /do not establish ATS bias or causation/i);
804
+ const liPlat = fullStats.source_performance.by_platform.find(p => p.platform === 'linkedin');
805
+ assert.equal(liPlat.response_time_sample_n, 4);
806
+ assert.equal(liPlat.response_time_sample_sufficient, false);
807
+ assert.equal(liPlat.median_response_days, null);
808
+ // H3: withdrawn (g-2) excluded from employer response time!
809
+ // Employer response deltas: [2 (t-1), 4 (t-2), 4 (t-4), 6 (t-3), 10 (g-1)] -> sample_n = 5, median = 4, p75 = 6, negative delta ignored = 1
810
+ assert.equal(fullStats.timing.response_time.sample_n, 5);
811
+ assert.equal(fullStats.timing.response_time.sample_sufficient, true);
812
+ assert.equal(fullStats.timing.response_time.median_days, 4);
813
+ assert.equal(fullStats.timing.response_time.p75_days, 6);
814
+ assert.equal(fullStats.timing.response_time.invalid_timestamps_ignored, 1);
815
+ // Top skill gap: Kubernetes (count 2)
816
+ assert.equal(fullStats.skills_summary.skill_gaps[0].skill, 'Kubernetes');
817
+ assert.equal(fullStats.skills_summary.skill_gaps[0].count, 2);
818
+
819
+ // H2: Legacy v1 aliases (interviewing, declined, coding_test, accepted), legacy `date`, legacy `score`, and out-of-range match_score > 10
820
+ const legacyRecords = [
821
+ { job_id: 'leg-i', company: 'L1', role: 'Dev', status: 'interviewing', score: 8, date: '2026-11-01T10:00:00Z', updated_at: '2026-11-03T10:00:00Z' },
822
+ { job_id: 'leg-a', company: 'L2', role: 'Dev', status: 'coding_test', score: 9, date: '2026-11-02T10:00:00Z', updated_at: '2026-11-05T10:00:00Z' },
823
+ { job_id: 'leg-o', company: 'L3', role: 'Dev', status: 'accepted', score: 10, date: '2026-11-03T10:00:00Z', updated_at: '2026-11-07T10:00:00Z' },
824
+ { job_id: 'leg-r', company: 'L4', role: 'Dev', status: 'declined', match_score: 85, date: '2026-11-04T10:00:00Z', updated_at: '2026-11-10T10:00:00Z' }, // out-of-range 85 ignored!
825
+ { job_id: 'leg-r2', company: 'L5', role: 'Dev', status: 'closed', score: 7, date: '2026-11-05T10:00:00Z', updated_at: '2026-11-12T10:00:00Z' },
826
+ { job_id: 'leg-s', company: 'L6', role: 'Dev', status: 'submitted', score: 6, date: '2026-11-01T10:00:00Z' }, // 22d silent via legacy `date`
827
+ ];
828
+ const legStats = computeCareerAnalytics(legacyRecords, null, { nowIso });
829
+ assert.equal(legStats.funnel.submitted_count, 6);
830
+ assert.equal(legStats.funnel.silent_14d_count, 1);
831
+ assert.equal(legStats.funnel.rejected_count, 2);
832
+ assert.equal(legStats.funnel.decided_count, 5);
833
+ assert.equal(legStats.funnel.avg_match_score, 8); // (8+9+10+7+6)/5 = 8.0, out-of-range 85 excluded!
834
+ assert.ok(legStats.data_quality_warnings.some(w => /out-of-range/i.test(w)));
835
+ assert.equal(legStats.timing.response_time.sample_n, 5);
836
+ assert.equal(legStats.timing.response_time.median_days, 4); // [2, 3, 4, 6, 7]
837
+ assert.equal(legStats.timing.overdue_follow_ups.map(x => x.job_id).includes('leg-s'), true);
838
+ const legArtifact = buildCareerInsightArtifact(legStats);
839
+ assert.equal(validateCareerInsights(legArtifact).valid, true);
840
+
841
+ // Pre-Stage 3 Regression (H2 date precedence): legacy record with `date` in Oct, `updated_at` in Nov, and no `applied_at`
842
+ // must be filtered and bucketed into Oct (original application date), NOT Nov (updated_at).
843
+ const crossMonthLegacy = [
844
+ {
845
+ job_id: 'leg-oct-to-nov',
846
+ company: 'OctAppliedCo',
847
+ role: 'Backend Engineer',
848
+ platform: 'linkedin',
849
+ status: 'interviewing',
850
+ score: 8.5,
851
+ date: '2026-10-20T10:00:00Z',
852
+ updated_at: '2026-11-05T10:00:00Z',
853
+ },
854
+ ];
855
+ const crossAll = computeCareerAnalytics(crossMonthLegacy, null, { nowIso });
856
+ assert.deepEqual(crossAll.timing.activity.monthly.map(m => m.period), ['2026-10']);
857
+ assert.equal(crossAll.timing.activity.monthly[0].submitted, 1);
858
+ const crossOct = computeCareerAnalytics(crossMonthLegacy, null, { nowIso, period: '2026-10' });
859
+ const crossNov = computeCareerAnalytics(crossMonthLegacy, null, { nowIso, period: '2026-11' });
860
+ assert.equal(crossOct.funnel.submitted_count, 1);
861
+ assert.equal(crossNov.funnel.submitted_count, 0);
862
+
863
+ const legacyWs = makeTempWorkspace('veycraft-legdate-');
864
+ try {
865
+ fs.writeFileSync(path.join(legacyWs.work, 'logs', 'applications-log.json'), JSON.stringify(crossMonthLegacy, null, 2));
866
+ const octCli = runCli(['career', 'analytics', '--period', '2026-10', '--json'], { cwd: legacyWs.work, home: legacyWs.home });
867
+ const novCli = runCli(['career', 'analytics', '--period', '2026-11', '--json'], { cwd: legacyWs.work, home: legacyWs.home });
868
+ assert.equal(octCli.status, 0, octCli.stdout + octCli.stderr);
869
+ assert.equal(novCli.status, 0, novCli.stdout + novCli.stderr);
870
+ const octJson = JSON.parse(octCli.stdout);
871
+ const novJson = JSON.parse(novCli.stdout);
872
+ assert.equal(octJson.funnel.submitted_count, 1);
873
+ assert.deepEqual(octJson.timing.activity.monthly.map(m => m.period), ['2026-10']);
874
+ assert.equal(novJson.funnel.submitted_count, 0);
875
+ } finally {
876
+ fs.rmSync(legacyWs.dir, { recursive: true, force: true });
877
+ }
878
+
879
+ // Period filtering: 2026-11 excludes g-5 (2026-10-15) -> 9 records
880
+ const novStats = computeCareerAnalytics(fullRecords, t4OwnerCvRegistry, { nowIso, period: '2026-11' });
881
+ assert.equal(novStats.period_type, 'monthly');
882
+ assert.equal(novStats.funnel.submitted_count, 9);
883
+
884
+ // Artifact strictly separates deterministic facts from empty AI arrays and validates against schema
885
+ const artifact = buildCareerInsightArtifact(novStats);
886
+ assert.equal(validateCareerInsights(artifact).valid, true);
887
+ assert.deepEqual(artifact.intelligence.ai_interpretations, []);
888
+ assert.deepEqual(artifact.intelligence.hypotheses, []);
889
+ assert.deepEqual(artifact.intelligence.recommended_actions, []);
890
+ assert.equal(artifact.intelligence.deterministic_facts.funnel.submitted_count, 9);
891
+
892
+ // 6e. Workspace CLI, H1 post-migration summary, M4 all-time filename & error paths
893
+ const ledgerPath = path.join(work, 'logs', 'applications-log.json');
894
+ fs.writeFileSync(path.join(work, 'logs', 'cv-versions.json'), JSON.stringify(t4OwnerCvRegistry, null, 2));
895
+ fs.writeFileSync(ledgerPath, JSON.stringify(fullRecords, null, 2));
896
+ const ledgerHashBefore = sha256File(ledgerPath);
897
+
898
+ const summaryRes = runCli(['career', 'summary', '--json'], { cwd: work, home });
899
+ assert.equal(summaryRes.status, 0, summaryRes.stdout + summaryRes.stderr);
900
+ const summaryJson = JSON.parse(summaryRes.stdout);
901
+ assert.equal(summaryJson.funnel.submitted_count, 10);
902
+ assert.equal(summaryJson.active_interviews, 2); // t-1, g-1
903
+ assert.equal(summaryJson.active_assessments, 1); // t-2
904
+ assert.equal(summaryJson.pending_notion_sync_count, 10);
905
+
906
+ // H1: Migrated v2.0 records with empty interviews: [] / assessments: [] preserve active counts
907
+ const migWork = makeTempWorkspace('veycraft-h1-mig-');
908
+ try {
909
+ const migLedger = path.join(migWork.work, 'logs', 'applications-log.json');
910
+ fs.writeFileSync(migLedger, JSON.stringify([
911
+ { job_id: 'm-int', company: 'IntCo', title: 'Sr', status: 'interview', applied_at: '2026-11-01T10:00:00Z' },
912
+ { job_id: 'm-asmt', company: 'AsmtCo', title: 'Sr', status: 'assessment', applied_at: '2026-11-02T10:00:00Z' },
913
+ ], null, 2));
914
+ migrateApplicationsLedger(migWork.work, { apply: true, home: migWork.home });
915
+ const migratedRows = JSON.parse(fs.readFileSync(migLedger, 'utf8'));
916
+ assert.deepEqual(migratedRows[0].interviews, []);
917
+ assert.deepEqual(migratedRows[1].assessments, []);
918
+ const postMigSum = summarizeCareerWorkspace(migWork.work, { home: migWork.home, nowIso });
919
+ assert.equal(postMigSum.active_interviews, 1);
920
+ assert.equal(postMigSum.active_assessments, 1);
921
+ } finally {
922
+ fs.rmSync(migWork.dir, { recursive: true, force: true });
923
+ }
924
+
925
+ const analyticsWrite = runCli(['career', 'analytics', '--period', '2026-11', '--write', '--json'], { cwd: work, home });
926
+ assert.equal(analyticsWrite.status, 0, analyticsWrite.stdout + analyticsWrite.stderr);
927
+ const writeJson = JSON.parse(analyticsWrite.stdout);
928
+ assert.ok(writeJson.written_path && fs.existsSync(writeJson.written_path));
929
+ assert.equal(path.basename(writeJson.written_path), 'monthly-2026-11.json');
930
+
931
+ // M4: --period all --write writes all-time.json (not all-all.json) and passes verify
932
+ const allWrite = runCli(['career', 'analytics', '--period', 'all', '--write', '--json'], { cwd: work, home });
933
+ assert.equal(allWrite.status, 0, allWrite.stdout + allWrite.stderr);
934
+ const allWriteJson = JSON.parse(allWrite.stdout);
935
+ assert.equal(path.basename(allWriteJson.written_path), 'all-time.json');
936
+ const verifyAllInsight = runCli(['verify', allWriteJson.written_path], { cwd: work, home });
937
+ assert.equal(verifyAllInsight.status, 0, verifyAllInsight.stdout + verifyAllInsight.stderr);
938
+
939
+ // Verify generated monthly insights artifact passes `veycraft verify`
940
+ const verifyInsight = runCli(['verify', writeJson.written_path], { cwd: work, home });
941
+ assert.equal(verifyInsight.status, 0, verifyInsight.stdout + verifyInsight.stderr);
942
+
943
+ // Ledger remains completely unmodified
944
+ assert.equal(sha256File(ledgerPath), ledgerHashBefore);
945
+
946
+ // CLI error paths: invalid --period, empty workspace, corrupt ledger
947
+ const badPeriodCli = runCli(['career', 'analytics', '--period', 'invalid-period'], { cwd: work, home });
948
+ assert.notEqual(badPeriodCli.status, 0);
949
+ assert.match(badPeriodCli.stderr, /Invalid --period/i);
950
+
951
+ const emptyWs = makeTempWorkspace('veycraft-empty-');
952
+ try {
953
+ const emptySum = runCli(['career', 'summary', '--json'], { cwd: emptyWs.work, home: emptyWs.home });
954
+ assert.equal(emptySum.status, 0, emptySum.stdout + emptySum.stderr);
955
+ assert.equal(JSON.parse(emptySum.stdout).funnel.submitted_count, 0);
956
+
957
+ fs.writeFileSync(path.join(emptyWs.work, 'logs', 'applications-log.json'), '{corrupt-json');
958
+ const corruptSum = runCli(['career', 'summary'], { cwd: emptyWs.work, home: emptyWs.home });
959
+ assert.notEqual(corruptSum.status, 0);
960
+ const corruptAn = runCli(['career', 'analytics'], { cwd: emptyWs.work, home: emptyWs.home });
961
+ assert.notEqual(corruptAn.status, 0);
962
+ } finally {
963
+ fs.rmSync(emptyWs.dir, { recursive: true, force: true });
964
+ }
965
+
966
+ // Direct API helper matches CLI
967
+ const directRun = runCareerAnalyticsForWorkspace(work, { home, period: '2026-11', write: false, nowIso });
968
+ assert.equal(directRun.analytics.funnel.submitted_count, 9);
969
+ const directSum = summarizeCareerWorkspace(work, { home, nowIso });
970
+ assert.equal(directSum.funnel.submitted_count, 10);
971
+ } finally {
972
+ fs.rmSync(dir, { recursive: true, force: true });
973
+ }
974
+ });
975
+
976
+ test('7. Stage 2 (T5): Local analytics dashboard is read-only, XSS-safe, offline, MIN_N=5 guarded, parity-aligned & excludes third-party data', () => {
977
+ const { dir, home, work } = makeTempWorkspace('veycraft-t5-');
978
+ try {
979
+ const ledgerPath = path.join(work, 'logs', 'applications-log.json');
980
+ const records = [
981
+ {
982
+ job_id: 'xss-1',
983
+ company: 'Evil </script><script>alert(1)</script> Corp',
984
+ title: 'Security Engineer',
985
+ platform: 'linkedin',
986
+ status: 'applied',
987
+ match_score: 8.5,
988
+ cv_version_id: 'cv-v2',
989
+ cv_tailoring: { is_tailored: true },
990
+ applied_at: '2026-10-01T10:00:00Z',
991
+ url: 'javascript:alert(1)',
992
+ notes: '<img src=x onerror=alert(1)>',
993
+ },
994
+ {
995
+ job_id: 'leg-1',
996
+ company: 'Legacy V1 Corp',
997
+ role: 'Backend Developer',
998
+ platform: 'greenhouse',
999
+ status: 'interviewing',
1000
+ score: 9,
1001
+ date: '2026-11-18T10:00:00Z',
1002
+ updated_at: '2026-11-20T10:00:00Z',
1003
+ url: 'https://boards.greenhouse.io/legacy/jobs/1',
1004
+ },
1005
+ {
1006
+ job_id: 'leg-declined',
1007
+ company: 'DeclinedCo',
1008
+ role: 'Infra Eng',
1009
+ platform: 'lever',
1010
+ status: 'declined',
1011
+ match_score: 99, // out-of-range score ignored
1012
+ date: '2026-11-10T10:00:00Z',
1013
+ updated_at: '2026-11-15T10:00:00Z',
1014
+ },
1015
+ {
1016
+ job_id: 'leg-withdrawn',
1017
+ company: 'WithdrawnCo',
1018
+ role: 'Staff Eng',
1019
+ platform: 'lever',
1020
+ status: 'withdrawn',
1021
+ match_score: 8,
1022
+ applied_at: '2026-11-12T10:00:00Z',
1023
+ updated_at: '2026-11-13T10:00:00Z', // self-withdrawal must NOT count as employer response time
1024
+ },
1025
+ {
1026
+ job_id: 'third-party-secret',
1027
+ company: 'ThirdPartyClientPrivateXYZ',
1028
+ title: 'Confidential Role',
1029
+ platform: 'linkedin',
1030
+ status: 'offer',
1031
+ applied_at: '2026-11-10T10:00:00Z',
1032
+ provenance: { third_party_subject: true },
1033
+ },
1034
+ ];
1035
+ fs.writeFileSync(
1036
+ path.join(work, 'logs', 'cv-versions.json'),
1037
+ JSON.stringify({
1038
+ schema_version: '1.0',
1039
+ updated_at: '2026-11-20T10:00:00Z',
1040
+ versions: [
1041
+ {
1042
+ cv_version_id: 'cv-v2',
1043
+ version_number: 2,
1044
+ label: 'Owner Tailored v2',
1045
+ kind: 'tailored',
1046
+ owner_scope: 'owner',
1047
+ base_cv_version_id: null,
1048
+ content_sha256: '5'.repeat(64),
1049
+ local_ref_rel: 'logs/resumes/2026-10-01-sec/resume.html',
1050
+ created_at: '2026-10-01T09:00:00Z',
1051
+ application_ids: [],
1052
+ },
1053
+ ],
1054
+ }, null, 2),
1055
+ );
1056
+ fs.writeFileSync(ledgerPath, JSON.stringify(records, null, 2));
1057
+ const beforeHash = sha256File(ledgerPath);
1058
+
1059
+ const res = runCli(['dashboard', '--no-open'], { cwd: work, home });
1060
+ assert.equal(res.status, 0, res.stdout + res.stderr);
1061
+
1062
+ // Read-only guarantee: dashboard never modifies applications-log.json
1063
+ assert.equal(sha256File(ledgerPath), beforeHash);
1064
+
1065
+ const dashPath = path.join(work, 'logs', 'exports', 'dashboard.html');
1066
+ assert.ok(fs.existsSync(dashPath));
1067
+ // M3: File permissions 0o600 on POSIX
1068
+ if (process.platform !== 'win32') {
1069
+ assert.equal(fs.statSync(dashPath).mode & 0o777, 0o600);
1070
+ }
1071
+ const html = fs.readFileSync(dashPath, 'utf8');
1072
+
1073
+ // M3: Third-party application record must NOT be embedded anywhere in dashboard.html
1074
+ assert.doesNotMatch(html, /ThirdPartyClientPrivateXYZ/);
1075
+ assert.doesNotMatch(html, /third-party-secret/);
1076
+
1077
+ // Both records and deterministic analytics injected (no unreplaced placeholders)
1078
+ assert.doesNotMatch(html, /\/\*__APPLICATIONS_DATA__\*\//);
1079
+ assert.doesNotMatch(html, /\/\*__CAREER_ANALYTICS__\*\//);
1080
+ assert.match(html, /window\.__JOB_HUNTER_LOGS__\s*=/);
1081
+ assert.match(html, /window\.__VEYCRAFT_ANALYTICS__\s*=/);
1082
+
1083
+ // XSS script-breakout escaped via \u003c / \u003e
1084
+ assert.doesNotMatch(html, /<\/script><script>alert\(1\)<\/script>/i);
1085
+ assert.match(html, /\\u003c\/script\\u003e\\u003cscript\\u003ealert\(1\)\\u003c\/script\\u003e/);
1086
+
1087
+ // Strictly offline, zero external CDNs/network APIs, zero browser storage mutations
1088
+ assert.doesNotMatch(html, /\bfetch\s*\(/);
1089
+ assert.doesNotMatch(html, /\bXMLHttpRequest\b/);
1090
+ assert.doesNotMatch(html, /\bWebSocket\b/);
1091
+ assert.doesNotMatch(html, /\blocalStorage\b|\bsessionStorage\b|\bindexedDB\b/);
1092
+ assert.doesNotMatch(html, /fonts\.googleapis|cdn\.jsdelivr|unpkg\.com|cdnjs\.cloudflare/i);
1093
+
1094
+ // Separate Silent (>=14d) column and MIN_SAMPLE_SIZE = 5 guard present
1095
+ assert.match(html, /Silent \(≥14d\)/);
1096
+ assert.match(html, /Rejected \/ Withdrawn/);
1097
+ assert.doesNotMatch(html, /Rejected \/ Ghosted/);
1098
+ assert.match(html, /const MIN_SAMPLE_SIZE = 5;/);
1099
+
1100
+ // M1 & M2: Execute extracted dashboard script in a sandboxed VM with mock DOM to verify actual runtime parity
1101
+ const scriptOpen = html.indexOf('<script>');
1102
+ const scriptClose = scriptOpen >= 0 ? html.indexOf('</script>', scriptOpen + '<script>'.length) : -1;
1103
+ const scriptBody = scriptOpen >= 0 && scriptClose > scriptOpen ? html.slice(scriptOpen + '<script>'.length, scriptClose) : null;
1104
+ assert.ok(scriptBody, 'Expected inline <script> block in dashboard.html');
1105
+ const elements = new Map();
1106
+ const makeEl = id => {
1107
+ const el = {
1108
+ id,
1109
+ textContent: '',
1110
+ innerHTML: '',
1111
+ className: '',
1112
+ value: '',
1113
+ classList: { add() {}, remove() {} },
1114
+ addEventListener() {},
1115
+ };
1116
+ elements.set(id, el);
1117
+ return el;
1118
+ };
1119
+ const sandbox = {
1120
+ window: {},
1121
+ document: {
1122
+ getElementById: id => elements.get(id) || makeEl(id),
1123
+ createElement: () => {
1124
+ let txt = '';
1125
+ return {
1126
+ set textContent(v) {
1127
+ txt = String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1128
+ },
1129
+ get innerHTML() { return txt; },
1130
+ };
1131
+ },
1132
+ },
1133
+ URL,
1134
+ Date,
1135
+ Math,
1136
+ Number,
1137
+ String,
1138
+ Boolean,
1139
+ Array,
1140
+ Object,
1141
+ Map,
1142
+ Set,
1143
+ JSON,
1144
+ RegExp,
1145
+ Error,
1146
+ FileReader: function FileReader() {},
1147
+ };
1148
+ vm.runInNewContext(
1149
+ `${scriptBody}\nthis.__exports = { canonicalStatus, classifyBucket, hasPositiveCallback, formatRateDisplay, safeHref, computeClientAnalytics };`,
1150
+ sandbox,
1151
+ );
1152
+ const { canonicalStatus, classifyBucket, formatRateDisplay, safeHref, computeClientAnalytics } = sandbox.__exports;
1153
+ const injectedAnalytics = sandbox.window.__VEYCRAFT_ANALYTICS__;
1154
+ const refNowTs = Date.parse(injectedAnalytics.computed_at);
1155
+
1156
+ // Assert actual rendered KPI DOM values match server analytics 1:1
1157
+ assert.equal(elements.get('kpi-applied').textContent, String(injectedAnalytics.funnel.submitted_count));
1158
+ assert.equal(elements.get('kpi-silent').textContent, String(injectedAnalytics.funnel.silent_14d_count));
1159
+ assert.equal(elements.get('kpi-overdue').textContent, String(injectedAnalytics.timing.overdue_follow_ups.length));
1160
+ assert.match(elements.get('kpi-callback').textContent, /n\/a \(n=4 < 5\)/);
1161
+ assert.match(elements.get('response-timing-summary').textContent, /n\/a \(sample n=2 < 5/);
1162
+ // XSS payload escaped in rendered Kanban HTML
1163
+ assert.doesNotMatch(elements.get('kanban-board').innerHTML, /<img src=x onerror=/i);
1164
+ assert.doesNotMatch(elements.get('kanban-board').innerHTML, /javascript:alert/i);
1165
+
1166
+ // Assert client helpers match server analytics 1:1 (M1, M2, H2, H3)
1167
+ assert.equal(canonicalStatus('declined'), 'rejected');
1168
+ assert.equal(canonicalStatus('coding_test'), 'assessment');
1169
+ assert.equal(canonicalStatus('accepted'), 'offer');
1170
+ assert.equal(safeHref('javascript:alert(1)'), null);
1171
+ assert.equal(safeHref('https://boards.greenhouse.io/legacy/jobs/1'), 'https://boards.greenhouse.io/legacy/jobs/1');
1172
+ assert.equal(formatRateDisplay(2, 4).pct, null);
1173
+ assert.equal(formatRateDisplay(2, 5).pct, 40);
1174
+ assert.equal(classifyBucket(records[0], refNowTs), 'silent14d');
1175
+ assert.equal(classifyBucket(records[2], refNowTs), 'rejected');
1176
+ assert.equal(classifyBucket(records[4], refNowTs), 'excluded');
1177
+
1178
+ const clientStats = computeClientAnalytics(sandbox.window.__JOB_HUNTER_LOGS__, refNowTs);
1179
+ assert.deepEqual(clientStats.timing.aging_buckets, injectedAnalytics.timing.aging_buckets);
1180
+ assert.equal(clientStats.timing.response_time.sample_n, injectedAnalytics.timing.response_time.sample_n);
1181
+ assert.equal(clientStats.timing.response_time.median_days, null); // M2: n=2 < 5
1182
+ assert.equal(clientStats.timing.response_time.p75_days, null);
1183
+
1184
+ // M3: Symlink refusal on logs/applications-log.json in cmdDashboard
1185
+ const symWork = makeTempWorkspace('veycraft-sym-');
1186
+ try {
1187
+ const outside = path.join(symWork.dir, 'outside.json');
1188
+ fs.writeFileSync(outside, '[]');
1189
+ const symLedger = path.join(symWork.work, 'logs', 'applications-log.json');
1190
+ let symlinkCreated = false;
1191
+ try {
1192
+ fs.symlinkSync(outside, symLedger);
1193
+ symlinkCreated = true;
1194
+ } catch {
1195
+ // Windows without Developer Mode / admin privileges may disallow file symlinks
1196
+ }
1197
+ if (symlinkCreated) {
1198
+ const symRes = runCli(['dashboard', '--no-open'], { cwd: symWork.work, home: symWork.home });
1199
+ assert.notEqual(symRes.status, 0);
1200
+ assert.match(symRes.stderr, /symbolic-link/i);
1201
+ } else {
1202
+ // Verify cli.mjs cmdDashboard explicitly enforces refuseSymlink on ledger + cv-versions and writes 0o600
1203
+ const cliSrc = fs.readFileSync(CLI, 'utf8');
1204
+ const dashFn = cliSrc.slice(cliSrc.indexOf('function cmdDashboard()'), cliSrc.indexOf('function isPidAlive'));
1205
+ assert.match(dashFn, /refuseSymlink\(logFile\)/);
1206
+ assert.match(dashFn, /refuseSymlink\(cvPath\)/);
1207
+ assert.match(dashFn, /writeAtomic\(outFile,\s*injected,\s*\{\s*mode:\s*0o600\s*\}\)/);
1208
+ }
1209
+ } finally {
1210
+ fs.rmSync(symWork.dir, { recursive: true, force: true });
1211
+ }
1212
+ } finally {
1213
+ fs.rmSync(dir, { recursive: true, force: true });
1214
+ }
1215
+ });
1216
+
1217
+ // ---------------- Stage 5 (T11): Ledger Locking, Lifecycle Write-Engine, CV Linking, Pre-Submit Gate & CLI ----------------
1218
+
1219
+ test('8. Stage 5 (T11.1): Ledger lock contention, nonce-safe release, dead-PID recovery, corrupt JSON & symlink refusal', () => {
1220
+ const { dir, home, work } = makeTempWorkspace('veycraft-t11-lock-');
1221
+ const nowIso = '2026-11-23T12:00:00Z';
1222
+ const lockPath = path.join(work, 'logs', LEDGER_LOCK_FILENAME);
1223
+ const ledgerPath = path.join(work, 'logs', 'applications-log.json');
1224
+ const skippedPath = path.join(work, 'logs', 'skipped-jobs.json');
1225
+ const cvPath = path.join(work, 'logs', 'cv-versions.json');
1226
+
1227
+ try {
1228
+ // 8a. Exclusive lock acquisition, nested contention refusal & clean release
1229
+ let seenNonce = null;
1230
+ withLedgerLock(work, { home, nowIso }, handle => {
1231
+ seenNonce = handle.nonce;
1232
+ assert.ok(fs.existsSync(lockPath));
1233
+ const inspected = inspectLedgerLock(work, { home, nowIso });
1234
+ assert.equal(inspected.locked, true);
1235
+ assert.equal(inspected.owner_alive, true);
1236
+ assert.equal(inspected.lock.pid, process.pid);
1237
+ assert.equal(inspected.lock.nonce, seenNonce);
1238
+
1239
+ // Concurrent writer MUST fail closed without stealing lock
1240
+ assert.throws(
1241
+ () => recordApplication(work, { job_id: 'gh:contend-1', status: 'discovered', company: 'Acme', title: 'SWE' }, { home, nowIso }),
1242
+ /ledger_locked/i,
1243
+ );
1244
+ // Live PID lock cannot be released via releaseStaleLedgerLock even with future timestamp
1245
+ assert.throws(
1246
+ () => releaseStaleLedgerLock(work, {
1247
+ home,
1248
+ nowIso: '2026-11-23T13:00:00Z',
1249
+ expectedNonce: seenNonce,
1250
+ confirmedExplicitRecovery: true,
1251
+ }),
1252
+ /still active|cannot be proven dead/i,
1253
+ );
1254
+ });
1255
+ assert.equal(fs.existsSync(lockPath), false, 'Lockfile should be released cleanly after callback');
1256
+
1257
+ // 8b. Nonce-safe release: if lockfile was replaced by another nonce during execution, release must NOT delete the other lock
1258
+ const foreignNonce = 'foreign_nonce_abcdef123456';
1259
+ withLedgerLock(work, { home, nowIso }, () => {
1260
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: process.pid, acquired_at: nowIso, nonce: foreignNonce }, null, 2));
1261
+ });
1262
+ assert.equal(fs.existsSync(lockPath), true, 'Foreign nonce lock must NOT be unlinked');
1263
+ fs.unlinkSync(lockPath);
1264
+
1265
+ // 8c. Dead-PID stale lock diagnostics & explicit recovery
1266
+ const deadPid = 99999999; // non-existent PID
1267
+ const staleNonce = 'dead_pid_nonce_123456';
1268
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: deadPid, acquired_at: '2026-11-23T11:00:00Z', nonce: staleNonce }, null, 2));
1269
+ const staleInfo = inspectLedgerLock(work, { home, nowIso });
1270
+ assert.equal(staleInfo.locked, true);
1271
+ assert.equal(staleInfo.stale, true);
1272
+ assert.equal(staleInfo.owner_alive, false);
1273
+
1274
+ // Must fail without explicit confirmation, wrong nonce, or non-stale age
1275
+ assert.throws(
1276
+ () => releaseStaleLedgerLock(work, { home, nowIso, expectedNonce: staleNonce, confirmedExplicitRecovery: false }),
1277
+ /confirmedExplicitRecovery/i,
1278
+ );
1279
+ assert.throws(
1280
+ () => releaseStaleLedgerLock(work, { home, nowIso, expectedNonce: 'wrong-nonce', confirmedExplicitRecovery: true }),
1281
+ /nonce mismatch/i,
1282
+ );
1283
+ assert.throws(
1284
+ () => releaseStaleLedgerLock(work, { home, nowIso: '2026-11-23T11:05:00Z', expectedNonce: staleNonce, confirmedExplicitRecovery: true }),
1285
+ /below staleLockAgeMs/i,
1286
+ );
1287
+ // Valid explicit recovery succeeds
1288
+ const released = releaseStaleLedgerLock(work, { home, nowIso, expectedNonce: staleNonce, confirmedExplicitRecovery: true });
1289
+ assert.equal(released.released, true);
1290
+ assert.equal(released.released_pid, deadPid);
1291
+ assert.equal(fs.existsSync(lockPath), false);
1292
+
1293
+ // Corrupt lockfile refused for automatic removal
1294
+ fs.writeFileSync(lockPath, '{bad json');
1295
+ const corruptLock = inspectLedgerLock(work, { home, nowIso });
1296
+ assert.equal(corruptLock.locked, true);
1297
+ assert.equal(corruptLock.corrupt, true);
1298
+ assert.throws(
1299
+ () => releaseStaleLedgerLock(work, { home, nowIso, expectedNonce: 'any', confirmedExplicitRecovery: true }),
1300
+ /corrupt/i,
1301
+ );
1302
+ fs.unlinkSync(lockPath);
1303
+
1304
+ // 8d. Corrupt JSON refusal on all 3 operational ledgers (never silently reset to empty!)
1305
+ fs.writeFileSync(ledgerPath, '[{"job_id": broken');
1306
+ const badLedgerHash = sha256File(ledgerPath);
1307
+ assert.throws(
1308
+ () => recordApplication(work, { job_id: 'gh:1', status: 'discovered', company: 'Acme', title: 'SWE' }, { home, nowIso }),
1309
+ /Corrupt JSON/i,
1310
+ );
1311
+ assert.equal(sha256File(ledgerPath), badLedgerHash, 'Corrupt applications-log.json must remain untouched');
1312
+ fs.unlinkSync(ledgerPath);
1313
+
1314
+ fs.writeFileSync(skippedPath, '{"not": "an array"}');
1315
+ assert.throws(
1316
+ () => recordSkippedJob(work, { job_id: 'gh:skip1', reason: 'mismatch', skip_reason: 'Wrong stack' }, { home, nowIso }),
1317
+ /expected a JSON array/i,
1318
+ );
1319
+ fs.unlinkSync(skippedPath);
1320
+
1321
+ fs.writeFileSync(cvPath, '{bad cv registry');
1322
+ const sampleCv = path.join(work, 'context', 'cv.md');
1323
+ fs.mkdirSync(path.dirname(sampleCv), { recursive: true });
1324
+ fs.writeFileSync(sampleCv, '# Synthetic Owner CV\nBuilt Node.js systems.\n');
1325
+ assert.throws(
1326
+ () => registerOwnerCvVersionForWorkspace(work, { cv_version_id: 'cv-1', label: 'Base', kind: 'generic', file: 'context/cv.md' }, { home, nowIso }),
1327
+ /Corrupt JSON/i,
1328
+ );
1329
+ fs.unlinkSync(cvPath);
1330
+
1331
+ // 8e. Validation failure before persistence leaves valid existing ledger untouched
1332
+ recordApplication(work, { job_id: 'gh:valid-1', status: 'discovered', company: 'CloudPay', title: 'Backend Engineer' }, { home, nowIso });
1333
+ const beforeValidHash = sha256File(ledgerPath);
1334
+ assert.throws(
1335
+ () => recordApplication(work, { job_id: 'gh:bad-score', status: 'discovered', match_score: 99 }, { home, nowIso }),
1336
+ /match_score/i,
1337
+ );
1338
+ assert.equal(sha256File(ledgerPath), beforeValidHash);
1339
+
1340
+ // 8f. Symlink refusal on protected ledger (when OS allows symlinks)
1341
+ const outsideFile = path.join(dir, 'outside-ledger.json');
1342
+ fs.writeFileSync(outsideFile, '[]');
1343
+ const symWork = makeTempWorkspace('veycraft-t11-sym-');
1344
+ try {
1345
+ const symTarget = path.join(symWork.work, 'logs', 'applications-log.json');
1346
+ let madeSym = false;
1347
+ try {
1348
+ fs.symlinkSync(outsideFile, symTarget);
1349
+ madeSym = true;
1350
+ } catch { /* Windows without symlink privilege */ }
1351
+ if (madeSym) {
1352
+ assert.throws(
1353
+ () => readValidatedApplicationsLedger(symWork.work, { home: symWork.home }),
1354
+ /symbolic-link/i,
1355
+ );
1356
+ }
1357
+ } finally {
1358
+ fs.rmSync(symWork.dir, { recursive: true, force: true });
1359
+ }
1360
+ } finally {
1361
+ fs.rmSync(dir, { recursive: true, force: true });
1362
+ }
1363
+ });
1364
+
1365
+ test('9. Stage 5 (T11.2): Lifecycle write-engine enforces dedup, reservation, receipt immutability, transitions & skip dedup', () => {
1366
+ const { dir, home, work } = makeTempWorkspace('veycraft-t11-life-');
1367
+ const t0 = '2026-11-23T09:00:00Z';
1368
+ const t1 = '2026-11-23T09:05:00Z';
1369
+ const t2 = '2026-11-23T09:10:00Z';
1370
+ const t3 = '2026-11-24T10:00:00Z';
1371
+ const t4 = '2026-11-25T11:00:00Z';
1372
+ const t5 = '2026-11-26T12:00:00Z';
1373
+ const t6 = '2026-11-27T13:00:00Z';
1374
+
1375
+ try {
1376
+ // 9a. recordApplication: create, idempotent repeat, non-submitted update, reject direct submitted status & non-HTTP(S) URLs
1377
+ assert.throws(
1378
+ () => recordApplication(work, { job_id: 'gh:badurl', status: 'discovered', url: 'javascript:alert(1)' }, { home, nowIso: t0 }),
1379
+ /non-HTTP\(S\)/i,
1380
+ );
1381
+ assert.throws(
1382
+ () => recordApplication(work, { job_id: 'gh:100', status: 'applied', company: 'CloudPay', title: 'Backend Engineer' }, { home, nowIso: t0 }),
1383
+ /only accepts non-submission statuses/i,
1384
+ );
1385
+ const created = recordApplication(work, {
1386
+ job_id: 'greenhouse:cloudpay-100',
1387
+ status: 'discovered',
1388
+ company: 'CloudPay Ledger',
1389
+ title: 'Senior Backend Engineer',
1390
+ platform: 'greenhouse',
1391
+ url: 'https://boards.greenhouse.io/cloudpay/jobs/100?utm_source=linkedin',
1392
+ match_score: 9.0,
1393
+ matched_skills: ['Node.js', 'TypeScript', 'PostgreSQL'],
1394
+ missing_skills: ['Kubernetes'],
1395
+ }, { home, nowIso: t0 });
1396
+ assert.equal(created.action, 'created');
1397
+ assert.equal(created.application_id, computeApplicationId('greenhouse:cloudpay-100'));
1398
+ assert.equal(created.canonical_fingerprint, 'cloudpay-ledger::senior-backend-engineer');
1399
+
1400
+ // Idempotent repeat makes no duplicate entry
1401
+ const repeat = recordApplication(work, {
1402
+ job_id: 'greenhouse:cloudpay-100',
1403
+ status: 'discovered',
1404
+ company: 'CloudPay Ledger',
1405
+ title: 'Senior Backend Engineer',
1406
+ }, { home, nowIso: t0 });
1407
+ assert.equal(repeat.action, 'idempotent_no_op');
1408
+
1409
+ // Update non-submitted to prepared
1410
+ const prepared = recordApplication(work, {
1411
+ job_id: 'greenhouse:cloudpay-100',
1412
+ status: 'prepared',
1413
+ notes: 'Tailored CV generated',
1414
+ }, { home, nowIso: t1 });
1415
+ assert.equal(prepared.action, 'updated');
1416
+ assert.equal(prepared.status, 'prepared');
1417
+ assert.equal(prepared.record.stage_history.length, 2);
1418
+
1419
+ // 9b. reserveApplicationSubmission: sets needs_review + submission_uncertain=true + applied_at=null
1420
+ const reserved = reserveApplicationSubmission(work, {
1421
+ job_id: 'greenhouse:cloudpay-100',
1422
+ }, { home, nowIso: t1, sourceRoot: REPO_ROOT });
1423
+ assert.equal(reserved.reserved, true);
1424
+ assert.equal(reserved.status, 'needs_review');
1425
+ assert.equal(reserved.submission_uncertain, true);
1426
+ assert.equal(reserved.applied_at, null);
1427
+
1428
+ // Refuses duplicate reservation & refuses downgrading active reservation via record
1429
+ assert.throws(
1430
+ () => reserveApplicationSubmission(work, { job_id: 'greenhouse:cloudpay-100' }, { home, nowIso: t2, sourceRoot: REPO_ROOT }),
1431
+ /already_reserved/i,
1432
+ );
1433
+ assert.throws(
1434
+ () => recordApplication(work, { job_id: 'greenhouse:cloudpay-100', status: 'prepared' }, { home, nowIso: t2 }),
1435
+ /reservation_active/i,
1436
+ );
1437
+ // Refuses transitioning unsubmitted reservation directly to interview
1438
+ assert.throws(
1439
+ () => transitionApplicationStage(work, { job_id: 'greenhouse:cloudpay-100', to_status: 'interview' }, { home, nowIso: t2 }),
1440
+ /cannot_transition_unsubmitted/i,
1441
+ );
1442
+
1443
+ // 9c. confirmApplicationSubmission: rejects blank/invalid/placeholder/too-long receipts
1444
+ for (const badReceipt of ['', ' ', 'ok', 'Thank you {{COMPANY}}', 'x'.repeat(161)]) {
1445
+ assert.throws(
1446
+ () => confirmApplicationSubmission(work, { job_id: 'greenhouse:cloudpay-100', receipt: badReceipt }, { home, nowIso: t2 }),
1447
+ /Receipt quote/i,
1448
+ );
1449
+ }
1450
+
1451
+ const confirmed = confirmApplicationSubmission(work, {
1452
+ job_id: 'greenhouse:cloudpay-100',
1453
+ receipt: 'Thank you for applying to CloudPay Ledger',
1454
+ url: 'https://boards.greenhouse.io/cloudpay/jobs/100/confirmation',
1455
+ }, { home, nowIso: t2 });
1456
+ assert.equal(confirmed.confirmed, true);
1457
+ assert.equal(confirmed.status, 'applied');
1458
+ assert.equal(confirmed.applied_at, t2);
1459
+ assert.equal(confirmed.record.submission_uncertain, false);
1460
+ assert.equal(confirmed.record.provenance.receipt_verified, true);
1461
+ assert.match(confirmed.record.notes, /receipt:\s*"Thank you for applying to CloudPay Ledger"/);
1462
+
1463
+ // Refuses duplicate confirmation, receipt overwrite, or record downgrade
1464
+ assert.throws(
1465
+ () => confirmApplicationSubmission(work, { job_id: 'greenhouse:cloudpay-100', receipt: 'Another receipt' }, { home, nowIso: t3 }),
1466
+ /already_confirmed/i,
1467
+ );
1468
+ assert.throws(
1469
+ () => recordApplication(work, { job_id: 'greenhouse:cloudpay-100', status: 'prepared' }, { home, nowIso: t3 }),
1470
+ /cannot_downgrade_submitted/i,
1471
+ );
1472
+ // Refuses cross-channel duplicate via record
1473
+ assert.throws(
1474
+ () => recordApplication(work, {
1475
+ job_id: 'linkedin:dup-999',
1476
+ status: 'discovered',
1477
+ company: 'CloudPay Ledger',
1478
+ title: 'Senior Backend Engineer',
1479
+ platform: 'linkedin',
1480
+ }, { home, nowIso: t3, sourceRoot: REPO_ROOT }),
1481
+ /duplicate_application/i,
1482
+ );
1483
+
1484
+ // Refuses confirming a dry_run or skipped record
1485
+ recordApplication(work, { job_id: 'lever:dry-1', status: 'dry_run', company: 'DryCo', title: 'Eng' }, { home, nowIso: t2 });
1486
+ assert.throws(
1487
+ () => confirmApplicationSubmission(work, { job_id: 'lever:dry-1', receipt: 'Application received' }, { home, nowIso: t3 }),
1488
+ /invalid_confirm_source_status/i,
1489
+ );
1490
+
1491
+ // 9d. transitionApplicationStage: follow-up on applied, interview + assessment + offer + withdrawn; preserves applied_at & receipt
1492
+ const followed = transitionApplicationStage(work, {
1493
+ job_id: 'greenhouse:cloudpay-100',
1494
+ to_status: 'applied',
1495
+ source: 'follow_up_radar',
1496
+ follow_up: { status: 'sent', draft_rel: 'logs/resumes/cloudpay-100/followup-draft.md' },
1497
+ notes: 'Sent 7d check-in',
1498
+ }, { home, nowIso: t3 });
1499
+ assert.equal(followed.record.follow_up.status, 'sent');
1500
+ assert.equal(followed.record.follow_up.follow_up_count, 1);
1501
+ assert.equal(followed.record.applied_at, t2);
1502
+
1503
+ const iv = transitionApplicationStage(work, {
1504
+ job_id: 'greenhouse:cloudpay-100',
1505
+ to_status: 'interview',
1506
+ source: 'recruiter_inbox_triage',
1507
+ interview: { stage: 'technical_screen', round: 1, scheduled_at: t4, timezone: 'UTC', status: 'scheduled', outcome: 'pending' },
1508
+ notes: 'Invited to technical screen',
1509
+ }, { home, nowIso: t4 });
1510
+ assert.equal(iv.to_status, 'interview');
1511
+ assert.equal(iv.record.interviews.length, 1);
1512
+ assert.equal(iv.record.interviews[0].stage, 'technical_screen');
1513
+ assert.equal(iv.record.applied_at, t2);
1514
+ assert.match(iv.record.notes, /receipt:\s*"Thank you for applying to CloudPay Ledger"/);
1515
+
1516
+ // Idempotent repeat of exact same status without supplemental update
1517
+ const ivNoOp = transitionApplicationStage(work, {
1518
+ job_id: 'greenhouse:cloudpay-100',
1519
+ to_status: 'interview',
1520
+ }, { home, nowIso: t4 });
1521
+ assert.equal(ivNoOp.action, 'idempotent_no_op');
1522
+
1523
+ // Backward timestamp rejected
1524
+ assert.throws(
1525
+ () => transitionApplicationStage(work, { job_id: 'greenhouse:cloudpay-100', to_status: 'assessment', at: t0 }, { home, nowIso: t5 }),
1526
+ /cannot precede/i,
1527
+ );
1528
+
1529
+ const asmt = transitionApplicationStage(work, {
1530
+ job_id: 'greenhouse:cloudpay-100',
1531
+ to_status: 'assessment',
1532
+ source: 'recruiter_inbox_triage',
1533
+ assessment: { type: 'take_home', due_at: t6, status: 'assigned', outcome: 'pending' },
1534
+ }, { home, nowIso: t5 });
1535
+ assert.equal(asmt.record.assessments.length, 1);
1536
+ assert.equal(asmt.record.assessments[0].type, 'take_home');
1537
+
1538
+ const rej = transitionApplicationStage(work, {
1539
+ job_id: 'greenhouse:cloudpay-100',
1540
+ to_status: 'rejected',
1541
+ source: 'recruiter_inbox_triage',
1542
+ notes: 'Role filled internally',
1543
+ }, { home, nowIso: t6 });
1544
+ assert.equal(rej.to_status, 'rejected');
1545
+ assert.equal(rej.record.applied_at, t2);
1546
+
1547
+ // Terminal state rejects invalid transitions (e.g., rejected -> offer)
1548
+ assert.throws(
1549
+ () => transitionApplicationStage(work, { job_id: 'greenhouse:cloudpay-100', to_status: 'offer' }, { home, nowIso: t6 }),
1550
+ /invalid_stage_transition/i,
1551
+ );
1552
+
1553
+ // 9e. recordSkippedJob: dedup, update, >160 char rejection
1554
+ assert.throws(
1555
+ () => recordSkippedJob(work, { job_id: 'gh:s1', reason: 'ghost_or_expired', skip_reason: 'a'.repeat(161) }, { home, nowIso: t0 }),
1556
+ /exceeds maximum length/i,
1557
+ );
1558
+ const sk1 = recordSkippedJob(work, {
1559
+ job_id: 'gh:s1',
1560
+ company: 'GhostCo',
1561
+ title: 'Old Role',
1562
+ platform: 'greenhouse',
1563
+ reason: 'ghost_or_expired',
1564
+ skip_reason: 'Closed banner observed',
1565
+ }, { home, nowIso: t0 });
1566
+ assert.equal(sk1.action, 'created');
1567
+ const skDup = recordSkippedJob(work, {
1568
+ job_id: 'GH:S1',
1569
+ company: 'GhostCo',
1570
+ title: 'Old Role',
1571
+ platform: 'greenhouse',
1572
+ reason: 'ghost_or_expired',
1573
+ skip_reason: 'Closed banner observed',
1574
+ }, { home, nowIso: t1 });
1575
+ assert.equal(skDup.action, 'idempotent_no_op');
1576
+ assert.equal(readValidatedSkippedJobs(work, { home }).records.length, 1);
1577
+ } finally {
1578
+ fs.rmSync(dir, { recursive: true, force: true });
1579
+ }
1580
+ });
1581
+
1582
+ test('10. Stage 5 (T11.3): CV registration computes SHA-256, enforces isolation/path safety & handles cross-file transaction failure/recovery', () => {
1583
+ const { dir, home, work } = makeTempWorkspace('veycraft-t11-cv-');
1584
+ const t0 = '2026-11-23T10:00:00Z';
1585
+ const t1 = '2026-11-23T10:05:00Z';
1586
+
1587
+ try {
1588
+ const ownerCv = path.join(work, 'logs', 'resumes', 'cloudpay-100', 'resume.html');
1589
+ fs.mkdirSync(path.dirname(ownerCv), { recursive: true });
1590
+ fs.writeFileSync(ownerCv, '<html><body><h1>Synthetic Candidate</h1><p>Node.js & PostgreSQL</p></body></html>');
1591
+ const expectedSha = sha256File(ownerCv);
1592
+
1593
+ // 10a. Single-file registration + SHA-256 + re-registration preserves created_at
1594
+ const reg1 = registerOwnerCvVersionForWorkspace(work, {
1595
+ cv_version_id: 'cv-cloudpay-v1',
1596
+ label: 'CloudPay Backend Tailored CV',
1597
+ kind: 'tailored',
1598
+ file: 'logs/resumes/cloudpay-100/resume.html',
1599
+ target_role: 'Senior Backend Engineer',
1600
+ ats_keyword_before_pct: 68,
1601
+ ats_keyword_after_pct: 91,
1602
+ }, { home, nowIso: t0 });
1603
+ assert.equal(reg1.registered, true);
1604
+ assert.equal(reg1.content_sha256, expectedSha);
1605
+ assert.equal(reg1.version.created_at, t0);
1606
+
1607
+ const reg2 = registerOwnerCvVersionForWorkspace(work, {
1608
+ cv_version_id: 'cv-cloudpay-v1',
1609
+ label: 'CloudPay Backend Tailored CV (Rev 2)',
1610
+ kind: 'tailored',
1611
+ file: 'logs/resumes/cloudpay-100/resume.html',
1612
+ }, { home, nowIso: t1 });
1613
+ assert.equal(reg2.version.created_at, t0, 'Re-registration must preserve original created_at');
1614
+ assert.equal(reg2.version.label, 'CloudPay Backend Tailored CV (Rev 2)');
1615
+
1616
+ // 10b. Security & third-party isolation refusals
1617
+ const tpCv = path.join(work, 'logs', 'resumes', 'cv-friend-alex', 'resume.html');
1618
+ fs.mkdirSync(path.dirname(tpCv), { recursive: true });
1619
+ fs.writeFileSync(tpCv, '<html><body><h1>Third Party</h1></body></html>');
1620
+ assert.throws(
1621
+ () => registerOwnerCvVersionForWorkspace(work, {
1622
+ cv_version_id: 'cv-tp-1',
1623
+ label: 'Friend CV',
1624
+ kind: 'generic',
1625
+ file: 'logs/resumes/cv-friend-alex/resume.html',
1626
+ }, { home, nowIso: t1 }),
1627
+ /third-party/i,
1628
+ );
1629
+ assert.throws(
1630
+ () => registerOwnerCvVersionForWorkspace(work, {
1631
+ cv_version_id: 'cv-tp-2',
1632
+ label: 'Marked 3P',
1633
+ kind: 'generic',
1634
+ file: 'logs/resumes/cloudpay-100/resume.html',
1635
+ owner_scope: 'third_party',
1636
+ }, { home, nowIso: t1 }),
1637
+ /third-party/i,
1638
+ );
1639
+
1640
+ // Path traversal refusal
1641
+ const outsideCv = path.join(dir, 'outside-cv.md');
1642
+ fs.writeFileSync(outsideCv, '# Outside');
1643
+ assert.throws(
1644
+ () => registerOwnerCvVersionForWorkspace(work, {
1645
+ cv_version_id: 'cv-escape',
1646
+ label: 'Escape',
1647
+ kind: 'generic',
1648
+ file: '../outside-cv.md',
1649
+ }, { home, nowIso: t1 }),
1650
+ /outside workspace boundary/i,
1651
+ );
1652
+
1653
+ // Symlink refusal (when OS permits symlink creation)
1654
+ const symCv = path.join(work, 'context', 'sym-cv.md');
1655
+ fs.mkdirSync(path.dirname(symCv), { recursive: true });
1656
+ let madeSym = false;
1657
+ try {
1658
+ fs.symlinkSync(outsideCv, symCv);
1659
+ madeSym = true;
1660
+ } catch { /* ignore if OS blocks symlinks */ }
1661
+ if (madeSym) {
1662
+ assert.throws(
1663
+ () => registerOwnerCvVersionForWorkspace(work, {
1664
+ cv_version_id: 'cv-sym',
1665
+ label: 'Sym',
1666
+ kind: 'generic',
1667
+ file: 'context/sym-cv.md',
1668
+ }, { home, nowIso: t1 }),
1669
+ /symbolic-link/i,
1670
+ );
1671
+ fs.unlinkSync(symCv);
1672
+ }
1673
+
1674
+ // 10c. Cross-file application linking transaction (success, step-2 rollback, crash-recovery detection)
1675
+ recordApplication(work, {
1676
+ job_id: 'gh:link-100',
1677
+ status: 'prepared',
1678
+ company: 'CloudPay',
1679
+ title: 'Senior Backend Engineer',
1680
+ platform: 'greenhouse',
1681
+ }, { home, nowIso: t0 });
1682
+ recordApplication(work, {
1683
+ job_id: 'gh:tp-app',
1684
+ status: 'prepared',
1685
+ company: 'FriendCo',
1686
+ title: 'Designer',
1687
+ third_party_subject: true,
1688
+ }, { home, nowIso: t0 });
1689
+
1690
+ // Refuses linking owner CV to third-party application
1691
+ assert.throws(
1692
+ () => registerOwnerCvVersionForWorkspace(work, {
1693
+ cv_version_id: 'cv-cloudpay-v1',
1694
+ label: 'Owner CV',
1695
+ kind: 'tailored',
1696
+ file: 'logs/resumes/cloudpay-100/resume.html',
1697
+ link_job_id: 'gh:tp-app',
1698
+ }, { home, nowIso: t1 }),
1699
+ /third_party_blocked/i,
1700
+ );
1701
+
1702
+ const cvRegPath = path.join(work, 'logs', 'cv-versions.json');
1703
+ const ledgerPath = path.join(work, 'logs', 'applications-log.json');
1704
+ const txPath = path.join(work, 'logs', LEDGER_TX_FILENAME);
1705
+ const cvHashBefore = sha256File(cvRegPath);
1706
+ const ledgerHashBefore = sha256File(ledgerPath);
1707
+
1708
+ // Simulate failure right before second file write -> automatic compensating rollback must restore BOTH files!
1709
+ assert.throws(
1710
+ () => registerOwnerCvVersionForWorkspace(work, {
1711
+ cv_version_id: 'cv-rollback-test',
1712
+ label: 'Rollback Test CV',
1713
+ kind: 'tailored',
1714
+ file: 'logs/resumes/cloudpay-100/resume.html',
1715
+ link_job_id: 'gh:link-100',
1716
+ }, {
1717
+ home,
1718
+ nowIso: t1,
1719
+ _testHooks: {
1720
+ beforeSecondWrite: () => { throw new Error('Simulated disk error before ledger write'); },
1721
+ },
1722
+ }),
1723
+ /cv_register_link_rolled_back/i,
1724
+ );
1725
+ assert.equal(sha256File(cvRegPath), cvHashBefore, 'cv-versions.json must be rolled back identically');
1726
+ assert.equal(sha256File(ledgerPath), ledgerHashBefore, 'applications-log.json must remain unchanged');
1727
+ assert.equal(fs.existsSync(txPath), false, 'tx journal cleaned up after clean rollback');
1728
+
1729
+ // Simulate crash / failed rollback leaving logs/.ledger-tx.json -> subsequent mutations MUST fail closed until explicit recovery!
1730
+ assert.throws(
1731
+ () => registerOwnerCvVersionForWorkspace(work, {
1732
+ cv_version_id: 'cv-crash-test',
1733
+ label: 'Crash Test CV',
1734
+ kind: 'tailored',
1735
+ file: 'logs/resumes/cloudpay-100/resume.html',
1736
+ link_job_id: 'gh:link-100',
1737
+ }, {
1738
+ home,
1739
+ nowIso: t1,
1740
+ _testHooks: {
1741
+ beforeSecondWrite: () => { throw new Error('Simulated crash during step 2'); },
1742
+ onRollback: () => { throw new Error('Simulated crash during rollback'); },
1743
+ },
1744
+ }),
1745
+ /cv_register_link_rollback_failed/i,
1746
+ );
1747
+ assert.equal(fs.existsSync(txPath), true, 'tx journal must remain for crash detection');
1748
+ const txInfo = inspectLedgerTransaction(work, { home });
1749
+ assert.equal(txInfo.pending, true);
1750
+ assert.equal(txInfo.transaction.stage, 'rollback_failed');
1751
+
1752
+ // Subsequent writes MUST fail closed while tx journal exists
1753
+ assert.throws(
1754
+ () => recordApplication(work, { job_id: 'gh:blocked-by-tx', status: 'discovered' }, { home, nowIso: t1 }),
1755
+ /incomplete_ledger_transaction/i,
1756
+ );
1757
+ assert.throws(
1758
+ () => recoverIncompleteLedgerTransaction(work, { home, nowIso: t1, confirmRollback: false }),
1759
+ /confirmRollback/i,
1760
+ );
1761
+
1762
+ // Explicit rollback recovery restores exact pre-crash bytes and clears journal
1763
+ const recovered = recoverIncompleteLedgerTransaction(work, { home, nowIso: t1, confirmRollback: true });
1764
+ assert.equal(recovered.recovered, true);
1765
+ assert.equal(sha256File(cvRegPath), cvHashBefore);
1766
+ assert.equal(sha256File(ledgerPath), ledgerHashBefore);
1767
+ assert.equal(fs.existsSync(txPath), false);
1768
+
1769
+ // Clean cross-file link succeeds and reflects in both cv-versions and applications-log
1770
+ const linked = registerOwnerCvVersionForWorkspace(work, {
1771
+ cv_version_id: 'cv-cloudpay-v1',
1772
+ label: 'CloudPay Backend Tailored CV',
1773
+ kind: 'tailored',
1774
+ file: 'logs/resumes/cloudpay-100/resume.html',
1775
+ link_job_id: 'gh:link-100',
1776
+ ats_keyword_before_pct: 70,
1777
+ ats_keyword_after_pct: 92,
1778
+ }, { home, nowIso: t1 });
1779
+ assert.equal(linked.linked_application_id, computeApplicationId('gh:link-100'));
1780
+ assert.equal(fs.existsSync(txPath), false);
1781
+ const listed = listOwnerCvVersions(work, { home });
1782
+ assert.equal(listed.versions.find(v => v.cv_version_id === 'cv-cloudpay-v1').linked_applications_count, 1);
1783
+ const ledgerAfter = readValidatedApplicationsLedger(work, { home }).records;
1784
+ const linkedApp = ledgerAfter.find(r => r.job_id === 'gh:link-100');
1785
+ assert.equal(linkedApp.cv_version_id, 'cv-cloudpay-v1');
1786
+ assert.equal(linkedApp.cv_tailoring.is_tailored, true);
1787
+ assert.equal(linkedApp.cv_tailoring.ats_keyword_after_pct, 92);
1788
+ } finally {
1789
+ fs.rmSync(dir, { recursive: true, force: true });
1790
+ }
1791
+ });
1792
+
1793
+ test('11. Stage 5 (T11.4): Pre-submit integrity gate (caps, uncertain reservations, platform, circuit breaker, blacklists, dedup) & cmdStatus alignment', () => {
1794
+ const { dir, home, work } = makeTempWorkspace('veycraft-t11-gate-');
1795
+ const today = '2026-11-23';
1796
+ const nowIso = `${today}T12:00:00Z`;
1797
+
1798
+ try {
1799
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
1800
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
1801
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
1802
+ fs.writeFileSync(
1803
+ path.join(work, 'context', 'preferences.yaml'),
1804
+ [
1805
+ 'blacklisted_companies: ["ToxicStaffing Global", "OldEmployer"]',
1806
+ 'blacklisted_domains:',
1807
+ ' - "spam-agency.example"',
1808
+ ' - "blocked.corp"',
1809
+ ].join('\n') + '\n',
1810
+ );
1811
+
1812
+ // Seed 3 applied + 1 unresolved submission_uncertain reservation today + 2 excluded (dry_run, third_party) + 1 old 20-day silent applied
1813
+ const seed = [
1814
+ normalizeApplicationRecord({ job_id: 'gh:a1', company: 'AlphaCo', title: 'Backend Eng', platform: 'greenhouse', url: 'https://boards.greenhouse.io/alpha/jobs/1', status: 'applied', applied_at: `${today}T08:00:00Z`, notes: 'receipt: "Submitted alpha"' }),
1815
+ normalizeApplicationRecord({ job_id: 'gh:a2', company: 'BetaCo', title: 'Platform Eng', platform: 'greenhouse', url: 'https://boards.greenhouse.io/beta/jobs/2', status: 'applied', applied_at: `${today}T08:30:00Z`, notes: 'receipt: "Submitted beta"' }),
1816
+ normalizeApplicationRecord({ job_id: 'gh:a3', company: 'GammaCo', title: 'API Eng', platform: 'greenhouse', url: 'https://boards.greenhouse.io/gamma/jobs/3', status: 'applied', applied_at: `${today}T09:00:00Z`, notes: 'receipt: "Submitted gamma"' }),
1817
+ normalizeApplicationRecord({ job_id: 'li:res1', company: 'DeltaCo', title: 'Fullstack Eng', platform: 'linkedin', url: 'https://www.linkedin.com/jobs/view/5001', status: 'needs_review', submission_uncertain: true, applied_at: null, updated_at: `${today}T09:30:00Z` }),
1818
+ normalizeApplicationRecord({ job_id: 'li:dry1', company: 'DryCo', title: 'Eng', platform: 'linkedin', status: 'dry_run', applied_at: null, updated_at: `${today}T09:35:00Z` }),
1819
+ normalizeApplicationRecord({ job_id: 'li:tp1', company: 'ThirdPartyCo', title: 'Designer', platform: 'linkedin', status: 'applied', applied_at: `${today}T09:40:00Z`, provenance: { created_by: 'test', created_at: `${today}T09:40:00Z`, last_updated_by: null, receipt_verified: true, third_party_subject: true } }),
1820
+ normalizeApplicationRecord({ job_id: 'li:silent20', company: 'QuietCo', title: 'Old Role', platform: 'linkedin', url: 'https://www.linkedin.com/jobs/view/100', status: 'applied', applied_at: '2026-11-01T10:00:00Z', notes: 'receipt: "Submitted quiet"' }),
1821
+ ];
1822
+ fs.writeFileSync(path.join(work, 'logs', 'applications-log.json'), JSON.stringify(seed, null, 2));
1823
+
1824
+ // 11a. Uncertain reservation MUST count toward daily/warm-up cap (4/5: 3 applied + 1 uncertain; dry_run & 3P excluded)
1825
+ const gate4 = evaluatePreSubmitGate(work, { platform: 'linkedin', company: 'FreshCo', title: 'Staff Eng', url: 'https://www.linkedin.com/jobs/view/9999', job_id: 'li:fresh-1' }, { home, nowIso, sourceRoot: REPO_ROOT });
1826
+ assert.equal(gate4.allowed, true);
1827
+ assert.equal(gate4.checks.daily_cap.today_applied, 3);
1828
+ assert.equal(gate4.checks.daily_cap.today_submission_uncertain, 1);
1829
+ assert.equal(gate4.checks.daily_cap.today_counted, 4);
1830
+ assert.equal(gate4.checks.daily_cap.effective_cap, 5);
1831
+
1832
+ // 11b. Per-platform cap: greenhouse has 3/3 -> BLOCKED; workday has cap 0 -> BLOCKED
1833
+ const gateGh = evaluatePreSubmitGate(work, { platform: 'greenhouse', company: 'NewCo', title: 'Eng', job_id: 'gh:new' }, { home, nowIso, sourceRoot: REPO_ROOT });
1834
+ assert.equal(gateGh.allowed, false);
1835
+ assert.ok(gateGh.violations.some(v => v.code === 'platform_cap_reached'));
1836
+
1837
+ const gateWd = evaluatePreSubmitGate(work, { platform: 'workday', company: 'NewCo', title: 'Eng', job_id: 'wd:new' }, { home, nowIso, sourceRoot: REPO_ROOT });
1838
+ assert.equal(gateWd.allowed, false);
1839
+ assert.ok(gateWd.violations.some(v => v.code === 'platform_disabled'));
1840
+
1841
+ // 11c. Blacklists: company substring & subdomain domain match -> BLOCKED
1842
+ const gateBlCo = evaluatePreSubmitGate(work, { platform: 'linkedin', company: 'ToxicStaffing Global LLC', title: 'Eng', job_id: 'li:bl1' }, { home, nowIso, sourceRoot: REPO_ROOT });
1843
+ assert.equal(gateBlCo.allowed, false);
1844
+ assert.ok(gateBlCo.violations.some(v => v.code === 'blacklisted_employer'));
1845
+
1846
+ const gateBlDom = evaluatePreSubmitGate(work, { platform: 'linkedin', company: 'CleanName', title: 'Eng', url: 'https://careers.spam-agency.example/jobs/1', job_id: 'li:bl2' }, { home, nowIso, sourceRoot: REPO_ROOT });
1847
+ assert.equal(gateBlDom.allowed, false);
1848
+ assert.ok(gateBlDom.violations.some(v => v.code === 'blacklisted_domain'));
1849
+
1850
+ // 11d. Circuit breaker: active cooldown blocks, expired cooldown passes
1851
+ fs.writeFileSync(path.join(work, 'logs', 'circuit-breaker.json'), JSON.stringify({
1852
+ platforms: {
1853
+ linkedin: { status: 'tripped', tripped_at: `${today}T10:00:00Z`, cooldown_until: '2026-11-24T10:00:00Z', trigger_signal: 'HTTP 429' },
1854
+ wellfound: { status: 'tripped', tripped_at: '2026-11-20T10:00:00Z', cooldown_until: '2026-11-21T10:00:00Z', trigger_signal: 'Old' },
1855
+ },
1856
+ }, null, 2));
1857
+ const gateCb = evaluatePreSubmitGate(work, { platform: 'linkedin', company: 'NewCo', title: 'Eng', job_id: 'li:cb1' }, { home, nowIso, sourceRoot: REPO_ROOT });
1858
+ assert.equal(gateCb.allowed, false);
1859
+ assert.ok(gateCb.violations.some(v => v.code === 'circuit_breaker_active'));
1860
+
1861
+ const gateCbExpired = evaluatePreSubmitGate(work, { platform: 'wellfound', company: 'NewCo', title: 'Eng', job_id: 'wf:ok1' }, { home, nowIso, sourceRoot: REPO_ROOT });
1862
+ assert.equal(gateCbExpired.allowed, true);
1863
+ fs.unlinkSync(path.join(work, 'logs', 'circuit-breaker.json'));
1864
+
1865
+ // 11e. Deduplication: job_id, canonical URL (ignoring utm_*), and cross-channel 60-day fingerprint
1866
+ assert.equal(
1867
+ normalizeCanonicalUrl('https://www.boards.greenhouse.io/alpha/jobs/1/?utm_source=x&refId=abc&gh_jid=1'),
1868
+ 'https://boards.greenhouse.io/alpha/jobs/1',
1869
+ );
1870
+ const gateDupId = evaluatePreSubmitGate(work, { platform: 'linkedin', job_id: 'LI:RES1' }, { home, nowIso, sourceRoot: REPO_ROOT });
1871
+ assert.equal(gateDupId.allowed, false);
1872
+ assert.ok(gateDupId.violations.some(v => v.code === 'duplicate_job_id'));
1873
+
1874
+ const gateDupUrl = evaluatePreSubmitGate(work, { platform: 'wellfound', url: 'https://boards.greenhouse.io/alpha/jobs/1?utm_campaign=job', job_id: 'wf:dupurl' }, { home, nowIso, sourceRoot: REPO_ROOT });
1875
+ assert.equal(gateDupUrl.allowed, false);
1876
+ assert.ok(gateDupUrl.violations.some(v => v.code === 'duplicate_canonical_url'));
1877
+
1878
+ const gateDupFp = evaluatePreSubmitGate(work, { platform: 'wellfound', company: 'AlphaCo', title: 'Backend Eng', job_id: 'wf:dupfp' }, { home, nowIso, sourceRoot: REPO_ROOT });
1879
+ assert.equal(gateDupFp.allowed, false);
1880
+ assert.ok(gateDupFp.violations.some(v => v.code === 'duplicate_cross_channel'));
1881
+
1882
+ // 11f. Adding 5th reservation blocks the 6th at warm-up cap 5/5!
1883
+ const res5 = reserveApplicationSubmission(work, { job_id: 'wf:fifth', company: 'FifthCo', title: 'Staff Eng', platform: 'wellfound' }, { home, nowIso, sourceRoot: REPO_ROOT });
1884
+ assert.equal(res5.reserved, true);
1885
+ assert.throws(
1886
+ () => reserveApplicationSubmission(work, { job_id: 'wf:sixth', company: 'SixthCo', title: 'Staff Eng', platform: 'wellfound' }, { home, nowIso, sourceRoot: REPO_ROOT }),
1887
+ /daily_cap_reached/i,
1888
+ );
1889
+
1890
+ // 11g. computeWorkspaceStatusMetrics / cmdStatus alignment: 22-day silent applied is silent_14d, NOT rejected; 3P excluded; MIN_N=5 respected
1891
+ const st = computeWorkspaceStatusMetrics(work, { home, nowIso, sourceRoot: REPO_ROOT });
1892
+ assert.equal(st.daily_cap.today, 5);
1893
+ assert.equal(st.daily_cap.submission_uncertain_today, 2);
1894
+ assert.equal(st.pipeline.applied, 4); // 3 today + 1 silent20 (3P excluded, uncertain not counted as applied)
1895
+ assert.equal(st.pipeline.rejected, 0, '14+ day silence must NEVER be counted as confirmed rejection');
1896
+ assert.equal(st.pipeline.rejected_or_ghosted, 0);
1897
+ assert.equal(st.pipeline.silent_14d, 1);
1898
+ assert.equal(st.third_party_excluded, 1);
1899
+ assert.match(st.top_platform, /insufficient sample|MIN_N=5/i);
1900
+ } finally {
1901
+ fs.rmSync(dir, { recursive: true, force: true });
1902
+ }
1903
+ });
1904
+
1905
+ test('12. Stage 5 (T11.5): End-to-end scoped CLI lifecycle, pre-submit JSON/flags, recovery commands & error handling', () => {
1906
+ const { dir, home, work } = makeTempWorkspace('veycraft-t11-cli-');
1907
+ try {
1908
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
1909
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
1910
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
1911
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
1912
+ const cvFile = path.join(work, 'logs', 'resumes', 'acme-901', 'resume.html');
1913
+ fs.mkdirSync(path.dirname(cvFile), { recursive: true });
1914
+ fs.writeFileSync(cvFile, '<html><body><h1>Synthetic Owner</h1><p>TypeScript</p></body></html>');
1915
+
1916
+ // 1. career record
1917
+ const r1 = runCli([
1918
+ 'career', 'record',
1919
+ '--job-id', 'lever:acme-901',
1920
+ '--status', 'prepared',
1921
+ '--company', 'Acme Cloud',
1922
+ '--title', 'Senior Full-Stack Engineer',
1923
+ '--platform', 'lever',
1924
+ '--url', 'https://jobs.lever.co/acme/901',
1925
+ '--match-score', '8.8',
1926
+ '--json',
1927
+ ], { cwd: work, home });
1928
+ assert.equal(r1.status, 0, r1.stdout + r1.stderr);
1929
+ const r1j = JSON.parse(r1.stdout);
1930
+ assert.equal(r1j.action, 'created');
1931
+ assert.equal(r1j.status, 'prepared');
1932
+
1933
+ // 2. career cv-register with application link
1934
+ const rCv = runCli([
1935
+ 'career', 'cv-register',
1936
+ '--id', 'cv-acme-901',
1937
+ '--label', 'Acme Fullstack Tailored',
1938
+ '--kind', 'tailored',
1939
+ '--file', 'logs/resumes/acme-901/resume.html',
1940
+ '--link-job-id', 'lever:acme-901',
1941
+ '--ats-before', '72',
1942
+ '--ats-after', '93',
1943
+ '--json',
1944
+ ], { cwd: work, home });
1945
+ assert.equal(rCv.status, 0, rCv.stdout + rCv.stderr);
1946
+ const rCvJ = JSON.parse(rCv.stdout);
1947
+ assert.equal(rCvJ.registered, true);
1948
+ assert.equal(rCvJ.linked_application_id, r1j.application_id);
1949
+
1950
+ // 3. pre-submit with candidate flags & --json
1951
+ const rPre = runCli([
1952
+ 'pre-submit',
1953
+ '--platform', 'lever',
1954
+ '--company', 'Acme Cloud',
1955
+ '--title', 'Senior Full-Stack Engineer',
1956
+ '--url', 'https://jobs.lever.co/acme/901',
1957
+ '--job-id', 'lever:acme-901',
1958
+ '--text', 'Short grounded note under seventy-five words.',
1959
+ '--json',
1960
+ ], { cwd: work, home });
1961
+ assert.equal(rPre.status, 0, rPre.stdout + rPre.stderr);
1962
+ assert.equal(JSON.parse(rPre.stdout).allowed, true);
1963
+
1964
+ // 4. career reserve -> pre-submit now blocks duplicate reservation!
1965
+ const rRes = runCli(['career', 'reserve', '--job-id', 'lever:acme-901', '--json'], { cwd: work, home });
1966
+ assert.equal(rRes.status, 0, rRes.stdout + rRes.stderr);
1967
+ assert.equal(JSON.parse(rRes.stdout).submission_uncertain, true);
1968
+
1969
+ const rPreDup = runCli(['pre-submit', '--job-id', 'lever:acme-901', '--json'], { cwd: work, home });
1970
+ assert.notEqual(rPreDup.status, 0);
1971
+ assert.equal(JSON.parse(rPreDup.stdout).allowed, false);
1972
+
1973
+ // 5. career confirm-submit
1974
+ const rConf = runCli([
1975
+ 'career', 'confirm-submit',
1976
+ '--job-id', 'lever:acme-901',
1977
+ '--receipt', 'Application received by Acme Cloud',
1978
+ '--json',
1979
+ ], { cwd: work, home });
1980
+ assert.equal(rConf.status, 0, rConf.stdout + rConf.stderr);
1981
+ assert.equal(JSON.parse(rConf.stdout).status, 'applied');
1982
+
1983
+ // 6. career transition (interview + assessment)
1984
+ const rTrn = runCli([
1985
+ 'career', 'transition',
1986
+ '--job-id', 'lever:acme-901',
1987
+ '--to', 'interview',
1988
+ '--source', 'recruiter_inbox_triage',
1989
+ '--stage', 'technical_screen',
1990
+ '--round', '1',
1991
+ '--notes', 'Recruiter call booked',
1992
+ '--json',
1993
+ ], { cwd: work, home });
1994
+ assert.equal(rTrn.status, 0, rTrn.stdout + rTrn.stderr);
1995
+ assert.equal(JSON.parse(rTrn.stdout).to_status, 'interview');
1996
+
1997
+ // 7. career skip
1998
+ const rSkip = runCli([
1999
+ 'career', 'skip',
2000
+ '--job-id', 'gh:ghost-404',
2001
+ '--reason', 'ghost_or_expired',
2002
+ '--skip-reason', 'Listing shows closed banner',
2003
+ '--company', 'GhostCo',
2004
+ '--title', 'Old Eng',
2005
+ '--json',
2006
+ ], { cwd: work, home });
2007
+ assert.equal(rSkip.status, 0, rSkip.stdout + rSkip.stderr);
2008
+ assert.equal(JSON.parse(rSkip.stdout).action, 'created');
2009
+
2010
+ // 8. career lock-status, summary, analytics, status --json
2011
+ const rLock = runCli(['career', 'lock-status', '--json'], { cwd: work, home });
2012
+ assert.equal(rLock.status, 0, rLock.stdout + rLock.stderr);
2013
+ assert.equal(JSON.parse(rLock.stdout).lock.locked, false);
2014
+ assert.equal(JSON.parse(rLock.stdout).transaction.pending, false);
2015
+
2016
+ const rSum = runCli(['career', 'summary', '--json'], { cwd: work, home });
2017
+ assert.equal(rSum.status, 0, rSum.stdout + rSum.stderr);
2018
+ assert.equal(JSON.parse(rSum.stdout).funnel.submitted_count, 1);
2019
+ assert.equal(JSON.parse(rSum.stdout).active_interviews, 1);
2020
+
2021
+ const rSt = runCli(['status', '--json'], { cwd: work, home });
2022
+ assert.equal(rSt.status, 0, rSt.stdout + rSt.stderr);
2023
+ const stJson = JSON.parse(rSt.stdout);
2024
+ assert.equal(stJson.pipeline.applied, 1);
2025
+ assert.equal(stJson.pipeline.interviewing, 1);
2026
+ assert.equal(stJson.pipeline.silent_14d, 0);
2027
+
2028
+ // 9. Unknown flags, missing required args & invalid transitions fail non-zero cleanly
2029
+ for (const badCmd of [
2030
+ ['career', 'record'],
2031
+ ['career', 'record', '--job-id', 'x:1', '--unknown-flag', 'val'],
2032
+ ['career', 'confirm-submit', '--job-id', 'lever:acme-901'],
2033
+ ['career', 'transition', '--job-id', 'lever:acme-901', '--to', 'invalid_status'],
2034
+ ['career', 'skip', '--job-id', 'x:2'],
2035
+ ['career', 'cv-register', '--id', 'only-id'],
2036
+ ['pre-submit', '--bogus-flag'],
2037
+ ]) {
2038
+ const bad = runCli(badCmd, { cwd: work, home });
2039
+ assert.notEqual(bad.status, 0, `Expected non-zero exit for: ${badCmd.join(' ')}`);
2040
+ }
2041
+
2042
+ // 10. Verify logs/sync-state.json was NEVER created or mutated by T11 ledger writes
2043
+ assert.equal(fs.existsSync(path.join(work, 'logs', 'sync-state.json')), false);
2044
+ } finally {
2045
+ fs.rmSync(dir, { recursive: true, force: true });
2046
+ }
2047
+ });
2048
+
2049
+ test('13. Stage 6 (T12.1): Run ledger & session checkpoint state machine, ledger-derived counts, 3-error auto-abort, and resume reconciliation', () => {
2050
+ const { dir, home, work } = makeTempWorkspace('veycraft-t12-run-cp-');
2051
+ const runId = '2026-11-23';
2052
+ const t0 = `${runId}T09:00:00Z`;
2053
+ const t1 = `${runId}T09:15:00Z`;
2054
+ const t2 = `${runId}T09:30:00Z`;
2055
+ const t3 = `${runId}T09:45:00Z`;
2056
+
2057
+ try {
2058
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2059
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2060
+
2061
+ // 13a. validateSessionCheckpoint enforces schema, submission_authorized === false, and secret token checks
2062
+ assert.ok(RUN_PHASES.includes('applying') && WORKFLOW_MODES.includes('batch_review_first'));
2063
+ const badCp = validateSessionCheckpoint({
2064
+ kind: 'session_checkpoint',
2065
+ version: 1,
2066
+ run_id: runId,
2067
+ updated_at: t0,
2068
+ phase: 'applying',
2069
+ workflow_mode: 'batch_review_first',
2070
+ dry_run: true,
2071
+ approval_mode: 'approve_before_submit',
2072
+ submission_authorized: true,
2073
+ caps: { effective_daily_cap: 5, applied_today: 0, reserved_unresolved: 0, per_platform_applied: {} },
2074
+ processed_job_ids: ['gh:dup-1'],
2075
+ queue: ['gh:dup-1'],
2076
+ awaiting_owner: [{ job_id: 'gh:q1', question: `Token ${['sk', '1234567890abcdef123456'].join('-')}` }],
2077
+ batch_selection: null,
2078
+ consecutive_errors: 0,
2079
+ next_action: 'ok',
2080
+ notes: '',
2081
+ });
2082
+ assert.equal(badCp.valid, false);
2083
+ assert.ok(badCp.errors.some(e => /submission_authorized must always be false/i.test(e)));
2084
+ assert.ok(badCp.errors.some(e => /cannot also appear in processed_job_ids/i.test(e)));
2085
+ assert.ok(badCp.errors.some(e => /prohibited credential or token pattern/i.test(e)));
2086
+
2087
+ // 13b. Start daily run and seed ledger records (including third-party record that must be excluded)
2088
+ const started = startOrUpdateDailyRun(work, {
2089
+ run_id: runId,
2090
+ workflow_mode: 'batch_review_first',
2091
+ platforms: ['greenhouse', 'linkedin'],
2092
+ notes: 'Morning run',
2093
+ }, { home, sourceRoot: REPO_ROOT, nowIso: t0 });
2094
+ assert.equal(started.action, 'started');
2095
+ assert.equal(started.run.status, 'running');
2096
+ assert.equal(started.checkpoint.phase, 'readiness');
2097
+ assert.equal(started.checkpoint.submission_authorized, false);
2098
+
2099
+ recordApplication(work, { job_id: 'gh:job-1', company: 'Alpha', title: 'Backend Eng', platform: 'greenhouse', status: 'prepared', match_score: 8.7, run_id: runId }, { home, nowIso: t0, sourceRoot: REPO_ROOT });
2100
+ recordApplication(work, { job_id: 'gh:job-2', company: 'Beta', title: 'Platform Eng', platform: 'greenhouse', status: 'discovered', match_score: 8.2, run_id: runId }, { home, nowIso: t0, sourceRoot: REPO_ROOT });
2101
+ recordApplication(work, { job_id: 'li:job-dry', company: 'DryCo', title: 'API Eng', platform: 'linkedin', status: 'dry_run', match_score: 8.0, run_id: runId }, { home, nowIso: t0, sourceRoot: REPO_ROOT });
2102
+ recordApplication(work, { job_id: 'li:3p-job', company: 'ThirdParty', title: 'Eng', platform: 'linkedin', status: 'prepared', run_id: runId, third_party_subject: true }, { home, nowIso: t0, sourceRoot: REPO_ROOT });
2103
+ recordSkippedJob(work, { job_id: 'gh:ghost-9', company: 'Ghost', title: 'Old', platform: 'greenhouse', reason: 'ghost_or_expired', skip_reason: 'Closed 60d ago', run_id: runId }, { home, nowIso: t0 });
2104
+
2105
+ // 13c. writeSessionCheckpoint derives counts from ledger and reconciles dry_run out of queue
2106
+ const cp1 = writeSessionCheckpoint(work, {
2107
+ run_id: runId,
2108
+ phase: 'applying',
2109
+ queue: ['gh:job-1', 'gh:job-2', 'li:job-dry'],
2110
+ batch_selection: 'APPLY 1,2',
2111
+ awaiting_job_id: 'gh:job-2',
2112
+ awaiting_question: 'Notice period in weeks?',
2113
+ }, { home, sourceRoot: REPO_ROOT, nowIso: t1 });
2114
+ assert.equal(cp1.checkpointed, true);
2115
+ assert.deepEqual(cp1.checkpoint.queue, ['gh:job-1', 'gh:job-2'], 'li:job-dry is already handled in ledger and moved out of queue');
2116
+ assert.ok(cp1.checkpoint.processed_job_ids.includes('li:job-dry'));
2117
+ assert.equal(cp1.run.counts.scanned, 4, '3 owner apps + 1 skipped job (3P excluded)');
2118
+ assert.equal(cp1.run.counts.prepared, 1);
2119
+ assert.equal(cp1.run.counts.dry_run, 1);
2120
+ assert.equal(cp1.run.counts.skipped, 1);
2121
+ assert.equal(cp1.run.counts.applied, 0);
2122
+
2123
+ // 13d. Reserve and confirm gh:job-1 out-of-band, then test resumeSessionCheckpoint: ledger wins & expires prior approval!
2124
+ reserveApplicationSubmission(work, { job_id: 'gh:job-1', company: 'Alpha', title: 'Backend Eng', platform: 'greenhouse' }, { home, nowIso: t2, sourceRoot: REPO_ROOT });
2125
+ // While gh:job-1 has unresolved submission_uncertain=true, attempting to advance checkpoint to "logging" or finish as "completed" MUST fail closed!
2126
+ assert.throws(
2127
+ () => writeSessionCheckpoint(work, { run_id: runId, phase: 'logging' }, { home, sourceRoot: REPO_ROOT, nowIso: t2 }),
2128
+ /unresolved_submission_uncertain/i,
2129
+ );
2130
+ assert.throws(
2131
+ () => finishDailyRun(work, { run_id: runId, status: 'completed' }, { home, sourceRoot: REPO_ROOT, nowIso: t2 }),
2132
+ /unresolved_submission_uncertain/i,
2133
+ );
2134
+
2135
+ // Confirm submission receipt for gh:job-1
2136
+ confirmApplicationSubmission(work, { job_id: 'gh:job-1', receipt: 'Application submitted to Alpha' }, { home, nowIso: t2 });
2137
+
2138
+ // Resume checkpoint: gh:job-1 must be removed from queue -> processed_job_ids, caps updated to applied_today=1, approval_expired_on_resume=true
2139
+ const resumed = resumeSessionCheckpoint(work, { run_id: runId }, { home, sourceRoot: REPO_ROOT, nowIso: t3 });
2140
+ assert.equal(resumed.resumed, true);
2141
+ assert.equal(resumed.approval_expired_on_resume, true);
2142
+ assert.equal(resumed.submission_authorized, false);
2143
+ assert.equal(resumed.discrepancies_reconciled, true);
2144
+ assert.deepEqual(resumed.moved_to_processed, ['gh:job-1']);
2145
+ assert.deepEqual(resumed.checkpoint.queue, ['gh:job-2']);
2146
+ assert.equal(resumed.checkpoint.caps.applied_today, 1);
2147
+ assert.equal(resumed.run.counts.applied, 1);
2148
+
2149
+ // 13e. Finish daily run cleanly -> status=completed, phase=finished, queue=[], and refusing subsequent resume
2150
+ const finished = finishDailyRun(work, { run_id: runId, status: 'completed', notes: 'Completed batch' }, { home, sourceRoot: REPO_ROOT, nowIso: t3 });
2151
+ assert.equal(finished.status, 'completed');
2152
+ assert.equal(finished.phase, 'finished');
2153
+ assert.deepEqual(finished.checkpoint.queue, []);
2154
+ assert.throws(
2155
+ () => resumeSessionCheckpoint(work, { run_id: runId }, { home, sourceRoot: REPO_ROOT, nowIso: t3 }),
2156
+ /cannot_resume_closed_run/i,
2157
+ );
2158
+
2159
+ // 13f. 3 consecutive errors MUST auto-abort an active run fail-closed
2160
+ const runId2 = '2026-11-24';
2161
+ startOrUpdateDailyRun(work, { run_id: runId2 }, { home, sourceRoot: REPO_ROOT, nowIso: `${runId2}T10:00:00Z` });
2162
+ const abortedCp = writeSessionCheckpoint(work, {
2163
+ run_id: runId2,
2164
+ phase: 'applying',
2165
+ consecutive_errors: 3,
2166
+ }, { home, sourceRoot: REPO_ROOT, nowIso: `${runId2}T10:10:00Z` });
2167
+ assert.equal(abortedCp.auto_aborted, true);
2168
+ assert.equal(abortedCp.phase, 'aborted');
2169
+ assert.equal(abortedCp.run_status, 'aborted');
2170
+ assert.ok(abortedCp.run.errors.some(e => /consecutive_errors=3/i.test(e)));
2171
+ } finally {
2172
+ fs.rmSync(dir, { recursive: true, force: true });
2173
+ }
2174
+ });
2175
+
2176
+ test('14. Stage 6 (T12.2): Deterministic job triage (Tier A/B/C, ghost/blacklist/dealbreaker) & Mission Control queue two-stage approval boundary', () => {
2177
+ const { dir, home, work } = makeTempWorkspace('veycraft-t12-triage-');
2178
+ const runId = '2026-11-23';
2179
+ const nowIso = `${runId}T10:00:00Z`;
2180
+
2181
+ try {
2182
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2183
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
2184
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2185
+ fs.writeFileSync(
2186
+ path.join(work, 'context', 'preferences.yaml'),
2187
+ [
2188
+ 'min_match_score: 7.5',
2189
+ 'active_persona: "backend-architect"',
2190
+ 'exclude_keywords: ["Intern", "Unpaid"]',
2191
+ 'blacklisted_companies: ["BadVendor Corp"]',
2192
+ 'blacklisted_domains: ["spamboard.example"]',
2193
+ ].join('\n') + '\n',
2194
+ );
2195
+
2196
+ const prefs = readWorkspaceTargetingPreferences(work, { home });
2197
+ assert.equal(prefs.min_match_score, 7.5);
2198
+ assert.equal(prefs.active_persona, 'backend-architect');
2199
+ assert.deepEqual(prefs.exclude_keywords, ['intern', 'unpaid']);
2200
+
2201
+ startOrUpdateDailyRun(work, { run_id: runId }, { home, sourceRoot: REPO_ROOT, nowIso });
2202
+
2203
+ // 14a. Tier A role (score >= 8.0 and >= min_match_score)
2204
+ const tierA = triageJobForWorkflow(work, {
2205
+ job_id: 'gh:tier-a-1',
2206
+ company: 'NovaPay',
2207
+ title: 'Senior Backend Engineer',
2208
+ platform: 'greenhouse',
2209
+ url: 'https://boards.greenhouse.io/novapay/jobs/101',
2210
+ match_score: 8.8,
2211
+ matched_skills: ['Node.js', 'PostgreSQL'],
2212
+ missing_skills: ['Go'],
2213
+ run_id: runId,
2214
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2215
+ assert.equal(tierA.tier, 'A');
2216
+ assert.equal(tierA.status, 'discovered');
2217
+ assert.equal(tierA.eligible_for_queue, true);
2218
+ assert.equal(tierA.tailoring_needed, true);
2219
+ assert.equal(tierA.record.persona_id, 'backend-architect');
2220
+
2221
+ // 14b. Tier B role below min_match_score (score 6.5 < 7.5 -> needs_review, still eligible if owner selects)
2222
+ const tierB = triageJobForWorkflow(work, {
2223
+ job_id: 'gh:tier-b-2',
2224
+ company: 'OrbitCloud',
2225
+ title: 'Platform Engineer',
2226
+ platform: 'greenhouse',
2227
+ url: 'https://boards.greenhouse.io/orbit/jobs/102',
2228
+ match_score: 6.5,
2229
+ matched_skills: ['Docker'],
2230
+ missing_skills: ['Kubernetes'],
2231
+ run_id: runId,
2232
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2233
+ assert.equal(tierB.tier, 'B');
2234
+ assert.equal(tierB.status, 'needs_review');
2235
+ assert.equal(tierB.disposition, 'stretch_needs_review');
2236
+ assert.equal(tierB.eligible_for_queue, true);
2237
+
2238
+ // 14c. Tier C roles (ghost, blacklisted, excluded keyword, score < 5) recorded atomically in both skipped-jobs.json & applications-log.json
2239
+ const tierCGhost = triageJobForWorkflow(work, {
2240
+ job_id: 'gh:tier-c-ghost',
2241
+ company: 'OldCo',
2242
+ title: 'Backend Engineer',
2243
+ platform: 'greenhouse',
2244
+ match_score: 8.5,
2245
+ ghost_or_expired: true,
2246
+ notes: 'Job closed banner visible',
2247
+ run_id: runId,
2248
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2249
+ assert.equal(tierCGhost.tier, 'C');
2250
+ assert.equal(tierCGhost.status, 'skipped');
2251
+ assert.equal(tierCGhost.skip_reason_code, 'ghost_or_expired');
2252
+ assert.equal(tierCGhost.eligible_for_queue, false);
2253
+
2254
+ const tierCBlack = triageJobForWorkflow(work, {
2255
+ job_id: 'li:tier-c-bl',
2256
+ company: 'BadVendor Corp Global',
2257
+ title: 'Backend Engineer',
2258
+ platform: 'linkedin',
2259
+ match_score: 9.0,
2260
+ run_id: runId,
2261
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2262
+ assert.equal(tierCBlack.tier, 'C');
2263
+ assert.equal(tierCBlack.skip_reason_code, 'blacklisted_employer');
2264
+
2265
+ const tierCLow = triageJobForWorkflow(work, {
2266
+ job_id: 'li:tier-c-low',
2267
+ company: 'MismatchCo',
2268
+ title: 'iOS Swift Engineer',
2269
+ platform: 'linkedin',
2270
+ match_score: 3.2,
2271
+ run_id: runId,
2272
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2273
+ assert.equal(tierCLow.tier, 'C');
2274
+ assert.equal(tierCLow.skip_reason_code, 'mismatch');
2275
+
2276
+ const skippedLedger = readValidatedSkippedJobs(work, { home }).records;
2277
+ assert.equal(skippedLedger.length, 3);
2278
+
2279
+ // 14d. enqueueSelectedRunJobs enforces Boundary 1: accepts Tier A/B, rejects Tier C, skipped, submitted, uncertain, third-party, and keeps submission_authorized=false
2280
+ assert.throws(
2281
+ () => enqueueSelectedRunJobs(work, { run_id: runId, job_ids: ['gh:tier-a-1', 'gh:tier-c-ghost'] }, { home, sourceRoot: REPO_ROOT, nowIso }),
2282
+ /ineligible_job_status/i,
2283
+ );
2284
+ assert.throws(
2285
+ () => enqueueSelectedRunJobs(work, { run_id: runId, job_ids: ['gh:unknown-job'] }, { home, sourceRoot: REPO_ROOT, nowIso }),
2286
+ /job_not_found_in_ledger/i,
2287
+ );
2288
+ recordApplication(work, { job_id: 'li:3p-isolated', company: '3P', title: 'Eng', status: 'discovered', third_party_subject: true }, { home, nowIso, sourceRoot: REPO_ROOT });
2289
+ assert.throws(
2290
+ () => enqueueSelectedRunJobs(work, { run_id: runId, job_ids: ['li:3p-isolated'] }, { home, sourceRoot: REPO_ROOT, nowIso }),
2291
+ /third_party_blocked/i,
2292
+ );
2293
+
2294
+ const enq = enqueueSelectedRunJobs(work, {
2295
+ run_id: runId,
2296
+ job_ids: ['gh:tier-a-1', 'gh:tier-b-2'],
2297
+ batch_selection: 'APPLY 1,2',
2298
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2299
+ assert.equal(enq.enqueued, true);
2300
+ assert.equal(enq.submission_authorized, false, 'Batch selection must NEVER authorize final submission');
2301
+ assert.deepEqual(enq.queue, ['gh:tier-a-1', 'gh:tier-b-2']);
2302
+ assert.equal(enq.checkpoint.phase, 'applying');
2303
+ assert.equal(enq.checkpoint.submission_authorized, false);
2304
+
2305
+ // Verify neither job was marked applied or reserved by enqueueing
2306
+ const appsAfterEnq = readValidatedApplicationsLedger(work, { home }).records;
2307
+ for (const id of ['gh:tier-a-1', 'gh:tier-b-2']) {
2308
+ const rec = appsAfterEnq.find(r => r.job_id === id);
2309
+ assert.notEqual(rec.status, 'applied');
2310
+ assert.equal(rec.submission_uncertain, false);
2311
+ }
2312
+ } finally {
2313
+ fs.rmSync(dir, { recursive: true, force: true });
2314
+ }
2315
+ });
2316
+
2317
+ test('15. Stage 6 (T12.3): Context-aware owner CV selection, cv-* folder collision guard, third-party exclusion & preparation package verification', () => {
2318
+ const { dir, home, work } = makeTempWorkspace('veycraft-t12-prep-');
2319
+ const nowIso = '2026-11-23T11:00:00Z';
2320
+
2321
+ try {
2322
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2323
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
2324
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2325
+ fs.writeFileSync(path.join(work, 'context', 'preferences.yaml'), 'active_persona: "ai-engineer"\n');
2326
+
2327
+ // 15a. computeCanonicalResumeFolderRel prevents owner company "CV" from colliding with reserved logs/resumes/cv-<slug>/
2328
+ const safeRel = computeCanonicalResumeFolderRel('CV Partners', 'Backend Engineer', 'gh:101');
2329
+ assert.match(safeRel, /^logs\/resumes\/job-cv-partners-/);
2330
+ assert.equal( safeRel.startsWith('logs/resumes/cv-'), false );
2331
+
2332
+ // 15b. Register owner CVs + seed a third-party entry in cv-versions.json to verify strict exclusion
2333
+ const genericHtml = path.join(work, 'logs', 'resumes', 'base-generic', 'resume.html');
2334
+ const aiHtml = path.join(work, 'logs', 'resumes', 'base-ai', 'resume.html');
2335
+ const jobTailoredHtml = path.join(work, 'logs', 'resumes', 'novapay-senior-ai-engineer-gh-201', 'resume.html');
2336
+ for (const f of [genericHtml, aiHtml, jobTailoredHtml]) {
2337
+ fs.mkdirSync(path.dirname(f), { recursive: true });
2338
+ fs.writeFileSync(f, '<!doctype html><html><head><title>Synthetic Candidate</title></head><body><h1>Synthetic Candidate</h1><p>Built Node.js and TypeScript distributed systems.</p><ul><li>Shipped API gateway handling 1200 requests per second.</li></ul></body></html>');
2339
+ }
2340
+
2341
+ registerOwnerCvVersionForWorkspace(work, {
2342
+ cv_version_id: 'cv-owner-generic-v1',
2343
+ label: 'Generic Fullstack Resume',
2344
+ kind: 'generic',
2345
+ file: 'logs/resumes/base-generic/resume.html',
2346
+ persona_id: 'fullstack',
2347
+ language: 'en',
2348
+ hygiene_score: 88,
2349
+ }, { home, nowIso });
2350
+
2351
+ registerOwnerCvVersionForWorkspace(work, {
2352
+ cv_version_id: 'cv-owner-ai-v2',
2353
+ label: 'AI Engineer Persona Resume',
2354
+ kind: 'generic',
2355
+ file: 'logs/resumes/base-ai/resume.html',
2356
+ version_number: 2,
2357
+ persona_id: 'ai-engineer',
2358
+ language: 'en',
2359
+ target_role: 'Senior AI Engineer',
2360
+ emphasized_skills: ['TypeScript', 'Node.js', 'LLM'],
2361
+ hygiene_score: 95,
2362
+ }, { home, nowIso });
2363
+
2364
+ // Inject an isolated third-party CV version directly into cv-versions.json to prove selectBestOwnerCvVersion & prepareApplicationPackage never select or link it
2365
+ const cvRegLoaded = readValidatedCvRegistry(work, { home });
2366
+ cvRegLoaded.registry.versions.push({
2367
+ cv_version_id: 'cv-third-party-friend',
2368
+ version_number: 99,
2369
+ label: 'Friend Senior AI Engineer CV',
2370
+ kind: 'tailored',
2371
+ owner_scope: 'third_party',
2372
+ base_cv_version_id: null,
2373
+ content_sha256: null,
2374
+ persona_id: 'ai-engineer',
2375
+ language: 'en',
2376
+ created_at: nowIso,
2377
+ updated_at: nowIso,
2378
+ local_ref_rel: 'logs/resumes/cv-friend-john/resume.html',
2379
+ tailoring_metadata: { target_job_id: 'gh:201-tp-sel', target_role: 'Senior AI Engineer', emphasized_skills: ['TypeScript', 'Node.js', 'LLM'] },
2380
+ ats_metrics: { keyword_match_before_pct: 90, keyword_match_after_pct: 99, hygiene_score: 100, page_count: 1 },
2381
+ application_ids: [],
2382
+ });
2383
+ fs.writeFileSync(cvRegLoaded.path, JSON.stringify(cvRegLoaded.registry, null, 2));
2384
+
2385
+ // Select for gh:201-tp-sel before job-specific CV is registered: must pick cv-owner-ai-v2 (never cv-third-party-friend even with exact target_job_id match!)
2386
+ const sel1 = selectBestOwnerCvVersion(work, {
2387
+ job_id: 'gh:201-tp-sel',
2388
+ title: 'Senior AI Engineer',
2389
+ matched_skills: ['TypeScript', 'Node.js'],
2390
+ missing_skills: ['Rust'],
2391
+ match_score: 8.9,
2392
+ }, { home });
2393
+ assert.equal(sel1.selected_cv_version_id, 'cv-owner-ai-v2');
2394
+ assert.equal(sel1.third_party_excluded, 1);
2395
+ assert.equal(sel1.tailoring_recommended, true);
2396
+
2397
+ // 15c. Triage gh:201 and test prepareApplicationPackage failure on missing/bad artifacts (placeholders, AI cliché, em-dash, >75w outreach)
2398
+ triageJobForWorkflow(work, {
2399
+ job_id: 'gh:201',
2400
+ company: 'NovaPay',
2401
+ title: 'Senior AI Engineer',
2402
+ platform: 'greenhouse',
2403
+ match_score: 8.9,
2404
+ matched_skills: ['TypeScript', 'Node.js'],
2405
+ }, { home, sourceRoot: REPO_ROOT, nowIso });
2406
+
2407
+ const jobFolder = path.dirname(jobTailoredHtml);
2408
+ // Missing tailoring-notes.md -> must fail when require_ready=true
2409
+ assert.throws(
2410
+ () => prepareApplicationPackage(work, { job_id: 'gh:201' }, { home, nowIso }),
2411
+ /missing tailoring-notes\.md/i,
2412
+ );
2413
+
2414
+ // Write tailoring-notes.md, but inject a {{PLACEHOLDER}}, banned cliché, and prose em-dash into resume.txt & outreach-draft.md
2415
+ fs.writeFileSync(path.join(jobFolder, 'tailoring-notes.md'), '# Tailoring Notes\n- Emphasized Node.js — verified.\n');
2416
+ fs.writeFileSync(path.join(jobFolder, 'resume.txt'), 'Synthetic Candidate\nSpearheaded synergy — {{UNRESOLVED_TOKEN}}\n');
2417
+ fs.writeFileSync(path.join(jobFolder, 'outreach-draft.md'), Array(80).fill('word').join(' '));
2418
+
2419
+ assert.throws(
2420
+ () => prepareApplicationPackage(work, { job_id: 'gh:201' }, { home, nowIso }),
2421
+ /unresolved template placeholder|banned AI cliché|prose em-dash|outreach word cap exceeded/i,
2422
+ );
2423
+
2424
+ // Refuses linking third-party CV version
2425
+ assert.throws(
2426
+ () => prepareApplicationPackage(work, { job_id: 'gh:201', cv_version_id: 'cv-third-party-friend', require_ready: false }, { home, nowIso }),
2427
+ /third_party_blocked/i,
2428
+ );
2429
+
2430
+ // Clean artifacts -> prepareApplicationPackage succeeds, transitions to status="prepared", links cv_version_id & cv_tailoring
2431
+ fs.writeFileSync(path.join(jobFolder, 'resume.txt'), 'Synthetic Candidate\nBuilt Node.js and TypeScript distributed systems.\n');
2432
+ fs.writeFileSync(path.join(jobFolder, 'outreach-draft.md'), 'Hi NovaPay team, I applied for the Senior AI Engineer role and built high-throughput Node.js and TypeScript services.');
2433
+
2434
+ registerOwnerCvVersionForWorkspace(work, {
2435
+ cv_version_id: 'cv-novapay-201',
2436
+ label: 'NovaPay Tailored AI Resume',
2437
+ kind: 'tailored',
2438
+ file: 'logs/resumes/novapay-senior-ai-engineer-gh-201/resume.html',
2439
+ base_cv_version_id: 'cv-owner-ai-v2',
2440
+ persona_id: 'ai-engineer',
2441
+ target_role: 'Senior AI Engineer',
2442
+ target_job_id: 'gh:201',
2443
+ ats_keyword_before_pct: 68,
2444
+ ats_keyword_after_pct: 94,
2445
+ }, { home, nowIso });
2446
+
2447
+ const prep = prepareApplicationPackage(work, {
2448
+ job_id: 'gh:201',
2449
+ ats_keyword_before_pct: 68,
2450
+ ats_keyword_after_pct: 94,
2451
+ }, { home, nowIso });
2452
+ assert.equal(prep.prepared, true);
2453
+ assert.equal(prep.submission_authorized, false);
2454
+ assert.equal(prep.status, 'prepared');
2455
+ assert.equal(prep.cv_version_id, 'cv-novapay-201');
2456
+ assert.equal(prep.cv_tailoring.is_tailored, true);
2457
+ assert.equal(prep.cv_tailoring.base_cv_version_id, 'cv-owner-ai-v2');
2458
+ assert.equal(prep.cv_tailoring.ats_keyword_after_pct, 94);
2459
+ assert.equal(prep.cv_tailoring.tailored_folder_rel, 'logs/resumes/novapay-senior-ai-engineer-gh-201');
2460
+ } finally {
2461
+ fs.rmSync(dir, { recursive: true, force: true });
2462
+ }
2463
+ });
2464
+
2465
+ test('16. Stage 6 (T12.4): Read-only workflow & post-application action queue planner (blockers, prep queue, 7d follow-ups, interviews/assessments, 14d silence != rejection)', () => {
2466
+ const { dir, home, work } = makeTempWorkspace('veycraft-t12-next-');
2467
+ const nowIso = '2026-11-23T12:00:00Z';
2468
+
2469
+ try {
2470
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2471
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2472
+
2473
+ // Empty workspace works safely and read-only
2474
+ const emptyPlan = computeCareerWorkflowQueue(work, { home, sourceRoot: REPO_ROOT, nowIso });
2475
+ assert.equal(emptyPlan.read_only, true);
2476
+ assert.equal(emptyPlan.blockers.length, 0);
2477
+
2478
+ // Seed:
2479
+ // 1) An unresolved submission_uncertain reservation (P0_BLOCKER)
2480
+ // 2) A prepared role in active run queue (P1_ACTIVE_RUN)
2481
+ // 3) An applied role 9 days old needing 7d follow-up (P3_POST_APPLY)
2482
+ // 4) An applied role 18 days old with zero reply (silent_14d — never rejected!)
2483
+ // 5) An interview role + assessment role (P3_POST_APPLY)
2484
+ // 6) An isolated third-party role (must be excluded)
2485
+ recordApplication(work, { job_id: 'gh:prep-1', company: 'PrepCo', title: 'Backend Eng', platform: 'greenhouse', status: 'prepared', match_score: 9.1 }, { home, nowIso, sourceRoot: REPO_ROOT });
2486
+ recordApplication(work, { job_id: 'gh:uncertain-1', company: 'UncertainCo', title: 'API Eng', platform: 'greenhouse', status: 'discovered', match_score: 8.4 }, { home, nowIso, sourceRoot: REPO_ROOT });
2487
+ reserveApplicationSubmission(work, { job_id: 'gh:uncertain-1', company: 'UncertainCo', title: 'API Eng', platform: 'greenhouse' }, { home, nowIso, sourceRoot: REPO_ROOT });
2488
+
2489
+ // Applied 9 days ago (overdue 7d follow-up)
2490
+ recordApplication(work, { job_id: 'li:fu-9d', company: 'FollowCo', title: 'Fullstack Eng', platform: 'linkedin', status: 'prepared', match_score: 8.5, discovered_at: '2026-11-14T09:00:00Z' }, { home, nowIso: '2026-11-14T09:00:00Z', sourceRoot: REPO_ROOT });
2491
+ confirmApplicationSubmission(work, { job_id: 'li:fu-9d', receipt: 'Submitted to FollowCo', applied_at: '2026-11-14T10:00:00Z' }, { home, nowIso: '2026-11-14T10:00:00Z' });
2492
+
2493
+ // Applied 18 days ago (silent >=14d AND overdue follow-up, never classified as rejected)
2494
+ recordApplication(work, { job_id: 'li:silent-18d', company: 'SilentCo', title: 'Platform Eng', platform: 'linkedin', status: 'prepared', match_score: 8.2, discovered_at: '2026-11-05T09:00:00Z' }, { home, nowIso: '2026-11-05T09:00:00Z', sourceRoot: REPO_ROOT });
2495
+ confirmApplicationSubmission(work, { job_id: 'li:silent-18d', receipt: 'Submitted to SilentCo', applied_at: '2026-11-05T10:00:00Z' }, { home, nowIso: '2026-11-05T10:00:00Z' });
2496
+
2497
+ // Active interview & assessment
2498
+ recordApplication(work, { job_id: 'lv:iv-1', company: 'InterviewCo', title: 'Staff Eng', platform: 'lever', status: 'prepared', match_score: 9.3, discovered_at: '2026-11-10T09:00:00Z' }, { home, nowIso: '2026-11-10T09:00:00Z', sourceRoot: REPO_ROOT });
2499
+ confirmApplicationSubmission(work, { job_id: 'lv:iv-1', receipt: 'Submitted to InterviewCo', applied_at: '2026-11-10T10:00:00Z' }, { home, nowIso: '2026-11-10T10:00:00Z' });
2500
+ transitionApplicationStage(work, {
2501
+ job_id: 'lv:iv-1',
2502
+ to_status: 'interview',
2503
+ source: 'recruiter_inbox_triage',
2504
+ at: '2026-11-15T10:00:00Z',
2505
+ interview: { round: 1, stage: 'technical_screen', status: 'scheduled', scheduled_at: '2026-11-25T15:00:00Z' },
2506
+ }, { home, nowIso: '2026-11-15T10:00:00Z' });
2507
+
2508
+ // Isolated third-party record
2509
+ recordApplication(work, { job_id: 'li:3p-ignored', company: 'ThirdParty', title: 'Eng', status: 'prepared', match_score: 9.9, third_party_subject: true }, { home, nowIso, sourceRoot: REPO_ROOT });
2510
+
2511
+ const ledgerHashBefore = sha256File(path.join(work, 'logs', 'applications-log.json'));
2512
+ const plan = computeCareerWorkflowQueue(work, { home, sourceRoot: REPO_ROOT, nowIso });
2513
+ const ledgerHashAfter = sha256File(path.join(work, 'logs', 'applications-log.json'));
2514
+ assert.equal(ledgerHashAfter, ledgerHashBefore, 'computeCareerWorkflowQueue must be strictly read-only');
2515
+
2516
+ assert.equal(plan.third_party_excluded, 1);
2517
+ assert.ok(plan.blockers.some(b => b.code === 'unresolved_submission_uncertain' && b.job_id === 'gh:uncertain-1'));
2518
+ assert.equal(plan.next_actions[0].priority, 'P0_BLOCKER');
2519
+ assert.equal(plan.next_actions[0].code, 'unresolved_submission_uncertain');
2520
+ assert.equal(plan.preparation_queue.length, 1);
2521
+ assert.equal(plan.preparation_queue[0].job_id, 'gh:prep-1');
2522
+ assert.equal(plan.post_application.overdue_follow_ups.length, 2);
2523
+ assert.equal(plan.post_application.active_interviews.length, 1);
2524
+ assert.equal(plan.post_application.silent_14d_hygiene.length, 1);
2525
+ assert.equal(plan.post_application.silent_14d_hygiene[0].job_id, 'li:silent-18d');
2526
+ assert.equal(plan.post_application.silent_14d_hygiene[0].classification, 'silent_14d');
2527
+ } finally {
2528
+ fs.rmSync(dir, { recursive: true, force: true });
2529
+ }
2530
+ });
2531
+
2532
+ test('17. Stage 6 (T12.5): End-to-end CLI workflow (run-start -> run-triage -> run-enqueue -> cv-register -> prepare -> run-checkpoint -> run-resume -> next -> run-finish -> verify checkpoint)', () => {
2533
+ const { dir, home, work } = makeTempWorkspace('veycraft-t12-cli-e2e-');
2534
+ const runId = '2026-11-23';
2535
+
2536
+ try {
2537
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2538
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
2539
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2540
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
2541
+ fs.writeFileSync(path.join(work, 'context', 'preferences.yaml'), 'min_match_score: 7\nactive_persona: "backend"\n');
2542
+
2543
+ // 1. run-start
2544
+ const rStart = runCli(['career', 'run-start', '--run-id', runId, '--platforms', 'greenhouse,lever', '--json'], { cwd: work, home });
2545
+ assert.equal(rStart.status, 0, rStart.stdout + rStart.stderr);
2546
+ assert.equal(JSON.parse(rStart.stdout).run_id, runId);
2547
+
2548
+ // 2. run-triage (Tier A, Tier B, Tier C ghost)
2549
+ const rTrA = runCli([
2550
+ 'career', 'run-triage',
2551
+ '--job-id', 'gh:nova-501',
2552
+ '--company', 'Nova Systems',
2553
+ '--title', 'Senior Backend Engineer',
2554
+ '--platform', 'greenhouse',
2555
+ '--url', 'https://boards.greenhouse.io/nova/jobs/501',
2556
+ '--match-score', '9.0',
2557
+ '--matched-skills', 'Node.js,PostgreSQL',
2558
+ '--run-id', runId,
2559
+ '--json',
2560
+ ], { cwd: work, home });
2561
+ assert.equal(rTrA.status, 0, rTrA.stdout + rTrA.stderr);
2562
+ assert.equal(JSON.parse(rTrA.stdout).tier, 'A');
2563
+
2564
+ const rTrB = runCli([
2565
+ 'career', 'run-triage',
2566
+ '--job-id', 'lv:orbit-502',
2567
+ '--company', 'Orbit Labs',
2568
+ '--title', 'Platform Engineer',
2569
+ '--platform', 'lever',
2570
+ '--match-score', '7.2',
2571
+ '--run-id', runId,
2572
+ '--json',
2573
+ ], { cwd: work, home });
2574
+ assert.equal(rTrB.status, 0, rTrB.stderr);
2575
+ assert.equal(JSON.parse(rTrB.stdout).tier, 'B');
2576
+
2577
+ const rTrC = runCli([
2578
+ 'career', 'run-triage',
2579
+ '--job-id', 'gh:ghost-503',
2580
+ '--company', 'Ghost Corp',
2581
+ '--title', 'Legacy Eng',
2582
+ '--platform', 'greenhouse',
2583
+ '--match-score', '8.1',
2584
+ '--ghost',
2585
+ '--run-id', runId,
2586
+ '--json',
2587
+ ], { cwd: work, home });
2588
+ assert.equal(rTrC.status, 0, rTrC.stderr);
2589
+ assert.equal(JSON.parse(rTrC.stdout).tier, 'C');
2590
+
2591
+ // 3. run-enqueue (Tier A + Tier B; verify Tier C is rejected)
2592
+ const rEnqBad = runCli(['career', 'run-enqueue', '--job-ids', 'gh:ghost-503', '--run-id', runId, '--json'], { cwd: work, home });
2593
+ assert.notEqual(rEnqBad.status, 0);
2594
+
2595
+ const rEnq = runCli([
2596
+ 'career', 'run-enqueue',
2597
+ '--job-ids', 'gh:nova-501,lv:orbit-502',
2598
+ '--batch-selection', 'APPLY 1,2',
2599
+ '--run-id', runId,
2600
+ '--json',
2601
+ ], { cwd: work, home });
2602
+ assert.equal(rEnq.status, 0, rEnq.stdout + rEnq.stderr);
2603
+ const enqJ = JSON.parse(rEnq.stdout);
2604
+ assert.equal(enqJ.submission_authorized, false);
2605
+ assert.deepEqual(enqJ.queue, ['gh:nova-501', 'lv:orbit-502']);
2606
+
2607
+ // 4. Scaffold tailored deliverables for gh:nova-501, register CV version, and run `career prepare`
2608
+ const folderRel = computeCanonicalResumeFolderRel('Nova Systems', 'Senior Backend Engineer', 'gh:nova-501');
2609
+ const folderAbs = path.join(work, folderRel);
2610
+ fs.mkdirSync(folderAbs, { recursive: true });
2611
+ fs.writeFileSync(path.join(folderAbs, 'resume.html'), '<!doctype html><html><body><h1>Synthetic Owner</h1><p>Built Node.js and PostgreSQL backends.</p></body></html>');
2612
+ fs.writeFileSync(path.join(folderAbs, 'resume.txt'), 'Synthetic Owner\nBuilt Node.js and PostgreSQL backends.\n');
2613
+ fs.writeFileSync(path.join(folderAbs, 'tailoring-notes.md'), '# Tailoring Notes\n- Highlighted Node.js and PostgreSQL.\n');
2614
+
2615
+ const rCvReg = runCli([
2616
+ 'career', 'cv-register',
2617
+ '--id', 'cv-nova-501',
2618
+ '--label', 'Nova Senior Backend Tailored CV',
2619
+ '--kind', 'tailored',
2620
+ '--file', `${folderRel}/resume.html`,
2621
+ '--persona', 'backend',
2622
+ '--target-role', 'Senior Backend Engineer',
2623
+ '--target-job-id', 'gh:nova-501',
2624
+ '--ats-before', '70',
2625
+ '--ats-after', '95',
2626
+ '--json',
2627
+ ], { cwd: work, home });
2628
+ assert.equal(rCvReg.status, 0, rCvReg.stdout + rCvReg.stderr);
2629
+
2630
+ const rPrep = runCli([
2631
+ 'career', 'prepare',
2632
+ '--job-id', 'gh:nova-501',
2633
+ '--ats-before', '70',
2634
+ '--ats-after', '95',
2635
+ '--json',
2636
+ ], { cwd: work, home });
2637
+ assert.equal(rPrep.status, 0, rPrep.stdout + rPrep.stderr);
2638
+ const prepJ = JSON.parse(rPrep.stdout);
2639
+ assert.equal(prepJ.prepared, true);
2640
+ assert.equal(prepJ.status, 'prepared');
2641
+ assert.equal(prepJ.cv_version_id, 'cv-nova-501');
2642
+
2643
+ // 5. Verify `--json pre-submit` flag-order fix (both `--json pre-submit` and `pre-submit --json` output valid JSON)
2644
+ const rPreLeadingJson = runCli(['--json', 'pre-submit', '--job-id', 'gh:nova-501'], { cwd: work, home });
2645
+ assert.equal(rPreLeadingJson.status, 0, rPreLeadingJson.stdout + rPreLeadingJson.stderr);
2646
+ assert.equal(JSON.parse(rPreLeadingJson.stdout).allowed, true);
2647
+
2648
+ // 6. run-checkpoint, reserve + confirm-submit gh:nova-501, then run-resume
2649
+ const rCp = runCli([
2650
+ 'career', 'run-checkpoint',
2651
+ '--run-id', runId,
2652
+ '--phase', 'applying',
2653
+ '--awaiting-job-id', 'lv:orbit-502',
2654
+ '--awaiting-question', 'Preferred start date?',
2655
+ '--json',
2656
+ ], { cwd: work, home });
2657
+ assert.equal(rCp.status, 0, rCp.stdout + rCp.stderr);
2658
+
2659
+ const rResv = runCli(['career', 'reserve', '--job-id', 'gh:nova-501', '--json'], { cwd: work, home });
2660
+ assert.equal(rResv.status, 0, rResv.stderr);
2661
+ const rConf = runCli(['career', 'confirm-submit', '--job-id', 'gh:nova-501', '--receipt', 'Application received by Nova Systems', '--json'], { cwd: work, home });
2662
+ assert.equal(rConf.status, 0, rConf.stderr);
2663
+
2664
+ const rResume = runCli(['career', 'run-resume', '--run-id', runId, '--json'], { cwd: work, home });
2665
+ assert.equal(rResume.status, 0, rResume.stdout + rResume.stderr);
2666
+ const resumeJ = JSON.parse(rResume.stdout);
2667
+ assert.equal(resumeJ.approval_expired_on_resume, true);
2668
+ assert.equal(resumeJ.submission_authorized, false);
2669
+ assert.deepEqual(resumeJ.moved_to_processed, ['gh:nova-501']);
2670
+ assert.deepEqual(resumeJ.checkpoint.queue, ['lv:orbit-502']);
2671
+
2672
+ // 7. career next (both JSON and text modes)
2673
+ const rNext = runCli(['career', 'next', '--job-id', 'lv:orbit-502', '--json'], { cwd: work, home });
2674
+ assert.equal(rNext.status, 0, rNext.stdout + rNext.stderr);
2675
+ const nextJ = JSON.parse(rNext.stdout);
2676
+ assert.equal(nextJ.read_only, true);
2677
+ assert.equal(nextJ.cap_budget.today_applied, 1);
2678
+ assert.equal(nextJ.awaiting_owner.length, 1);
2679
+
2680
+ const rNextText = runCli(['career', 'next'], { cwd: work, home });
2681
+ assert.equal(rNextText.status, 0, rNextText.stdout + rNextText.stderr);
2682
+ assert.match(rNextText.stdout, /Cap Budget Today:/);
2683
+
2684
+ // 8. run-finish and `veycraft verify logs/runs/current-session-checkpoint.json`
2685
+ const rFin = runCli(['career', 'run-finish', '--run-id', runId, '--status', 'completed', '--json'], { cwd: work, home });
2686
+ assert.equal(rFin.status, 0, rFin.stdout + rFin.stderr);
2687
+ assert.equal(JSON.parse(rFin.stdout).counts.applied, 1);
2688
+ assert.equal(JSON.parse(rFin.stdout).counts.skipped, 1);
2689
+
2690
+ const cpFile = path.join(work, 'logs', 'runs', 'current-session-checkpoint.json');
2691
+ const runFile = path.join(work, 'logs', 'runs', `${runId}.json`);
2692
+ const rVerCp = runCli(['verify', cpFile], { cwd: work, home });
2693
+ assert.equal(rVerCp.status, 0, rVerCp.stdout + rVerCp.stderr);
2694
+ const rVerRun = runCli(['verify', runFile], { cwd: work, home });
2695
+ assert.equal(rVerRun.status, 0, rVerRun.stdout + rVerRun.stderr);
2696
+ } finally {
2697
+ fs.rmSync(dir, { recursive: true, force: true });
2698
+ }
2699
+ });
2700
+
2701
+ test('18. Stage 7 (T13): Regression tests for CV attribution parity, confirm-submit/cv-register guards, object open_questions, BANNED_AI_CLICHES parity, backup runs/*.json & sync input error diagnostics', () => {
2702
+ const { dir, home, work } = makeTempWorkspace('veycraft-t13-reg-');
2703
+ const nowIso = '2026-11-23T14:00:00Z';
2704
+
2705
+ try {
2706
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2707
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
2708
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2709
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
2710
+
2711
+ // Register a generic owner CV and a third-party CV
2712
+ const genericRel = 'context/cv.md';
2713
+ fs.writeFileSync(path.join(work, genericRel), '# Synthetic Owner\nBuilt TypeScript and Node.js systems.\n');
2714
+ registerOwnerCvVersionForWorkspace(work, {
2715
+ cv_version_id: 'cv-generic-owner-v1',
2716
+ label: 'Generic Owner CV',
2717
+ kind: 'generic',
2718
+ file: genericRel,
2719
+ }, { home, nowIso });
2720
+
2721
+ const cvRegPath = path.join(work, 'logs', 'cv-versions.json');
2722
+ const cvRegRaw = JSON.parse(fs.readFileSync(cvRegPath, 'utf8'));
2723
+ cvRegRaw.versions.push({
2724
+ cv_version_id: 'cv-third-party-99',
2725
+ version_number: 1,
2726
+ label: 'Friend CV',
2727
+ kind: 'generic',
2728
+ owner_scope: 'third_party',
2729
+ base_cv_version_id: null,
2730
+ content_sha256: 'a'.repeat(64),
2731
+ persona_id: null,
2732
+ language: 'en',
2733
+ local_ref_rel: 'logs/resumes/cv-friend-99/resume.html',
2734
+ tailoring_metadata: null,
2735
+ ats_metrics: null,
2736
+ application_ids: [],
2737
+ created_at: nowIso,
2738
+ updated_at: nowIso,
2739
+ });
2740
+ fs.writeFileSync(cvRegPath, JSON.stringify(cvRegRaw, null, 2) + '\n');
2741
+
2742
+ // D3: registerOwnerCvVersionForWorkspace must reject third-party base_cv_version_id and self-referencing base_cv_version_id
2743
+ const tFileRel = 'logs/resumes/reg-tailored/resume.html';
2744
+ fs.mkdirSync(path.dirname(path.join(work, tFileRel)), { recursive: true });
2745
+ fs.writeFileSync(path.join(work, tFileRel), '<!doctype html><html><body><h1>Synthetic Owner</h1><p>Node.js</p></body></html>');
2746
+ assert.throws(
2747
+ () => registerOwnerCvVersionForWorkspace(work, {
2748
+ cv_version_id: 'cv-bad-base-tp',
2749
+ label: 'Bad Base TP',
2750
+ kind: 'tailored',
2751
+ file: tFileRel,
2752
+ base_cv_version_id: 'cv-third-party-99',
2753
+ }, { home, nowIso }),
2754
+ /third_party_blocked/i,
2755
+ );
2756
+ assert.throws(
2757
+ () => registerOwnerCvVersionForWorkspace(work, {
2758
+ cv_version_id: 'cv-self-cycle',
2759
+ label: 'Self Cycle',
2760
+ kind: 'tailored',
2761
+ file: tFileRel,
2762
+ base_cv_version_id: 'cv-self-cycle',
2763
+ }, { home, nowIso }),
2764
+ /invalid_base_cv_version/i,
2765
+ );
2766
+
2767
+ // D1: prepareApplicationPackage with ONLY a generic CV registered + tailoring-notes.md must NOT attach generic CV as tailored cv_version_id (records as base_cv_version_id instead)
2768
+ recordApplication(work, {
2769
+ job_id: 'gh:t13-1',
2770
+ company: 'SyncSafe Labs',
2771
+ title: 'Backend Engineer',
2772
+ platform: 'greenhouse',
2773
+ url: 'https://boards.greenhouse.io/syncsafe/jobs/1',
2774
+ status: 'discovered',
2775
+ match_score: 8.8,
2776
+ }, { home, nowIso, sourceRoot: REPO_ROOT });
2777
+ const folderRel = computeCanonicalResumeFolderRel('SyncSafe Labs', 'Backend Engineer', 'gh:t13-1');
2778
+ const folderAbs = path.join(work, folderRel);
2779
+ fs.mkdirSync(folderAbs, { recursive: true });
2780
+ fs.writeFileSync(path.join(folderAbs, 'resume.html'), '<!doctype html><html><body><h1>Synthetic Owner</h1><p>Built reliable APIs.</p></body></html>');
2781
+ fs.writeFileSync(path.join(folderAbs, 'tailoring-notes.md'), '# Notes\n- Emphasized Node.js.\n');
2782
+
2783
+ const prep1 = prepareApplicationPackage(work, { job_id: 'gh:t13-1' }, { home, nowIso });
2784
+ assert.equal(prep1.prepared, true);
2785
+ assert.equal(prep1.cv_version_id, null, 'must not link generic CV directly as tailored cv_version_id');
2786
+ assert.equal(prep1.cv_tailoring.is_tailored, true);
2787
+ assert.equal(prep1.cv_tailoring.base_cv_version_id, 'cv-generic-owner-v1');
2788
+
2789
+ // D1b: explicit base_cv_version_id contradicting root CV must fail closed
2790
+ assert.throws(
2791
+ () => prepareApplicationPackage(work, {
2792
+ job_id: 'gh:t13-1',
2793
+ cv_version_id: 'cv-generic-owner-v1',
2794
+ base_cv_version_id: 'cv-nonexistent-other',
2795
+ }, { home, nowIso }),
2796
+ /base_cv_version_mismatch/i,
2797
+ );
2798
+
2799
+ // D3b: linking a root CV via cv-register --link-job-id must clear any stale base_cv_version_id on the application
2800
+ registerOwnerCvVersionForWorkspace(work, {
2801
+ cv_version_id: 'cv-root-tailored-v1',
2802
+ label: 'Root Tailored CV',
2803
+ kind: 'tailored',
2804
+ file: `${folderRel}/resume.html`,
2805
+ link_job_id: 'gh:t13-1',
2806
+ }, { home, nowIso });
2807
+ const afterLink = readValidatedApplicationsLedger(work, { home }).records.find(r => r.job_id === 'gh:t13-1');
2808
+ assert.equal(afterLink.cv_version_id, 'cv-root-tailored-v1');
2809
+ assert.equal(afterLink.cv_tailoring.base_cv_version_id, null, 'root CV link must not leave stale contradicting base_cv_version_id');
2810
+
2811
+ // D2: confirmApplicationSubmission must reject unregistered or third-party --cv-version-id
2812
+ reserveApplicationSubmission(work, { job_id: 'gh:t13-1', company: 'SyncSafe Labs', title: 'Backend Engineer', platform: 'greenhouse' }, { home, nowIso, sourceRoot: REPO_ROOT });
2813
+ assert.throws(
2814
+ () => confirmApplicationSubmission(work, { job_id: 'gh:t13-1', receipt: 'Submitted ok', cv_version_id: 'cv-does-not-exist' }, { home, nowIso }),
2815
+ /cv_version_not_found/i,
2816
+ );
2817
+ assert.throws(
2818
+ () => confirmApplicationSubmission(work, { job_id: 'gh:t13-1', receipt: 'Submitted ok', cv_version_id: 'cv-third-party-99' }, { home, nowIso }),
2819
+ /third_party_blocked/i,
2820
+ );
2821
+ const confOk = confirmApplicationSubmission(work, {
2822
+ job_id: 'gh:t13-1',
2823
+ receipt: 'Application received by SyncSafe Labs',
2824
+ cv_version_id: 'cv-generic-owner-v1',
2825
+ }, { home, nowIso });
2826
+ assert.equal(confOk.confirmed, true);
2827
+ assert.equal(confOk.record.cv_version_id, 'cv-generic-owner-v1');
2828
+ assert.equal(confOk.record.cv_tailoring.is_tailored, false, 'confirmApplicationSubmission must reconcile cv_tailoring.is_tailored with CV kind');
2829
+
2830
+ // D6: computeCareerWorkflowQueue must surface object-shaped open_questions ({ question, field_type })
2831
+ recordApplication(work, {
2832
+ job_id: 'lv:t13-q1',
2833
+ company: 'QuestionCo',
2834
+ title: 'Staff Engineer',
2835
+ platform: 'lever',
2836
+ status: 'needs_review',
2837
+ match_score: 8.5,
2838
+ open_questions: [{ question: 'Do you hold EU work authorization?', field_type: 'select' }],
2839
+ }, { home, nowIso, sourceRoot: REPO_ROOT });
2840
+ const nextPlan = computeCareerWorkflowQueue(work, { home, sourceRoot: REPO_ROOT, nowIso });
2841
+ assert.ok(
2842
+ nextPlan.awaiting_owner.some(a => a.job_id === 'lv:t13-q1' && a.question === 'Do you hold EU work authorization?'),
2843
+ 'object-shaped open_questions must be surfaced in awaiting_owner',
2844
+ );
2845
+
2846
+ // D4: BANNED_AI_CLICHES parity — cmdAudit catches items beyond index 14 ('proven track record', 'leveraged', 'deeply excited'), and pre-submit blocks banned clichés on --text
2847
+ assert.ok(BANNED_AI_CLICHES.includes('proven track record'));
2848
+ assert.ok(BANNED_AI_CLICHES.includes('dynamic environment'));
2849
+ assert.ok(BANNED_AI_CLICHES.includes('results-driven'));
2850
+ const clichéCv = path.join(work, 'cliche-cv.md');
2851
+ fs.writeFileSync(clichéCv, '# Candidate\n- Leveraged a proven track record in a fast-paced environment and deeply excited to build APIs (50% faster).\n');
2852
+ const rAudit = runCli(['audit', clichéCv], { cwd: work, home });
2853
+ assert.equal(rAudit.status, 0, rAudit.stderr);
2854
+ assert.match(rAudit.stdout, /proven track record|leveraged|deeply excited/i);
2855
+
2856
+ const rPreCliche = runCli(['pre-submit', '--text', 'Hi team, I am thrilled to apply and deeply excited to leverage synergy for your backend team.', '--json'], { cwd: work, home });
2857
+ assert.equal(rPreCliche.status, 1);
2858
+ const preClicheJson = JSON.parse(rPreCliche.stdout);
2859
+ assert.equal(preClicheJson.allowed, false);
2860
+ assert.ok(preClicheJson.violations.some(v => v.code === 'draft_banned_cliches'));
2861
+ assert.ok(preClicheJson.checks.draft.banned_cliches.includes('thrilled to apply'));
2862
+ assert.ok(preClicheJson.checks.draft.banned_cliches.includes('deeply excited'));
2863
+
2864
+ // D7: cmdBackup includes logs/runs/*.json (daily run + session checkpoint)
2865
+ startOrUpdateDailyRun(work, { run_id: '2026-11-23', platforms: ['greenhouse'] }, { home, nowIso });
2866
+ const rBackup = runCli(['backup'], { cwd: work, home });
2867
+ assert.equal(rBackup.status, 0, rBackup.stdout + rBackup.stderr);
2868
+ const backupDirs = fs.readdirSync(path.join(work, 'logs', 'backups')).filter(d => d.startsWith('backup-'));
2869
+ assert.equal(backupDirs.length, 1);
2870
+ const backedUpRun = path.join(work, 'logs', 'backups', backupDirs[0], 'logs', 'runs', '2026-11-23.json');
2871
+ const backedUpCp = path.join(work, 'logs', 'backups', backupDirs[0], 'logs', 'runs', 'current-session-checkpoint.json');
2872
+ assert.equal(fs.existsSync(backedUpRun), true, 'backup must include logs/runs/YYYY-MM-DD.json');
2873
+ assert.equal(fs.existsSync(backedUpCp), true, 'backup must include logs/runs/current-session-checkpoint.json');
2874
+
2875
+ // D5: loadCareerSyncInputs reports the exact corrupt daily run filename on malformed JSON
2876
+ const badRunPath = path.join(work, 'logs', 'runs', '2026-11-24.json');
2877
+ fs.writeFileSync(badRunPath, '{corrupt json');
2878
+ assert.throws(
2879
+ () => loadCareerSyncInputs(work, { home }),
2880
+ /Invalid JSON in daily run file .*2026-11-24\.json/i,
2881
+ );
2882
+ } finally {
2883
+ fs.rmSync(dir, { recursive: true, force: true });
2884
+ }
2885
+ });
2886
+
2887
+ // ===========================================================================
2888
+ // Test 19: SEC-02 — Third-Party CV & Application Data Leakage Prevention
2889
+ // ===========================================================================
2890
+ test('19. SEC-02: centralized third-party CV and application ownership isolation prevents leakage across analytics, summary, dashboard, next queue, status metrics, and Notion sync', () => {
2891
+ const { dir, home, work } = makeTempWorkspace('veycraft-sec02-');
2892
+
2893
+ try {
2894
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
2895
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
2896
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
2897
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
2898
+ fs.writeFileSync(path.join(work, 'context', 'cv.md'), '# Synthetic Owner\nBuilt TypeScript and Node.js systems.\n');
2899
+ const nowIso = '2026-07-10T10:00:00Z';
2900
+
2901
+ // Build CV versions registry covering:
2902
+ // - cv-owner-base: legitimate owner master CV
2903
+ // - cv-owner-tailored: legitimate owner tailored CV derived from cv-owner-base
2904
+ // - cv-tp-direct: third-party CV (owner_scope: 'third_party')
2905
+ // - cv-tp-child-masked: entry marked owner_scope: 'owner' but derived from cv-tp-direct (base_cv_version_id ancestry leak)
2906
+ // - cv-tp-path-masked: entry marked owner_scope: 'owner' but pointing to logs/resumes/cv-friend/resume.html
2907
+ // - cv-tp-reverse-link: third-party entry linking application_ids / target_job_id
2908
+ const cvRegistry = {
2909
+ schema_version: '1.0',
2910
+ updated_at: nowIso,
2911
+ versions: [
2912
+ {
2913
+ cv_version_id: 'cv-owner-base',
2914
+ version_number: 1,
2915
+ label: 'Owner Master CV',
2916
+ kind: 'generic',
2917
+ owner_scope: 'owner',
2918
+ base_cv_version_id: null,
2919
+ content_sha256: '1'.repeat(64),
2920
+ persona_id: 'backend',
2921
+ language: 'en',
2922
+ local_ref_rel: 'context/cv.md',
2923
+ tailoring_metadata: null,
2924
+ ats_metrics: null,
2925
+ application_ids: ['app-owner-1'],
2926
+ created_at: nowIso,
2927
+ updated_at: nowIso,
2928
+ },
2929
+ {
2930
+ cv_version_id: 'cv-owner-tailored',
2931
+ version_number: 1,
2932
+ label: 'Owner Tailored CV',
2933
+ kind: 'tailored',
2934
+ owner_scope: 'owner',
2935
+ base_cv_version_id: 'cv-owner-base',
2936
+ content_sha256: '2'.repeat(64),
2937
+ persona_id: 'backend',
2938
+ language: 'en',
2939
+ local_ref_rel: 'logs/resumes/2026-07-10-acme-owner-1/resume.html',
2940
+ tailoring_metadata: { target_job_id: 'gh:owner-2', target_role: 'Staff Backend Engineer 2', emphasized_skills: ['Node.js'], true_gaps_excluded: [] },
2941
+ ats_metrics: null,
2942
+ application_ids: ['app-owner-2'],
2943
+ created_at: nowIso,
2944
+ updated_at: nowIso,
2945
+ },
2946
+ {
2947
+ cv_version_id: 'cv-tp-direct',
2948
+ version_number: 1,
2949
+ label: 'Third Party Direct CV',
2950
+ kind: 'tailored',
2951
+ owner_scope: 'third_party',
2952
+ base_cv_version_id: null,
2953
+ content_sha256: '3'.repeat(64),
2954
+ persona_id: null,
2955
+ language: 'en',
2956
+ local_ref_rel: 'logs/resumes/cv-alice-client/resume.html',
2957
+ tailoring_metadata: { target_job_id: 'gh:tp-2', target_role: 'Third Party Beta Role', emphasized_skills: [], true_gaps_excluded: [] },
2958
+ ats_metrics: null,
2959
+ application_ids: [],
2960
+ created_at: nowIso,
2961
+ updated_at: nowIso,
2962
+ },
2963
+ {
2964
+ cv_version_id: 'cv-tp-child-masked',
2965
+ version_number: 1,
2966
+ label: 'Masked Child of Third Party Base',
2967
+ kind: 'tailored',
2968
+ owner_scope: 'owner',
2969
+ base_cv_version_id: 'cv-tp-direct',
2970
+ content_sha256: '4'.repeat(64),
2971
+ persona_id: null,
2972
+ language: 'en',
2973
+ local_ref_rel: 'logs/resumes/2026-07-10-masked-child/resume.html',
2974
+ tailoring_metadata: { target_job_id: null, target_role: 'Third Party Delta Role', emphasized_skills: [], true_gaps_excluded: [] },
2975
+ ats_metrics: null,
2976
+ application_ids: [],
2977
+ created_at: nowIso,
2978
+ updated_at: nowIso,
2979
+ },
2980
+ {
2981
+ cv_version_id: 'cv-tp-path-masked',
2982
+ version_number: 1,
2983
+ label: 'Masked Path Third Party CV',
2984
+ kind: 'generic',
2985
+ owner_scope: 'owner',
2986
+ base_cv_version_id: null,
2987
+ content_sha256: '5'.repeat(64),
2988
+ persona_id: null,
2989
+ language: 'en',
2990
+ local_ref_rel: 'logs/resumes/cv-bob-client/resume.html',
2991
+ tailoring_metadata: null,
2992
+ ats_metrics: null,
2993
+ application_ids: [],
2994
+ created_at: nowIso,
2995
+ updated_at: nowIso,
2996
+ },
2997
+ ],
2998
+ };
2999
+ const cvVal = validateCvVersionsRegistry(cvRegistry);
3000
+ assert.equal(cvVal.valid, true, cvVal.errors.join('; '));
3001
+ writeAtomic(path.join(work, 'logs', 'cv-versions.json'), `${JSON.stringify(cvRegistry, null, 2)}\n`, { boundary: work, home });
3002
+
3003
+ // Verify listOwnerCvVersions & selectBestOwnerCvVersion filter out third-party CVs AND masked descendants/paths
3004
+ const ownerCvs = listOwnerCvVersions(work, { home });
3005
+ assert.deepEqual(ownerCvs.versions.map(v => v.cv_version_id), ['cv-owner-base', 'cv-owner-tailored']);
3006
+ assert.equal(ownerCvs.third_party_excluded, 3);
3007
+
3008
+ const makeOwnerApp = (idx, cvId, isTailored, baseCvId = null) => normalizeApplicationRecord({
3009
+ job_id: `gh:owner-${idx}`,
3010
+ applied_at: '2026-07-05T10:00:00Z',
3011
+ updated_at: '2026-07-05T10:00:00Z',
3012
+ company: `OwnerSecretCleanCo${idx}`,
3013
+ title: `Staff Backend Engineer ${idx}`,
3014
+ url: `https://boards.greenhouse.io/ownersecretcleanco${idx}/jobs/${100 + idx}`,
3015
+ platform: 'greenhouse',
3016
+ source_channel: 'direct_ats',
3017
+ status: idx <= 2 ? 'interview' : 'applied',
3018
+ match_score: 8.5,
3019
+ cv_version_id: cvId,
3020
+ cv_tailoring: {
3021
+ is_tailored: isTailored,
3022
+ base_cv_version_id: baseCvId,
3023
+ tailored_folder_rel: isTailored ? `logs/resumes/2026-07-05-owner-${idx}` : null,
3024
+ tailoring_notes_rel: isTailored ? `logs/resumes/2026-07-05-owner-${idx}/evidence-map.md` : null,
3025
+ ats_keyword_before_pct: 60,
3026
+ ats_keyword_after_pct: 85,
3027
+ },
3028
+ provenance: {
3029
+ created_by: '04-fill-and-apply',
3030
+ created_at: nowIso,
3031
+ last_updated_by: null,
3032
+ receipt_verified: true,
3033
+ third_party_subject: false,
3034
+ },
3035
+ });
3036
+
3037
+ const ownerRecords = [
3038
+ makeOwnerApp(1, 'cv-owner-base', false, null),
3039
+ makeOwnerApp(2, 'cv-owner-tailored', true, 'cv-owner-base'),
3040
+ makeOwnerApp(3, 'cv-owner-base', false, null),
3041
+ makeOwnerApp(4, 'cv-owner-tailored', true, 'cv-owner-base'),
3042
+ makeOwnerApp(5, 'cv-owner-base', false, null),
3043
+ ];
3044
+
3045
+ // 1. Third-party record marked via provenance flag
3046
+ const tp1Provenance = normalizeApplicationRecord({
3047
+ job_id: 'gh:tp-1',
3048
+ applied_at: '2026-07-05T10:00:00Z',
3049
+ company: 'LeakCanaryAlphaCorp',
3050
+ title: 'Third Party Alpha Role',
3051
+ url: 'https://boards.greenhouse.io/leakcanaryalpha/jobs/1',
3052
+ platform: 'workday',
3053
+ status: 'offer',
3054
+ match_score: 9.5,
3055
+ cv_version_id: 'cv-owner-base',
3056
+ provenance: { created_by: '27-universal-cv-builder', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: true },
3057
+ });
3058
+
3059
+ // 2. Third-party record linked via cv_version_id in cv-versions.json WITHOUT provenance.third_party_subject = true
3060
+ const tp2RegistryCv = normalizeApplicationRecord({
3061
+ job_id: 'gh:tp-2',
3062
+ applied_at: '2026-07-05T10:00:00Z',
3063
+ company: 'LeakCanaryBetaCorp',
3064
+ title: 'Third Party Beta Role',
3065
+ url: 'https://boards.greenhouse.io/leakcanarybeta/jobs/2',
3066
+ platform: 'workday',
3067
+ status: 'interview',
3068
+ match_score: 9.2,
3069
+ cv_version_id: 'cv-tp-direct',
3070
+ cv_tailoring: { is_tailored: true, base_cv_version_id: null, tailored_folder_rel: null, tailoring_notes_rel: null },
3071
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3072
+ });
3073
+
3074
+ // 3a. Third-party record linked indirectly via cv_tailoring.base_cv_version_id
3075
+ const tp3BaseCv = normalizeApplicationRecord({
3076
+ job_id: 'gh:tp-3a',
3077
+ applied_at: '2026-07-05T10:00:00Z',
3078
+ company: 'LeakCanaryGammaCorp',
3079
+ title: 'Third Party Gamma Role',
3080
+ url: 'https://boards.greenhouse.io/leakcanarygamma/jobs/3',
3081
+ platform: 'workday',
3082
+ status: 'interview',
3083
+ match_score: 9.1,
3084
+ cv_version_id: null,
3085
+ cv_tailoring: { is_tailored: true, base_cv_version_id: 'cv-tp-direct', tailored_folder_rel: null, tailoring_notes_rel: null },
3086
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3087
+ });
3088
+
3089
+ // 3b. Third-party record linked via a registry CV whose ancestor base_cv_version_id is third-party
3090
+ const tp3AncestryCv = normalizeApplicationRecord({
3091
+ job_id: 'gh:tp-3b',
3092
+ applied_at: '2026-07-05T10:00:00Z',
3093
+ company: 'LeakCanaryDeltaCorp',
3094
+ title: 'Third Party Delta Role',
3095
+ url: 'https://boards.greenhouse.io/leakcanarydelta/jobs/4',
3096
+ platform: 'workday',
3097
+ status: 'interview',
3098
+ match_score: 9.0,
3099
+ cv_version_id: 'cv-tp-child-masked',
3100
+ cv_tailoring: { is_tailored: true, base_cv_version_id: 'cv-tp-direct', tailored_folder_rel: null, tailoring_notes_rel: null },
3101
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3102
+ });
3103
+
3104
+ // 4. Third-party record linked via cv_tailoring.tailored_folder_rel under logs/resumes/cv-<slug>/
3105
+ const tp4FolderRel = normalizeApplicationRecord({
3106
+ job_id: 'gh:tp-4',
3107
+ applied_at: '2026-07-05T10:00:00Z',
3108
+ company: 'LeakCanaryEpsilonCorp',
3109
+ title: 'Third Party Epsilon Role',
3110
+ url: 'https://boards.greenhouse.io/leakcanaryepsilon/jobs/5',
3111
+ platform: 'workday',
3112
+ status: 'applied',
3113
+ match_score: 8.8,
3114
+ cv_version_id: 'cv-owner-base',
3115
+ cv_tailoring: { is_tailored: false, base_cv_version_id: null, tailored_folder_rel: 'logs/resumes/cv-external-friend', tailoring_notes_rel: null },
3116
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3117
+ });
3118
+
3119
+ // 5. Third-party record linked via cv_tailoring.tailoring_notes_rel under logs/resumes/cv-<slug>/
3120
+ const tp5NotesRel = normalizeApplicationRecord({
3121
+ job_id: 'gh:tp-5',
3122
+ applied_at: '2026-07-05T10:00:00Z',
3123
+ company: 'LeakCanaryZetaCorp',
3124
+ title: 'Third Party Zeta Role',
3125
+ url: 'https://boards.greenhouse.io/leakcanaryzeta/jobs/6',
3126
+ platform: 'workday',
3127
+ status: 'applied',
3128
+ match_score: 8.7,
3129
+ cv_version_id: 'cv-owner-base',
3130
+ cv_tailoring: { is_tailored: false, base_cv_version_id: null, tailored_folder_rel: null, tailoring_notes_rel: 'logs/resumes/cv-external-friend/evidence-map.md' },
3131
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3132
+ });
3133
+
3134
+ // 6. Missing registry entry / ambiguous ownership -> excluded fail-closed
3135
+ const tp6MissingCv = normalizeApplicationRecord({
3136
+ job_id: 'gh:tp-6',
3137
+ applied_at: '2026-07-05T10:00:00Z',
3138
+ company: 'LeakCanaryEtaCorp',
3139
+ title: 'Third Party Eta Role',
3140
+ url: 'https://boards.greenhouse.io/leakcanaryeta/jobs/7',
3141
+ platform: 'workday',
3142
+ status: 'interview',
3143
+ match_score: 8.9,
3144
+ cv_version_id: 'cv-unknown-orphan-id',
3145
+ cv_tailoring: { is_tailored: true, base_cv_version_id: null, tailored_folder_rel: null, tailoring_notes_rel: null },
3146
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3147
+ });
3148
+
3149
+ const allThirdPartyRecords = [
3150
+ tp1Provenance,
3151
+ tp2RegistryCv,
3152
+ tp3BaseCv,
3153
+ tp3AncestryCv,
3154
+ tp4FolderRel,
3155
+ tp5NotesRel,
3156
+ tp6MissingCv,
3157
+ ];
3158
+
3159
+ for (const tpRec of allThirdPartyRecords) {
3160
+ const cls = classifyApplicationOwnership(tpRec, cvRegistry);
3161
+ assert.equal(cls.isOwner, false, `Expected ${tpRec.application_id} to be excluded, got reason=${cls.reason}`);
3162
+ assert.equal(isOwnerApplicationRecord(tpRec, cvRegistry), false);
3163
+ }
3164
+
3165
+ for (const ownRec of ownerRecords) {
3166
+ const cls = classifyApplicationOwnership(ownRec, cvRegistry);
3167
+ assert.equal(cls.isOwner, true, `Expected ${ownRec.application_id} to be owner, got reason=${cls.reason}`);
3168
+ assert.equal(isOwnerApplicationRecord(ownRec, cvRegistry), true);
3169
+ }
3170
+
3171
+ // 7. Malformed registry data -> fails closed with validation error
3172
+ assert.throws(
3173
+ () => classifyApplicationOwnership(ownerRecords[0], { schema_version: '999', versions: 'corrupt' }),
3174
+ /Invalid CV versions registry/i,
3175
+ );
3176
+ assert.throws(
3177
+ () => computeCareerAnalytics(ownerRecords, { schema_version: '999', versions: 'corrupt' }, { period: 'all', now: new Date(nowIso) }),
3178
+ /Invalid CV versions registry/i,
3179
+ );
3180
+
3181
+ // 8 & 9. Owner-only dataset vs Mixed (owner + third-party) dataset must produce identical analytics counts & rates
3182
+ const ownerOnlyAnalytics = computeCareerAnalytics(ownerRecords, cvRegistry, { period: 'all', now: new Date(nowIso) });
3183
+ const mixedRecords = [...ownerRecords, ...allThirdPartyRecords];
3184
+ const mixedAnalytics = computeCareerAnalytics(mixedRecords, cvRegistry, { period: 'all', now: new Date(nowIso) });
3185
+
3186
+ assert.equal(ownerOnlyAnalytics.funnel.total_tracked, 5);
3187
+ assert.equal(ownerOnlyAnalytics.isolation.third_party_applications_excluded, 0);
3188
+ assert.equal(mixedAnalytics.funnel.total_tracked, 5);
3189
+ assert.equal(mixedAnalytics.isolation.third_party_applications_excluded, allThirdPartyRecords.length);
3190
+ assert.deepEqual(mixedAnalytics.funnel, ownerOnlyAnalytics.funnel);
3191
+ assert.deepEqual(mixedAnalytics.source_performance, ownerOnlyAnalytics.source_performance);
3192
+ assert.deepEqual(mixedAnalytics.cv_performance, ownerOnlyAnalytics.cv_performance);
3193
+
3194
+ // 10. Persist mixed ledger & cv-versions.json to workspace and verify zero third-party identifiers leak into
3195
+ // analytics artifact, summary, dashboard, status metrics, run counts, workflow queue (career next), or Notion sync inputs
3196
+ // Note: Keep persisted ledger schema-valid while testing registry-linked third-party records (tp1Provenance, tp2RegistryCv, tp3BaseCv, tp3AncestryCv, tp6MissingCv)
3197
+ const persistedMixedRecords = [
3198
+ ...ownerRecords,
3199
+ tp1Provenance,
3200
+ tp2RegistryCv,
3201
+ tp3BaseCv,
3202
+ tp3AncestryCv,
3203
+ tp6MissingCv,
3204
+ ];
3205
+ writeAtomic(path.join(work, 'logs', 'cv-versions.json'), `${JSON.stringify(cvRegistry, null, 2)}\n`, { boundary: work, home });
3206
+ writeAtomic(path.join(work, 'logs', 'applications-log.json'), `${JSON.stringify(persistedMixedRecords, null, 2)}\n`, { boundary: work, home });
3207
+
3208
+ const wsAnalytics = runCareerAnalyticsForWorkspace(work, { period: 'all', nowIso, write: true, home });
3209
+ const wsSummary = summarizeCareerWorkspace(work, { nowIso, home });
3210
+ const wsMetrics = computeWorkspaceStatusMetrics(work, { home, nowIso });
3211
+ const wsNext = computeCareerWorkflowQueue(work, { home, sourceRoot: REPO_ROOT, nowIso });
3212
+ const wsSyncInputs = loadCareerSyncInputs(work, { home });
3213
+ const rDashboard = runCli(['career', 'dashboard'], { cwd: work, home });
3214
+ assert.equal(rDashboard.status, 0, rDashboard.stderr);
3215
+
3216
+ assert.equal(wsSummary.funnel.total_tracked, 5);
3217
+ assert.equal(wsMetrics.pipeline.applied, 5);
3218
+ assert.equal(wsMetrics.third_party_excluded, 5);
3219
+
3220
+ const combinedOutputs = JSON.stringify({
3221
+ artifact: wsAnalytics.artifact,
3222
+ summary: wsSummary,
3223
+ metrics: wsMetrics,
3224
+ next: wsNext,
3225
+ dashboardHtml: fs.readFileSync(path.join(work, 'logs', 'exports', 'dashboard.html'), 'utf8'),
3226
+ });
3227
+
3228
+ for (const forbidden of [
3229
+ 'LeakCanaryAlphaCorp',
3230
+ 'LeakCanaryBetaCorp',
3231
+ 'LeakCanaryGammaCorp',
3232
+ 'LeakCanaryDeltaCorp',
3233
+ 'LeakCanaryEpsilonCorp',
3234
+ 'LeakCanaryZetaCorp',
3235
+ 'LeakCanaryEtaCorp',
3236
+ 'cv-tp-direct',
3237
+ 'cv-tp-child-masked',
3238
+ 'cv-tp-path-masked',
3239
+ 'cv-unknown-orphan-id',
3240
+ 'gh:tp-1',
3241
+ 'gh:tp-2',
3242
+ 'gh:tp-3a',
3243
+ 'gh:tp-3b',
3244
+ 'gh:tp-6',
3245
+ ]) {
3246
+ assert.equal(
3247
+ combinedOutputs.includes(forbidden),
3248
+ false,
3249
+ `Third-party identifier "${forbidden}" must never leak into analytics, summary, metrics, next queue, or dashboard`,
3250
+ );
3251
+ }
3252
+ assert.ok(wsSyncInputs.applications.length === 10);
3253
+ } finally {
3254
+ fs.rmSync(dir, { recursive: true, force: true });
3255
+ }
3256
+ });
3257
+
3258
+ // ===========================================================================
3259
+ // Test 19b: SEC-02 Closure — F-01 (path canonicalization), F-04 (missing registry fail-closed),
3260
+ // and F-05 (lifecycle write & Notion sync ownership centralization)
3261
+ // ===========================================================================
3262
+ test('19b. SEC-02 closure: F-01 path canonicalization, F-04 missing CV registry fail-closed, and F-05 lifecycle/Notion ownership centralization', () => {
3263
+ const { dir, home, work } = makeTempWorkspace('veycraft-sec02-closure-');
3264
+ const nowIso = '2026-07-10T10:00:00Z';
3265
+
3266
+ try {
3267
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
3268
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
3269
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
3270
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
3271
+ fs.writeFileSync(path.join(work, 'context', 'cv.md'), '# Owner CV\nBuilt Node.js systems.\n');
3272
+
3273
+ // F-01: Alternate non-canonical third-party path representations must be detected & rejected
3274
+ const thirdPartyVariants = [
3275
+ 'logs/resumes/./cv-alice/resume.html',
3276
+ 'logs//resumes/cv-alice/resume.html',
3277
+ 'logs/resumes/foo/../cv-alice/resume.html',
3278
+ 'logs\\resumes\\.\\cv-alice\\resume.html',
3279
+ 'logs/resumes\\cv-alice/resume.html',
3280
+ 'logs/resumes/cv-alice/resume.html',
3281
+ ];
3282
+ for (const p of thirdPartyVariants) {
3283
+ assert.equal(isThirdPartyCvPath(p), true, `isThirdPartyCvPath must detect "${p}"`);
3284
+ }
3285
+ for (const safeOwnerPath of ['context/cv.md', 'logs/resumes/2026-07-10-acme-1/resume.html', 'logs/resumes/acme-2026-11/']) {
3286
+ assert.equal(isThirdPartyCvPath(safeOwnerPath), false, `Valid owner path must not be flagged third-party: "${safeOwnerPath}"`);
3287
+ }
3288
+
3289
+ // F-01: Non-canonical paths in CV registry must fail validation and ownership checks
3290
+ for (const badPath of ['logs/resumes/./cv-alice/resume.html', 'logs//resumes/cv-alice/resume.html', 'logs/resumes/foo/../cv-alice/resume.html']) {
3291
+ const badReg = {
3292
+ schema_version: '1.0',
3293
+ updated_at: nowIso,
3294
+ versions: [{
3295
+ cv_version_id: 'cv-bad-path',
3296
+ version_number: 1,
3297
+ label: 'Bad Path CV',
3298
+ kind: 'generic',
3299
+ owner_scope: 'owner',
3300
+ base_cv_version_id: null,
3301
+ content_sha256: 'a'.repeat(64),
3302
+ local_ref_rel: badPath,
3303
+ created_at: nowIso,
3304
+ application_ids: [],
3305
+ }],
3306
+ };
3307
+ assert.equal(validateCvVersionsRegistry(badReg).valid, false, `Registry must reject non-canonical path "${badPath}"`);
3308
+ assert.equal(classifyCvRegistryEntryOwnership(badReg.versions[0], new Map([['cv-bad-path', badReg.versions[0]]])).isOwner, false);
3309
+ assert.throws(() => registerCvVersion(null, badReg.versions[0]), /third-party|unsafe/i);
3310
+ }
3311
+
3312
+ // F-04: Missing registry (null) must fail closed for CV-attributed records while preserving unattributed owner records
3313
+ const recWithCv = normalizeApplicationRecord({
3314
+ job_id: 'gh:f04-cv',
3315
+ company: 'MissingRegCvCorp',
3316
+ title: 'Engineer',
3317
+ url: 'https://boards.greenhouse.io/missingregcv/jobs/1',
3318
+ platform: 'greenhouse',
3319
+ status: 'applied',
3320
+ applied_at: nowIso,
3321
+ updated_at: nowIso,
3322
+ cv_version_id: 'cv-tp-or-unknown',
3323
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3324
+ });
3325
+ const recWithBaseCv = normalizeApplicationRecord({
3326
+ job_id: 'gh:f04-base',
3327
+ company: 'MissingRegBaseCorp',
3328
+ title: 'Engineer',
3329
+ url: 'https://boards.greenhouse.io/missingregbase/jobs/2',
3330
+ platform: 'greenhouse',
3331
+ status: 'applied',
3332
+ applied_at: nowIso,
3333
+ updated_at: nowIso,
3334
+ cv_version_id: null,
3335
+ cv_tailoring: { is_tailored: true, base_cv_version_id: 'cv-tp-base', tailored_folder_rel: null, tailoring_notes_rel: null },
3336
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3337
+ });
3338
+ const recUnattributed = normalizeApplicationRecord({
3339
+ job_id: 'gh:f04-unattr',
3340
+ company: 'UnattributedOwnerCorp',
3341
+ title: 'Engineer',
3342
+ url: 'https://boards.greenhouse.io/unattrowner/jobs/3',
3343
+ platform: 'greenhouse',
3344
+ status: 'applied',
3345
+ applied_at: nowIso,
3346
+ updated_at: nowIso,
3347
+ cv_version_id: null,
3348
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3349
+ });
3350
+
3351
+ assert.equal(classifyApplicationOwnership(recWithCv, null).isOwner, false);
3352
+ assert.equal(classifyApplicationOwnership(recWithCv, null).reason, 'missing_cv_versions_registry');
3353
+ assert.equal(classifyApplicationOwnership(recWithBaseCv, null).isOwner, false);
3354
+ assert.equal(classifyApplicationOwnership(recWithBaseCv, null).reason, 'missing_cv_versions_registry');
3355
+ assert.equal(classifyApplicationOwnership(recUnattributed, null).isOwner, true);
3356
+
3357
+ const emptyReg = { schema_version: '1.0', updated_at: nowIso, versions: [] };
3358
+ assert.equal(classifyApplicationOwnership(recWithCv, emptyReg).isOwner, false);
3359
+ assert.equal(classifyApplicationOwnership(recWithBaseCv, emptyReg).isOwner, false);
3360
+ assert.equal(classifyApplicationOwnership(recUnattributed, emptyReg).isOwner, true);
3361
+ assert.throws(() => classifyApplicationOwnership(recUnattributed, { schema_version: 'bad', versions: 'nope' }), /Invalid CV versions registry/i);
3362
+
3363
+ // Workspace without logs/cv-versions.json: CV-attributed records excluded from analytics, summary, status metrics, run counts, queue & dashboard
3364
+ writeAtomic(path.join(work, 'logs', 'applications-log.json'), JSON.stringify([recWithCv, recWithBaseCv, recUnattributed], null, 2) + '\n', { boundary: work, home });
3365
+ const f04Sum = summarizeCareerWorkspace(work, { home, nowIso });
3366
+ const f04Metrics = computeWorkspaceStatusMetrics(work, { home, nowIso });
3367
+ const f04Counts = deriveRunCountsFromLedger(work, '2026-07-10', { home });
3368
+ const f04Queue = computeCareerWorkflowQueue(work, { home, sourceRoot: REPO_ROOT, nowIso });
3369
+ const f04Dash = runCli(['career', 'dashboard'], { cwd: work, home });
3370
+ assert.equal(f04Dash.status, 0, f04Dash.stderr);
3371
+ const f04DashHtml = fs.readFileSync(path.join(work, 'logs', 'exports', 'dashboard.html'), 'utf8');
3372
+
3373
+ assert.equal(f04Sum.funnel.total_tracked, 1);
3374
+ assert.equal(f04Metrics.pipeline.applied, 1);
3375
+ assert.equal(f04Metrics.third_party_excluded, 2);
3376
+ assert.equal(f04Counts.counts.applied, 1);
3377
+ const f04Combined = JSON.stringify({ f04Sum, f04Metrics, f04Queue, f04DashHtml });
3378
+ assert.equal(f04Combined.includes('MissingRegCvCorp'), false);
3379
+ assert.equal(f04Combined.includes('MissingRegBaseCorp'), false);
3380
+ assert.equal(f04DashHtml.includes('UnattributedOwnerCorp'), true);
3381
+
3382
+ // F-05: Ownership centralization across lifecycle mutations and Notion sync
3383
+ const revJobId = 'gh:f05-rev';
3384
+ const revAppId = computeApplicationId(revJobId);
3385
+ const f05Reg = {
3386
+ schema_version: '1.0',
3387
+ updated_at: nowIso,
3388
+ versions: [
3389
+ {
3390
+ cv_version_id: 'cv-owner-valid',
3391
+ version_number: 1,
3392
+ label: 'Valid Owner CV',
3393
+ kind: 'generic',
3394
+ owner_scope: 'owner',
3395
+ base_cv_version_id: null,
3396
+ content_sha256: '1'.repeat(64),
3397
+ local_ref_rel: 'context/cv.md',
3398
+ created_at: nowIso,
3399
+ application_ids: [],
3400
+ },
3401
+ {
3402
+ cv_version_id: 'cv-tp-root',
3403
+ version_number: 1,
3404
+ label: 'Third Party Root',
3405
+ kind: 'tailored',
3406
+ owner_scope: 'third_party',
3407
+ base_cv_version_id: null,
3408
+ content_sha256: '2'.repeat(64),
3409
+ local_ref_rel: 'logs/resumes/cv-alice/resume.html',
3410
+ tailoring_metadata: { target_job_id: revJobId, target_role: 'Rev Role', emphasized_skills: [], true_gaps_excluded: [] },
3411
+ created_at: nowIso,
3412
+ application_ids: [revAppId],
3413
+ },
3414
+ {
3415
+ cv_version_id: 'cv-tp-child-masked',
3416
+ version_number: 1,
3417
+ label: 'Masked Child of TP Root',
3418
+ kind: 'tailored',
3419
+ owner_scope: 'owner',
3420
+ base_cv_version_id: 'cv-tp-root',
3421
+ content_sha256: '3'.repeat(64),
3422
+ local_ref_rel: 'logs/resumes/2026-07-10-masked/resume.html',
3423
+ created_at: nowIso,
3424
+ application_ids: [],
3425
+ },
3426
+ ],
3427
+ };
3428
+ writeAtomic(path.join(work, 'logs', 'cv-versions.json'), JSON.stringify(f05Reg, null, 2) + '\n', { boundary: work, home });
3429
+
3430
+ // Valid owner CV & third-party CV with registry
3431
+ const recOwnerWithCv = normalizeApplicationRecord({
3432
+ job_id: 'gh:f05-owner',
3433
+ company: 'OwnerValidCo',
3434
+ title: 'Engineer',
3435
+ url: 'https://boards.greenhouse.io/ownervalid/jobs/1',
3436
+ platform: 'greenhouse',
3437
+ status: 'applied',
3438
+ applied_at: nowIso,
3439
+ updated_at: nowIso,
3440
+ cv_version_id: 'cv-owner-valid',
3441
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3442
+ });
3443
+ assert.equal(classifyApplicationOwnership(recOwnerWithCv, f05Reg).isOwner, true);
3444
+ assert.equal(validateCvAttribution(recOwnerWithCv, { allCvRegistry: f05Reg }).valid, true);
3445
+
3446
+ // registerOwnerCvVersionForWorkspace must reject masked third-party child base_cv_version_id & missing base_cv_version_id
3447
+ assert.throws(
3448
+ () => registerOwnerCvVersionForWorkspace(work, {
3449
+ cv_version_id: 'cv-laundered-1',
3450
+ label: 'Laundered',
3451
+ kind: 'tailored',
3452
+ file: 'context/cv.md',
3453
+ base_cv_version_id: 'cv-tp-child-masked',
3454
+ }, { home, nowIso }),
3455
+ /third_party_blocked/i,
3456
+ );
3457
+ assert.throws(
3458
+ () => registerOwnerCvVersionForWorkspace(work, {
3459
+ cv_version_id: 'cv-missing-base',
3460
+ label: 'Missing Base',
3461
+ kind: 'tailored',
3462
+ file: 'context/cv.md',
3463
+ base_cv_version_id: 'cv-does-not-exist',
3464
+ }, { home, nowIso }),
3465
+ /invalid_base_cv_version/i,
3466
+ );
3467
+
3468
+ // confirmApplicationSubmission must reject masked third-party child CV
3469
+ writeAtomic(path.join(work, 'logs', 'applications-log.json'), JSON.stringify([recOwnerWithCv], null, 2) + '\n', { boundary: work, home });
3470
+ reserveApplicationSubmission(work, { job_id: 'gh:f05-res', company: 'ReserveCo', title: 'Eng', platform: 'greenhouse' }, { home, nowIso, sourceRoot: REPO_ROOT });
3471
+ assert.throws(
3472
+ () => confirmApplicationSubmission(work, { job_id: 'gh:f05-res', receipt: 'Received', cv_version_id: 'cv-tp-child-masked' }, { home, nowIso }),
3473
+ /third_party_blocked/i,
3474
+ );
3475
+
3476
+ // prepareApplicationPackage must reject masked third-party child CV, masked base CV, and reverse-linked third-party records
3477
+ const pkgDir = path.join(work, 'logs', 'resumes', '2026-07-10-f05-pkg');
3478
+ fs.mkdirSync(pkgDir, { recursive: true });
3479
+ fs.writeFileSync(path.join(pkgDir, 'resume.txt'), 'Alex Rivera\nBuilt Node.js systems.');
3480
+ const recRevPrepared = normalizeApplicationRecord({
3481
+ job_id: revJobId,
3482
+ company: 'RevLinkCo',
3483
+ title: 'Engineer',
3484
+ platform: 'greenhouse',
3485
+ status: 'discovered',
3486
+ updated_at: nowIso,
3487
+ provenance: { created_by: '02-discover-and-triage', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3488
+ });
3489
+ const recPrepOwner = normalizeApplicationRecord({
3490
+ job_id: 'gh:f05-prep-owner',
3491
+ company: 'PrepOwnerCo',
3492
+ title: 'Engineer',
3493
+ platform: 'greenhouse',
3494
+ status: 'discovered',
3495
+ updated_at: nowIso,
3496
+ provenance: { created_by: '02-discover-and-triage', created_at: nowIso, last_updated_by: null, receipt_verified: false, third_party_subject: false },
3497
+ });
3498
+ writeAtomic(path.join(work, 'logs', 'applications-log.json'), JSON.stringify([recOwnerWithCv, recRevPrepared, recPrepOwner], null, 2) + '\n', { boundary: work, home });
3499
+ assert.throws(
3500
+ () => prepareApplicationPackage(work, { job_id: revJobId, folder_rel: 'logs/resumes/2026-07-10-f05-pkg', require_ready: false }, { home, nowIso }),
3501
+ /third_party_blocked/i,
3502
+ );
3503
+ assert.throws(
3504
+ () => prepareApplicationPackage(work, { job_id: 'gh:f05-prep-owner', folder_rel: 'logs/resumes/2026-07-10-f05-pkg', cv_version_id: 'cv-tp-child-masked', require_ready: false }, { home, nowIso }),
3505
+ /third_party_blocked/i,
3506
+ );
3507
+ assert.throws(
3508
+ () => prepareApplicationPackage(work, { job_id: 'gh:f05-prep-owner', folder_rel: 'logs/resumes/2026-07-10-f05-pkg', base_cv_version_id: 'cv-tp-child-masked', require_ready: false }, { home, nowIso }),
3509
+ /third_party_blocked/i,
3510
+ );
3511
+ // registerOwnerCvVersionForWorkspace must also reject linking owner CV to reverse-linked third-party application
3512
+ assert.throws(
3513
+ () => registerOwnerCvVersionForWorkspace(work, {
3514
+ cv_version_id: 'cv-owner-link-rev',
3515
+ label: 'Owner Link Rev',
3516
+ kind: 'generic',
3517
+ file: 'context/cv.md',
3518
+ link_job_id: revJobId,
3519
+ }, { home, nowIso }),
3520
+ /third_party_blocked/i,
3521
+ );
3522
+
3523
+ // Notion sync eligibility must block reverse-linked records and third-party paths in screenshot, dossier_rel, blueprint_rel, draft_rel
3524
+ const recRevSubmitted = normalizeApplicationRecord({
3525
+ job_id: revJobId,
3526
+ company: 'RevLinkNotionCo',
3527
+ title: 'Engineer',
3528
+ url: 'https://boards.greenhouse.io/revlink/jobs/1',
3529
+ platform: 'greenhouse',
3530
+ status: 'applied',
3531
+ applied_at: nowIso,
3532
+ updated_at: nowIso,
3533
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3534
+ });
3535
+ const makeArtifactTpRec = (id, patch) => normalizeApplicationRecord({
3536
+ job_id: id,
3537
+ company: `TpArtifactCo-${id}`,
3538
+ title: 'Engineer',
3539
+ url: `https://boards.greenhouse.io/tpartifact/jobs/${id.replace(/\W/g, '')}`,
3540
+ platform: 'greenhouse',
3541
+ status: 'applied',
3542
+ applied_at: nowIso,
3543
+ updated_at: nowIso,
3544
+ provenance: { created_by: '04-fill-and-apply', created_at: nowIso, last_updated_by: null, receipt_verified: true, third_party_subject: false },
3545
+ ...patch,
3546
+ });
3547
+ const recTpShot = makeArtifactTpRec('gh:f05-shot', { screenshot: 'logs/resumes/cv-alice/shot.png' });
3548
+ const recTpDraft = makeArtifactTpRec('gh:f05-draft', { follow_up: { follow_up_count: 0, status: 'drafted', next_due_at: null, last_followed_up_at: null, draft_rel: 'logs/resumes/./cv-alice/draft.md' } });
3549
+ const recTpDossier = makeArtifactTpRec('gh:f05-dossier', { interviews: [{ interview_id: 'iv1', round: 1, stage: 'technical_screen', status: 'scheduled', outcome: 'pending', scheduled_at: null, timezone: null, dossier_rel: 'logs/resumes/cv-alice/dossier.md', notes: '' }] });
3550
+ const recTpBlueprint = makeArtifactTpRec('gh:f05-blueprint', { assessments: [{ assessment_id: 'as1', type: 'take_home', status: 'assigned', outcome: 'pending', received_at: nowIso, due_at: null, submitted_at: null, blueprint_rel: 'logs/resumes/cv-alice/blueprint.md', notes: '' }] });
3551
+
3552
+ const notionRes = computeNotionSyncDiff({
3553
+ applications: [recOwnerWithCv, recRevSubmitted, recTpShot, recTpDraft, recTpDossier, recTpBlueprint],
3554
+ dailyRuns: [],
3555
+ insights: [],
3556
+ allCvRegistry: f05Reg,
3557
+ syncState: createEmptySyncState(),
3558
+ createdAt: nowIso,
3559
+ });
3560
+ assert.deepEqual(
3561
+ notionRes.plan.operations.map(o => o.canonical_key),
3562
+ [recOwnerWithCv.application_id],
3563
+ 'Only legitimate verified owner application may enter Notion sync operations',
3564
+ );
3565
+ assert.equal(notionRes.plan.blocked_items.length, 5, 'All 5 third-party/reverse-linked/artifact-path applications must be blocked');
3566
+ } finally {
3567
+ fs.rmSync(dir, { recursive: true, force: true });
3568
+ }
3569
+ });
3570
+
3571
+ // ===========================================================================
3572
+ // Test 20: SEC-04 — Path Traversal & Symlink Bypass Prevention
3573
+ // ===========================================================================
3574
+ test('20. SEC-04: relative path validation, workspace containment, third-party path isolation & CLI symlink refusal', () => {
3575
+ const { dir, home, work } = makeTempWorkspace('veycraft-sec04-');
3576
+ const outsideDir = path.join(dir, 'outside-secret');
3577
+ fs.mkdirSync(outsideDir, { recursive: true });
3578
+ fs.mkdirSync(path.join(work, 'config'), { recursive: true });
3579
+ fs.mkdirSync(path.join(work, 'context'), { recursive: true });
3580
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'guardrails.yaml'), path.join(work, 'config', 'guardrails.yaml'));
3581
+ fs.copyFileSync(path.join(REPO_ROOT, 'config', 'invariants.txt'), path.join(work, 'config', 'invariants.txt'));
3582
+ const nowIso = '2026-07-10T12:00:00Z';
3583
+
3584
+ try {
3585
+ // 1. ../secret.txt traversal, 2. nested logs/resumes/../../../../etc/passwd, 3. absolute POSIX /etc/passwd,
3586
+ // 4. Windows drive C:\Windows\System32\drivers\etc\hosts, 5. UNC \\server\share\file, 13. mixed separators / quotes
3587
+ const unsafePaths = [
3588
+ '../secret.txt',
3589
+ 'logs/resumes/../../../../etc/passwd',
3590
+ '/etc/passwd',
3591
+ 'C:\\Windows\\System32\\drivers\\etc\\hosts',
3592
+ '\\\\server\\share\\file',
3593
+ '//server/share/file',
3594
+ 'logs/resumes/./bad',
3595
+ 'logs/resumes/bad"quote/file.md',
3596
+ 'logs/resumes/bad\x00null.md',
3597
+ ];
3598
+ for (const bad of unsafePaths) {
3599
+ assert.equal(isSafeWorkspaceRelativePath(bad), false, `Expected unsafe path to be rejected: ${bad}`);
3600
+ }
3601
+
3602
+ // 8. Third-party CV path in owner record (logs/resumes/cv-client/...) rejected when allowThirdParty=false
3603
+ assert.equal(isSafeWorkspaceRelativePath('logs/resumes/cv-client/resume.html', { allowThirdParty: false }), false);
3604
+ assert.equal(isSafeWorkspaceRelativePath('logs/resumes/cv-client/resume.html', { allowThirdParty: true }), true);
3605
+
3606
+ // 12. Legitimate relative paths inside workspace continue to work
3607
+ assert.equal(isSafeWorkspaceRelativePath('logs/screenshots/gh-101.png', { allowThirdParty: false }), true);
3608
+ assert.equal(isSafeWorkspaceRelativePath('logs\\resumes\\2026-07-10-acme-101\\interview-dossier.md', { allowThirdParty: false }), true);
3609
+
3610
+ // 9. Persisted ledger containing invalid relative paths in screenshot, cv_tailoring, interviews, assessments, follow_up
3611
+ const validBaseRec = normalizeApplicationRecord({
3612
+ job_id: 'gh:sec04-valid',
3613
+ company: 'SafePathCo',
3614
+ title: 'Backend Engineer',
3615
+ platform: 'greenhouse',
3616
+ status: 'applied',
3617
+ applied_at: nowIso,
3618
+ updated_at: nowIso,
3619
+ });
3620
+ for (const [label, mutator] of [
3621
+ ['screenshot ../', r => ({ ...r, screenshot: '../secret.png' })],
3622
+ ['screenshot third-party on owner', r => ({ ...r, screenshot: 'logs/resumes/cv-other/shot.png' })],
3623
+ ['tailored_folder_rel traversal', r => ({ ...r, cv_tailoring: { is_tailored: true, base_cv_version_id: null, tailored_folder_rel: '../../etc', tailoring_notes_rel: null } })],
3624
+ ['tailoring_notes_rel drive path', r => ({ ...r, cv_tailoring: { is_tailored: true, base_cv_version_id: null, tailored_folder_rel: null, tailoring_notes_rel: 'C:\\secret\\notes.md' } })],
3625
+ ['tailored_folder_rel third-party on owner', r => ({ ...r, cv_tailoring: { is_tailored: true, base_cv_version_id: null, tailored_folder_rel: 'logs/resumes/cv-friend', tailoring_notes_rel: null } })],
3626
+ ['interviews.dossier_rel UNC', r => ({ ...r, interviews: [{ interview_id: 'iv_1', round: 1, stage: 'technical_screen', status: 'scheduled', outcome: 'pending', scheduled_at: null, timezone: null, dossier_rel: '\\\\server\\share\\dossier.md', notes: '' }] })],
3627
+ ['assessments.blueprint_rel absolute', r => ({ ...r, assessments: [{ assessment_id: 'asmt_1', type: 'take_home', status: 'assigned', outcome: 'pending', received_at: nowIso, due_at: null, submitted_at: null, blueprint_rel: '/etc/passwd', notes: '' }] })],
3628
+ ['follow_up.draft_rel traversal', r => ({ ...r, follow_up: { follow_up_count: 0, status: 'drafted', next_due_at: null, last_followed_up_at: null, draft_rel: 'logs/resumes/../../../secret.md' } })],
3629
+ ]) {
3630
+ const badLedgerCheck = validateApplicationLedger([mutator(validBaseRec)]);
3631
+ assert.equal(badLedgerCheck.valid, false, `Expected validateApplicationLedger to reject: ${label}`);
3632
+ }
3633
+
3634
+ // Lifecycle write functions must reject unsafe relative paths before mutating ledger
3635
+ for (const badPath of ['../secret.png', '/etc/passwd', 'C:\\Windows\\win.ini', '\\\\server\\share\\a.png', 'logs/resumes/cv-client/shot.png']) {
3636
+ assert.throws(
3637
+ () => recordApplication(work, { job_id: 'gh:sec04-1', company: 'Acme', title: 'Engineer', status: 'discovered', screenshot: badPath }, { home, nowIso, sourceRoot: REPO_ROOT }),
3638
+ /relative path|traversal|third-party|outside workspace/i,
3639
+ );
3640
+ }
3641
+
3642
+ // Legitimate record + reserve + confirm + transition with safe relative paths succeeds
3643
+ const recOk = recordApplication(work, {
3644
+ job_id: 'gh:sec04-1',
3645
+ company: 'AcmeSafe',
3646
+ title: 'Staff Engineer',
3647
+ platform: 'greenhouse',
3648
+ status: 'prepared',
3649
+ screenshot: 'logs/screenshots/gh-sec04-1.png',
3650
+ }, { home, nowIso, sourceRoot: REPO_ROOT });
3651
+ assert.equal(recOk.record.screenshot, 'logs/screenshots/gh-sec04-1.png');
3652
+
3653
+ reserveApplicationSubmission(work, { job_id: 'gh:sec04-1', company: 'AcmeSafe', title: 'Staff Engineer', platform: 'greenhouse' }, { home, nowIso, sourceRoot: REPO_ROOT });
3654
+ assert.throws(
3655
+ () => confirmApplicationSubmission(work, { job_id: 'gh:sec04-1', receipt: 'Application received', screenshot: '../escape.png' }, { home, nowIso }),
3656
+ /relative path|traversal/i,
3657
+ );
3658
+ confirmApplicationSubmission(work, {
3659
+ job_id: 'gh:sec04-1',
3660
+ receipt: 'Application received',
3661
+ screenshot: 'logs/screenshots/gh-sec04-1-confirmed.png',
3662
+ }, { home, nowIso });
3663
+
3664
+ for (const badRel of ['../escape.md', '/etc/passwd', 'C:\\Windows\\System32\\drivers\\etc\\hosts', '\\\\server\\share\\file', 'logs/resumes/cv-client/doc.md']) {
3665
+ assert.throws(
3666
+ () => transitionApplicationStage(work, {
3667
+ job_id: 'gh:sec04-1',
3668
+ to_status: 'interview',
3669
+ interview: { stage: 'technical_screen', status: 'scheduled', dossier_rel: badRel },
3670
+ }, { home, nowIso }),
3671
+ /relative path|traversal|third-party|outside workspace/i,
3672
+ );
3673
+ assert.throws(
3674
+ () => transitionApplicationStage(work, {
3675
+ job_id: 'gh:sec04-1',
3676
+ to_status: 'assessment',
3677
+ assessment: { type: 'take_home', status: 'assigned', blueprint_rel: badRel },
3678
+ }, { home, nowIso }),
3679
+ /relative path|traversal|third-party|outside workspace/i,
3680
+ );
3681
+ assert.throws(
3682
+ () => transitionApplicationStage(work, {
3683
+ job_id: 'gh:sec04-1',
3684
+ to_status: 'applied',
3685
+ follow_up: { status: 'drafted', draft_rel: badRel },
3686
+ }, { home, nowIso }),
3687
+ /relative path|traversal|third-party|outside workspace/i,
3688
+ );
3689
+ }
3690
+
3691
+ // 10 & 11. CLI reader commands (audit, verify, pre-submit --draft, verify --facts) reject outside-workspace paths and traversal
3692
+ const outsideFile = path.join(outsideDir, 'outside-resume.md');
3693
+ fs.writeFileSync(outsideFile, '# Secret Outside File\n- Built systems reducing latency by 40%.\n');
3694
+
3695
+ const rAuditOutside = runCli(['audit', outsideFile], { cwd: work, home });
3696
+ assert.notEqual(rAuditOutside.status, 0, 'audit must reject file outside workspace');
3697
+ assert.match(rAuditOutside.stderr, /outside workspace boundary/i);
3698
+
3699
+ const rAuditTraversal = runCli(['audit', '../outside-secret/outside-resume.md'], { cwd: work, home });
3700
+ assert.notEqual(rAuditTraversal.status, 0, 'audit must reject ../ traversal');
3701
+ assert.match(rAuditTraversal.stderr, /traversal|outside workspace/i);
3702
+
3703
+ const rVerifyOutside = runCli(['verify', outsideFile], { cwd: work, home });
3704
+ assert.notEqual(rVerifyOutside.status, 0, 'verify must reject file outside workspace');
3705
+ assert.match(rVerifyOutside.stderr, /outside workspace boundary/i);
3706
+
3707
+ const insideResume = path.join(work, 'logs', 'resumes', 'safe-pkg', 'resume.txt');
3708
+ fs.mkdirSync(path.dirname(insideResume), { recursive: true });
3709
+ fs.writeFileSync(insideResume, 'Alex Rivera\nSenior Engineer building Node.js services reducing latency by 38%.');
3710
+
3711
+ const rVerifyOutsideFacts = runCli(['verify', insideResume, '--facts', outsideFile], { cwd: work, home });
3712
+ assert.notEqual(rVerifyOutsideFacts.status, 0, 'verify --facts must reject facts file outside workspace');
3713
+ assert.match(rVerifyOutsideFacts.stderr, /outside workspace boundary/i);
3714
+
3715
+ const rPreSubmitOutside = runCli(['pre-submit', '--draft', outsideFile], { cwd: work, home });
3716
+ assert.notEqual(rPreSubmitOutside.status, 0, 'pre-submit --draft must reject draft file outside workspace');
3717
+ assert.match(rPreSubmitOutside.stderr, /outside workspace boundary/i);
3718
+
3719
+ const rPreSubmitUNC = runCli(['pre-submit', '--draft', '\\\\server\\share\\draft.md'], { cwd: work, home });
3720
+ assert.notEqual(rPreSubmitUNC.status, 0, 'pre-submit --draft must reject UNC path');
3721
+ assert.match(rPreSubmitUNC.stderr, /Refusing UNC/i);
3722
+
3723
+ // Legitimate in-workspace files succeed for audit, verify, and pre-submit --draft
3724
+ const rVerifyInside = runCli(['verify', 'logs/resumes/safe-pkg/resume.txt'], { cwd: work, home });
3725
+ assert.equal(rVerifyInside.status, 0, rVerifyInside.stderr);
3726
+ const rPreSubmitInside = runCli(['pre-submit', '--draft', 'logs/resumes/safe-pkg/resume.txt'], { cwd: work, home });
3727
+ assert.equal(rPreSubmitInside.status, 0, rPreSubmitInside.stderr);
3728
+
3729
+ // 6 & 7. Symlinked file inside workspace pointing outside & symlinked parent directory inside workspace
3730
+ const symFile = path.join(work, 'logs', 'symlink-resume.md');
3731
+ let symlinkCreated = false;
3732
+ try {
3733
+ fs.symlinkSync(outsideFile, symFile, 'file');
3734
+ symlinkCreated = true;
3735
+ } catch {
3736
+ // Windows without Developer Mode / elevation may disallow file symlinks; test directory junction as fallback
3737
+ }
3738
+ if (symlinkCreated) {
3739
+ const rAuditSym = runCli(['audit', 'logs/symlink-resume.md'], { cwd: work, home });
3740
+ assert.notEqual(rAuditSym.status, 0, 'audit must reject symlinked file');
3741
+ assert.match(rAuditSym.stderr, /symbolic-link/i);
3742
+
3743
+ const rVerifySym = runCli(['verify', 'logs/symlink-resume.md'], { cwd: work, home });
3744
+ assert.notEqual(rVerifySym.status, 0, 'verify must reject symlinked file');
3745
+ assert.match(rVerifySym.stderr, /symbolic-link/i);
3746
+
3747
+ const rPreSym = runCli(['pre-submit', '--draft', 'logs/symlink-resume.md'], { cwd: work, home });
3748
+ assert.notEqual(rPreSym.status, 0, 'pre-submit must reject symlinked draft');
3749
+ assert.match(rPreSym.stderr, /symbolic-link/i);
3750
+ }
3751
+
3752
+ const symDir = path.join(work, 'logs', 'symlink-dir');
3753
+ let dirLinkCreated = false;
3754
+ try {
3755
+ fs.symlinkSync(outsideDir, symDir, process.platform === 'win32' ? 'junction' : 'dir');
3756
+ dirLinkCreated = true;
3757
+ } catch {
3758
+ // ignore if OS blocks symlink/junction creation
3759
+ }
3760
+ if (dirLinkCreated) {
3761
+ const rVerifySymDir = runCli(['verify', 'logs/symlink-dir'], { cwd: work, home });
3762
+ assert.notEqual(rVerifySymDir.status, 0, 'verify must reject symlinked/junction directory');
3763
+ assert.match(rVerifySymDir.stderr, /symbolic-link/i);
3764
+
3765
+ const rAuditViaSymParent = runCli(['audit', 'logs/symlink-dir/outside-resume.md'], { cwd: work, home });
3766
+ assert.notEqual(rAuditViaSymParent.status, 0, 'audit must reject file under symlinked parent directory');
3767
+ assert.match(rAuditViaSymParent.stderr, /symbolic-link/i);
3768
+
3769
+ assert.throws(
3770
+ () => recordApplication(work, {
3771
+ job_id: 'gh:sec04-sym',
3772
+ company: 'SymCo',
3773
+ title: 'Engineer',
3774
+ status: 'discovered',
3775
+ screenshot: 'logs/symlink-dir/outside-resume.md',
3776
+ }, { home, nowIso, sourceRoot: REPO_ROOT }),
3777
+ /symbolic-link/i,
3778
+ );
3779
+ fs.rmSync(symDir, { recursive: true, force: true });
3780
+ }
3781
+ if (symlinkCreated) {
3782
+ fs.rmSync(symFile, { force: true });
3783
+ }
3784
+ } finally {
3785
+ fs.rmSync(dir, { recursive: true, force: true });
3786
+ }
3787
+ });
3788
+
3789
+ // ===========================================================================
3790
+ // Test 20b: SEC-04 Closure — F-02 (remove arbitrary outside evals/fixtures bypass),
3791
+ // F-06 (validateCvVersionsRegistry local_ref_rel), F-10 (cmdEval --file & ADS)
3792
+ // ===========================================================================
3793
+ test('20b. SEC-04 closure: blocks F-02 outside evals/fixtures bypass, F-06 unsafe registry local_ref_rel, and F-10 eval --file/ADS', () => {
3794
+ const { dir, home, work } = makeTempWorkspace('veycraft-sec04-closure-');
3795
+ const outsideDir = path.join(dir, 'outside-spoofed');
3796
+ const outsideFixtures = path.join(outsideDir, 'evals', 'fixtures');
3797
+ fs.mkdirSync(outsideFixtures, { recursive: true });
3798
+ fs.mkdirSync(path.join(work, 'logs', 'resumes', 'safe-pkg'), { recursive: true });
3799
+
3800
+ try {
3801
+ // F-02: Outside directory containing a spoofed evals/fixtures/ground-truth.json MUST NOT be trusted
3802
+ const spoofedGt = path.join(outsideFixtures, 'ground-truth.json');
3803
+ const spoofedDoc = path.join(outsideFixtures, 'secret-outside.md');
3804
+ fs.writeFileSync(spoofedGt, JSON.stringify({ ground_truth_metrics: ['38%'], forbidden_skills: [] }));
3805
+ fs.writeFileSync(spoofedDoc, '# Outside Secret\n- Improved latency by 38%.\n');
3806
+
3807
+ const safeInside = path.join(work, 'logs', 'resumes', 'safe-pkg', 'resume.txt');
3808
+ fs.writeFileSync(safeInside, 'Alex Rivera\nBuilt Node.js services improving latency by 38%.');
3809
+
3810
+ for (const [label, args] of [
3811
+ ['audit outside evals/fixtures', ['audit', spoofedDoc]],
3812
+ ['verify outside evals/fixtures', ['verify', spoofedDoc]],
3813
+ ['verify --facts outside evals/fixtures', ['verify', safeInside, '--facts', spoofedGt]],
3814
+ ['pre-submit --draft outside evals/fixtures', ['pre-submit', '--draft', spoofedDoc]],
3815
+ ]) {
3816
+ const res = runCli(args, { cwd: work, home });
3817
+ assert.notEqual(res.status, 0, `${label} must be rejected`);
3818
+ assert.match(res.stderr, /outside workspace boundary/i, `${label} must report boundary error`);
3819
+ }
3820
+
3821
+ // Legitimate in-workspace file and legitimate SOURCE/evals/fixtures/ground-truth.json remain allowed
3822
+ const legitVerify = runCli(['verify', 'logs/resumes/safe-pkg/resume.txt', '--facts', path.join(REPO_ROOT, 'evals', 'fixtures', 'ground-truth.json')], { cwd: work, home });
3823
+ assert.equal(legitVerify.status, 0, legitVerify.stdout + legitVerify.stderr);
3824
+
3825
+ // F-06: validateCvVersionsRegistry rejects traversal, absolute, drive, UNC, and mixed-separator unsafe local_ref_rel
3826
+ const nowIso = '2026-07-10T12:00:00Z';
3827
+ const makeReg = ref => ({
3828
+ schema_version: '1.0',
3829
+ updated_at: nowIso,
3830
+ versions: [{
3831
+ cv_version_id: 'cv-ref-test',
3832
+ version_number: 1,
3833
+ label: 'Ref Test',
3834
+ kind: 'generic',
3835
+ owner_scope: 'owner',
3836
+ base_cv_version_id: null,
3837
+ content_sha256: '1'.repeat(64),
3838
+ local_ref_rel: ref,
3839
+ created_at: nowIso,
3840
+ application_ids: [],
3841
+ }],
3842
+ });
3843
+ for (const badRef of [
3844
+ '../../../etc/passwd',
3845
+ '/etc/passwd',
3846
+ 'C:\\Windows\\win.ini',
3847
+ '\\\\server\\share\\cv.html',
3848
+ 'logs\\resumes\\..\\..\\secret.html',
3849
+ 'logs/resumes/./cv-alice/resume.html',
3850
+ 'logs/resumes/cv.html:ads',
3851
+ ]) {
3852
+ assert.equal(validateCvVersionsRegistry(makeReg(badRef)).valid, false, `Registry must reject unsafe local_ref_rel: ${badRef}`);
3853
+ }
3854
+ assert.equal(validateCvVersionsRegistry(makeReg('context/cv.md')).valid, true);
3855
+ assert.equal(validateCvVersionsRegistry(makeReg('logs/resumes/2026-07-10-acme/resume.html')).valid, true);
3856
+ const validTpReg = makeReg('logs/resumes/cv-client/resume.html');
3857
+ validTpReg.versions[0].owner_scope = 'third_party';
3858
+ assert.equal(validateCvVersionsRegistry(validTpReg).valid, true);
3859
+
3860
+ // F-10: ADS rejection in validateSafeWorkspaceRelativePath & CLI assertSafeCliInputPath + cmdEval --file boundary & symlink safety
3861
+ assert.equal(isSafeWorkspaceRelativePath('logs/file.md:ads'), false);
3862
+ assert.equal(isSafeWorkspaceRelativePath('logs/file.md:Zone.Identifier'), false);
3863
+ assert.equal(isSafeWorkspaceRelativePath('logs/2026-07-10-acme/resume.md'), true);
3864
+
3865
+ const rAdsAudit = runCli(['audit', 'logs/resumes/safe-pkg/resume.txt:ads'], { cwd: work, home });
3866
+ assert.notEqual(rAdsAudit.status, 0);
3867
+ assert.match(rAdsAudit.stderr, /alternate data stream|colon/i);
3868
+
3869
+ const outsideEvalJson = path.join(outsideDir, 'external-eval.json');
3870
+ fs.writeFileSync(outsideEvalJson, JSON.stringify({ jd_evaluations: {} }));
3871
+ const rEvalOutside = runCli(['eval', '--file', outsideEvalJson], { cwd: work, home });
3872
+ assert.notEqual(rEvalOutside.status, 0, 'eval --file must reject outside-workspace path');
3873
+ assert.match(rEvalOutside.stderr, /outside workspace boundary/i);
3874
+
3875
+ const rEvalTraversal = runCli(['eval', '--file', '../outside-spoofed/external-eval.json'], { cwd: work, home });
3876
+ assert.notEqual(rEvalTraversal.status, 0, 'eval --file must reject ../ traversal');
3877
+ assert.match(rEvalTraversal.stderr, /traversal/i);
3878
+
3879
+ // Symlink / junction parent refusal on eval --file
3880
+ const evalJunc = path.join(work, 'logs', 'eval-junc');
3881
+ let juncCreated = false;
3882
+ try {
3883
+ fs.symlinkSync(outsideDir, evalJunc, process.platform === 'win32' ? 'junction' : 'dir');
3884
+ juncCreated = true;
3885
+ } catch { /* ignore if OS forbids links */ }
3886
+ if (juncCreated) {
3887
+ const rEvalJunc = runCli(['eval', '--file', 'logs/eval-junc/external-eval.json'], { cwd: work, home });
3888
+ assert.notEqual(rEvalJunc.status, 0, 'eval --file must reject symlinked/junction parent directory');
3889
+ assert.match(rEvalJunc.stderr, /symbolic-link/i);
3890
+ fs.rmSync(evalJunc, { recursive: true, force: true });
3891
+ }
3892
+
3893
+ // Valid in-workspace eval JSON still works cleanly
3894
+ const insideEvalJson = path.join(work, 'logs', 'valid-eval.json');
3895
+ fs.copyFileSync(path.join(REPO_ROOT, 'evals', 'results', 'baseline-verified-run.json'), insideEvalJson);
3896
+ const rEvalInside = runCli(['eval', '--file', 'logs/valid-eval.json'], { cwd: work, home });
3897
+ assert.equal(rEvalInside.status, 0, rEvalInside.stdout + rEvalInside.stderr);
3898
+ } finally {
3899
+ fs.rmSync(dir, { recursive: true, force: true });
3900
+ }
3901
+ });
3902
+
3903
+ // ===========================================================================
3904
+ // Test 21: SEC-01 — SSRF Guard Bypass & Redirect Validation
3905
+ // ===========================================================================
3906
+ test('21. SEC-01: SSRF guard blocks IPv4/IPv6 private, loopback, link-local, CGNAT, IPv4-compatible/mapped/NAT64/6to4, and unsafe redirects', async () => {
3907
+ // 1-9. Direct URL classification across IPv4, IPv6, and alternate encodings
3908
+ const blockedUrls = [
3909
+ // 1. IPv4 loopback
3910
+ 'http://127.0.0.1/admin',
3911
+ 'http://127.255.255.254:8080/internal',
3912
+ // 2. IPv4 private RFC1918
3913
+ 'http://10.0.0.1/secret',
3914
+ 'http://172.16.0.1/secret',
3915
+ 'http://172.31.255.255/secret',
3916
+ 'http://192.168.1.1/secret',
3917
+ // 3. IPv4 link-local / cloud metadata
3918
+ 'http://169.254.169.254/latest/meta-data/',
3919
+ 'http://169.254.0.1/status',
3920
+ // 4. Carrier-grade NAT 100.64.0.0/10
3921
+ 'http://100.64.0.1/cgnat',
3922
+ 'http://100.100.100.200/latest/meta-data/',
3923
+ 'http://100.127.255.254/cgnat',
3924
+ // 5. IPv4-mapped IPv6
3925
+ 'http://[::ffff:127.0.0.1]/',
3926
+ 'http://[::ffff:169.254.169.254]/latest/meta-data/',
3927
+ 'http://[::ffff:100.64.0.1]/',
3928
+ 'http://[0:0:0:0:0:ffff:10.0.0.1]/',
3929
+ // 6. IPv4-compatible IPv6
3930
+ 'http://[::127.0.0.1]/',
3931
+ 'http://[::169.254.169.254]/latest/meta-data/',
3932
+ 'http://[::10.0.0.1]/',
3933
+ 'http://[::192.168.0.1]/',
3934
+ 'http://[::100.64.1.1]/',
3935
+ // 7. IPv6 loopback (canonical & expanded)
3936
+ 'http://[::1]/',
3937
+ 'http://[0:0:0:0:0:0:0:1]/',
3938
+ 'http://[0000:0000:0000:0000:0000:0000:0000:0001]/',
3939
+ // 8. IPv6 unspecified, unique-local, link-local, site-local, multicast, NAT64, 6to4
3940
+ 'http://[::]/',
3941
+ 'http://[0:0:0:0:0:0:0:0]/',
3942
+ 'http://[fc00::1]/',
3943
+ 'http://[fd12:3456:789a::1]/',
3944
+ 'http://[fe80::1]/',
3945
+ 'http://[fe80::1%25eth0]/',
3946
+ 'http://[fec0::1]/',
3947
+ 'http://[ff02::1]/',
3948
+ 'http://[64:ff9b::127.0.0.1]/',
3949
+ 'http://[64:ff9b::169.254.169.254]/',
3950
+ 'http://[2002:7f00:0001::1]/',
3951
+ 'http://[2002:a9fe:a9fe::1]/',
3952
+ // 9. Alternate URL forms, decimal/octal/hex normalized by WHATWG URL, credentials, internal domains, non-HTTP
3953
+ 'http://2130706433/', // 127.0.0.1 decimal
3954
+ 'http://0x7f000001/', // 127.0.0.1 hex
3955
+ 'http://0177.0.0.1/', // 127.0.0.1 octal
3956
+ 'http://0.0.0.0/',
3957
+ 'http://localhost:3000/',
3958
+ 'http://api.localhost/',
3959
+ 'http://service.local/',
3960
+ 'http://metadata.google.internal/computeMetadata/v1/',
3961
+ 'http://user:pass@example.com/private',
3962
+ 'ftp://example.com/file',
3963
+ 'file:///etc/passwd',
3964
+ ];
3965
+
3966
+ for (const raw of blockedUrls) {
3967
+ const reason = isBlockedSsrfUrl(raw);
3968
+ assert.ok(reason !== null, `Expected SSRF guard to block "${raw}", but got null`);
3969
+ }
3970
+
3971
+ // 14. Safe public destinations remain permitted
3972
+ const allowedUrls = [
3973
+ 'https://github.com/redasalem/veycraft',
3974
+ 'https://boards.greenhouse.io/acme/jobs/12345',
3975
+ 'https://jobs.lever.co/acme/11111111-2222-3333-4444-555555555555',
3976
+ 'https://93.184.216.34/jobs', // public IPv4
3977
+ 'https://100.63.255.254/public', // just below 100.64.0.0/10
3978
+ 'https://100.128.0.1/public', // just above 100.64.0.0/10
3979
+ 'https://[2606:4700:4700::1111]/', // public IPv6
3980
+ ];
3981
+ for (const raw of allowedUrls) {
3982
+ assert.equal(isBlockedSsrfUrl(raw), null, `Expected safe public URL "${raw}" to be allowed`);
3983
+ }
3984
+
3985
+ // Helper to build synthetic mock fetch responses without any network traffic
3986
+ const makeResp = (status, location = null) => ({
3987
+ status,
3988
+ headers: {
3989
+ get(name) {
3990
+ return String(name).toLowerCase() === 'location' ? location : null;
3991
+ },
3992
+ },
3993
+ });
3994
+ const mockPublicDns = async () => [{ address: '93.184.216.34', family: 4 }];
3995
+
3996
+ // 10. Public URL redirecting (302) to private/loopback/metadata address -> blocked before redirect request is issued
3997
+ const calls10 = [];
3998
+ const mockFetch10 = async (url, opts) => {
3999
+ calls10.push({ url, redirect: opts.redirect });
4000
+ if (url === 'https://jobs.example.com/apply') {
4001
+ return makeResp(302, 'http://169.254.169.254/latest/meta-data/iam/security-credentials/');
4002
+ }
4003
+ throw new Error(`Unexpected network call to ${url}`);
4004
+ };
4005
+ await assert.rejects(
4006
+ () => fetchUrlWithSafeRedirects('https://jobs.example.com/apply', { fetchImpl: mockFetch10, lookupImpl: mockPublicDns }),
4007
+ /Redirect target blocked by SSRF guard/i,
4008
+ );
4009
+ assert.equal(calls10.length, 1, 'Must never issue fetch request to blocked redirect target');
4010
+ assert.equal(calls10[0].redirect, 'manual');
4011
+
4012
+ // 11. Multi-hop redirect ending in blocked address ([::127.0.0.1] and 100.64.0.1)
4013
+ const calls11 = [];
4014
+ const mockFetch11 = async url => {
4015
+ calls11.push(url);
4016
+ if (url === 'https://short.example.com/1') return makeResp(301, 'https://careers.example.org/2');
4017
+ if (url === 'https://careers.example.org/2') return makeResp(307, 'http://[::127.0.0.1]:8080/internal');
4018
+ throw new Error(`Unexpected call to ${url}`);
4019
+ };
4020
+ await assert.rejects(
4021
+ () => fetchUrlWithSafeRedirects('https://short.example.com/1', { fetchImpl: mockFetch11, lookupImpl: mockPublicDns }),
4022
+ /Redirect target blocked by SSRF guard/i,
4023
+ );
4024
+ assert.equal(calls11.length, 2);
4025
+
4026
+ // 12a. Redirect loop detection
4027
+ const mockFetchLoop = async url => {
4028
+ if (url === 'https://loop.example.com/a') return makeResp(302, 'https://loop.example.com/b');
4029
+ if (url === 'https://loop.example.com/b') return makeResp(302, 'https://loop.example.com/a');
4030
+ return makeResp(200);
4031
+ };
4032
+ await assert.rejects(
4033
+ () => fetchUrlWithSafeRedirects('https://loop.example.com/a', { fetchImpl: mockFetchLoop, lookupImpl: mockPublicDns }),
4034
+ /Redirect loop detected/i,
4035
+ );
4036
+
4037
+ // 12b. Excessive redirect hops
4038
+ const mockFetchExcessive = async url => {
4039
+ const m = url.match(/\/hop-(\d+)$/);
4040
+ const n = m ? Number(m[1]) : 0;
4041
+ return makeResp(302, `https://hops.example.com/hop-${n + 1}`);
4042
+ };
4043
+ await assert.rejects(
4044
+ () => fetchUrlWithSafeRedirects('https://hops.example.com/hop-0', { fetchImpl: mockFetchExcessive, lookupImpl: mockPublicDns, maxRedirects: 3 }),
4045
+ /Maximum redirect limit \(3\) exceeded/i,
4046
+ );
4047
+
4048
+ // 13. Missing or malformed redirect Location header
4049
+ await assert.rejects(
4050
+ () => fetchUrlWithSafeRedirects('https://badloc.example.com/missing', {
4051
+ fetchImpl: async () => makeResp(302, null),
4052
+ lookupImpl: mockPublicDns,
4053
+ }),
4054
+ /missing Location header/i,
4055
+ );
4056
+ await assert.rejects(
4057
+ () => fetchUrlWithSafeRedirects('https://badloc.example.com/bad', {
4058
+ fetchImpl: async () => makeResp(302, 'http://[::invalid-ipv6'),
4059
+ lookupImpl: mockPublicDns,
4060
+ }),
4061
+ /Malformed redirect Location/i,
4062
+ );
4063
+
4064
+ // 14b. Safe multi-hop public redirect succeeds
4065
+ const safeRes = await fetchUrlWithSafeRedirects('https://jobs.example.com/start', {
4066
+ fetchImpl: async url => {
4067
+ if (url === 'https://jobs.example.com/start') return makeResp(301, '/roles/backend');
4068
+ if (url === 'https://jobs.example.com/roles/backend') return makeResp(200);
4069
+ throw new Error(`Unexpected URL ${url}`);
4070
+ },
4071
+ lookupImpl: mockPublicDns,
4072
+ });
4073
+ assert.equal(safeRes.response.status, 200);
4074
+ assert.equal(safeRes.finalUrl, 'https://jobs.example.com/roles/backend');
4075
+ assert.equal(safeRes.redirects, 1);
4076
+ });
4077
+
4078
+ // ===========================================================================
4079
+ // Test 21b: SEC-01 Closure — F-03 (DNS resolution / DNS rebinding / pinned IP)
4080
+ // and F-08 (trailing dots, Teredo 2001:0000::/32, discard 100::/64, TEST-NET)
4081
+ // ===========================================================================
4082
+ test('21b. SEC-01 closure: F-03 DNS resolution & rebinding defense + F-08 trailing dots, Teredo, discard & TEST-NET blocks', async () => {
4083
+ // F-08: Trailing dots, Teredo, IPv6 discard, and RFC 5737 TEST-NET ranges
4084
+ const f08Blocked = [
4085
+ 'http://localhost../',
4086
+ 'http://localhost.../',
4087
+ 'http://api.localhost../',
4088
+ 'http://service.local../',
4089
+ 'http://[2001:0000:4136:e378:8000:63bf:80ff:fffe]/', // Teredo 2001:0000::/32
4090
+ 'http://[2001:0:4136:e378::1]/',
4091
+ 'http://[100::1]/', // RFC 6666 discard 100::/64
4092
+ 'http://192.0.2.1/', // TEST-NET-1
4093
+ 'http://198.51.100.1/', // TEST-NET-2
4094
+ 'http://203.0.113.1/', // TEST-NET-3
4095
+ ];
4096
+ for (const u of f08Blocked) {
4097
+ assert.ok(isBlockedSsrfUrl(u) !== null, `F-08 expected SSRF guard to block "${u}"`);
4098
+ }
4099
+ assert.equal(isBlockedSsrfUrl('https://93.184.216.34/public'), null);
4100
+ assert.equal(isBlockedSsrfUrl('https://[2606:4700:4700::1111]/public'), null);
4101
+ assert.equal(classifyIpAddress('93.184.216.34'), null);
4102
+ assert.ok(classifyIpAddress('127.0.0.1') !== null);
4103
+ assert.ok(classifyIpAddress('169.254.169.254') !== null);
4104
+ assert.ok(classifyIpAddress('fe80::1') !== null);
4105
+
4106
+ const makeResp = (status, location = null) => ({
4107
+ status,
4108
+ headers: { get: name => (String(name).toLowerCase() === 'location' ? location : null) },
4109
+ });
4110
+
4111
+ // F-03: Hostnames resolving to loopback, RFC1918, metadata, IPv6 loopback/ULA/link-local, or mixed public+private must NEVER reach fetchImpl
4112
+ const dnsCases = [
4113
+ ['loopback IPv4', 'http://127.0.0.1.nip.io/admin', [{ address: '127.0.0.1', family: 4 }]],
4114
+ ['RFC1918 10/8', 'http://intranet.example.com/', [{ address: '10.0.0.15', family: 4 }]],
4115
+ ['RFC1918 172.16/12', 'http://corp.example.com/', [{ address: '172.16.4.2', family: 4 }]],
4116
+ ['RFC1918 192.168/16', 'http://router.example.com/', [{ address: '192.168.1.1', family: 4 }]],
4117
+ ['metadata link-local', 'http://169.254.169.254.nip.io/latest/meta-data/', [{ address: '169.254.169.254', family: 4 }]],
4118
+ ['IPv6 loopback', 'http://v6loop.example.com/', [{ address: '::1', family: 6 }]],
4119
+ ['IPv6 ULA', 'http://v6ula.example.com/', [{ address: 'fd12:3456:789a::1', family: 6 }]],
4120
+ ['IPv6 link-local', 'http://v6ll.example.com/', [{ address: 'fe80::1', family: 6 }]],
4121
+ ['multi-address with 1 private', 'http://dual.example.com/', [{ address: '93.184.216.34', family: 4 }, { address: '10.0.0.1', family: 4 }]],
4122
+ ];
4123
+
4124
+ for (const [label, url, answers] of dnsCases) {
4125
+ let called = false;
4126
+ await assert.rejects(
4127
+ () => fetchUrlWithSafeRedirects(url, {
4128
+ lookupImpl: async () => answers,
4129
+ fetchImpl: async () => {
4130
+ called = true;
4131
+ return makeResp(200);
4132
+ },
4133
+ }),
4134
+ /Blocked by SSRF guard/i,
4135
+ `F-03 must block DNS case: ${label}`,
4136
+ );
4137
+ assert.equal(called, false, `Mock request layer must NEVER be called for ${label}`);
4138
+ }
4139
+
4140
+ // F-03: DNS lookup error fails closed without calling fetchImpl
4141
+ let errCalled = false;
4142
+ await assert.rejects(
4143
+ () => fetchUrlWithSafeRedirects('https://nxdomain.example.invalid/', {
4144
+ lookupImpl: async () => { throw new Error('ENOTFOUND'); },
4145
+ fetchImpl: async () => {
4146
+ errCalled = true;
4147
+ return makeResp(200);
4148
+ },
4149
+ }),
4150
+ /DNS lookup failed/i,
4151
+ );
4152
+ assert.equal(errCalled, false);
4153
+
4154
+ // F-03: Redirect from public hostname to hostname resolving to private/metadata IP must be blocked before 2nd hop request
4155
+ const hopCalls = [];
4156
+ await assert.rejects(
4157
+ () => fetchUrlWithSafeRedirects('https://public-start.example.com/go', {
4158
+ lookupImpl: async host => {
4159
+ if (host === 'public-start.example.com') return [{ address: '93.184.216.34', family: 4 }];
4160
+ if (host === 'rebind-target.example.com') return [{ address: '169.254.169.254', family: 4 }];
4161
+ return [{ address: '93.184.216.34', family: 4 }];
4162
+ },
4163
+ fetchImpl: async url => {
4164
+ hopCalls.push(url);
4165
+ if (url === 'https://public-start.example.com/go') return makeResp(302, 'https://rebind-target.example.com/secret');
4166
+ throw new Error(`Unexpected fetch to ${url}`);
4167
+ },
4168
+ }),
4169
+ /Blocked by SSRF guard/i,
4170
+ );
4171
+ assert.deepEqual(hopCalls, ['https://public-start.example.com/go']);
4172
+
4173
+ // F-03: Multi-hop redirect chain containing prohibited DNS target on hop 3
4174
+ const chainCalls = [];
4175
+ await assert.rejects(
4176
+ () => fetchUrlWithSafeRedirects('https://hop1.example.com/', {
4177
+ lookupImpl: async host => {
4178
+ if (host === 'hop3-private.example.com') return [{ address: '127.0.0.1', family: 4 }];
4179
+ return [{ address: '93.184.216.34', family: 4 }];
4180
+ },
4181
+ fetchImpl: async url => {
4182
+ chainCalls.push(url);
4183
+ if (url === 'https://hop1.example.com/') return makeResp(301, 'https://hop2.example.com/');
4184
+ if (url === 'https://hop2.example.com/') return makeResp(307, 'https://hop3-private.example.com/internal');
4185
+ throw new Error(`Unexpected fetch to ${url}`);
4186
+ },
4187
+ }),
4188
+ /Blocked by SSRF guard/i,
4189
+ );
4190
+ assert.deepEqual(chainCalls, ['https://hop1.example.com/', 'https://hop2.example.com/']);
4191
+
4192
+ // F-03: HEAD-to-GET fallback revalidates DNS (blocks DNS rebinding between HEAD 405 and GET retry)
4193
+ let lookupCount = 0;
4194
+ const fallbackMethods = [];
4195
+ const rebindLookup = async () => {
4196
+ lookupCount++;
4197
+ if (lookupCount === 1) return [{ address: '93.184.216.34', family: 4 }];
4198
+ return [{ address: '127.0.0.1', family: 4 }]; // rebinds on second lookup
4199
+ };
4200
+ const headRes = await fetchUrlWithSafeRedirects('https://rebind-head-get.example.com/profile', {
4201
+ method: 'HEAD',
4202
+ lookupImpl: rebindLookup,
4203
+ fetchImpl: async (_url, opts) => {
4204
+ fallbackMethods.push({ method: opts.method, pinned: opts.resolvedAddresses });
4205
+ return makeResp(405);
4206
+ },
4207
+ });
4208
+ assert.equal(headRes.response.status, 405);
4209
+ assert.deepEqual(headRes.resolvedAddresses, [{ address: '93.184.216.34', family: 4 }]);
4210
+ await assert.rejects(
4211
+ () => fetchUrlWithSafeRedirects('https://rebind-head-get.example.com/profile', {
4212
+ method: 'GET',
4213
+ lookupImpl: rebindLookup,
4214
+ fetchImpl: async (_url, opts) => {
4215
+ fallbackMethods.push({ method: opts.method, pinned: opts.resolvedAddresses });
4216
+ return makeResp(200);
4217
+ },
4218
+ }),
4219
+ /Blocked by SSRF guard/i,
4220
+ );
4221
+ assert.equal(fallbackMethods.length, 1, 'Rebound GET fallback must never reach request layer');
4222
+
4223
+ // F-03: Public hostname with safe addresses succeeds and passes pinned addresses
4224
+ let receivedPinned = null;
4225
+ const okRes = await fetchUrlWithSafeRedirects('https://safe-public.example.com/cv', {
4226
+ method: 'HEAD',
4227
+ lookupImpl: async () => [{ address: '93.184.216.34', family: 4 }, { address: '2606:4700:4700::1111', family: 6 }],
4228
+ fetchImpl: async (_url, opts) => {
4229
+ receivedPinned = opts.resolvedAddresses;
4230
+ return makeResp(200);
4231
+ },
4232
+ });
4233
+ assert.equal(okRes.response.status, 200);
4234
+ assert.deepEqual(receivedPinned, [
4235
+ { address: '93.184.216.34', family: 4 },
4236
+ { address: '2606:4700:4700::1111', family: 6 },
4237
+ ]);
4238
+ const validatedDirect = await resolveAndValidateSsrfHost(new URL('https://93.184.216.34/ok'));
4239
+ assert.deepEqual(validatedDirect, [{ address: '93.184.216.34', family: 4 }]);
4240
+ });
4241
+
4242
+ // ===========================================================================
4243
+ // Test 22: SEC-03 — DOCX Zip Bomb & Decompression DoS Defense
4244
+ // ===========================================================================
4245
+ test('22. SEC-03: hardened extractDocxText enforces input size, entry count, compressed/uncompressed budgets, duplicate/overlapping offsets, and integrity checks', () => {
4246
+ // Helper to construct synthetic ZIP/DOCX buffers with fine-grained control over headers & offsets
4247
+ function buildCustomDocxZip(entries, { eocdEntryCountOverride = null } = {}) {
4248
+ const locals = [];
4249
+ const centrals = [];
4250
+ const offsets = [];
4251
+ let offset = 0;
4252
+
4253
+ for (let i = 0; i < entries.length; i++) {
4254
+ const f = entries[i];
4255
+ const nameBuf = Buffer.from(f.name, 'utf8');
4256
+ const method = f.method ?? 8;
4257
+ const rawData = Buffer.isBuffer(f.rawData) ? f.rawData : Buffer.from(String(f.rawData || ''), 'utf8');
4258
+ const compData = f.compressedData
4259
+ ? f.compressedData
4260
+ : (method === 8 ? zlib.deflateRawSync(rawData) : rawData);
4261
+ const uncompSize = f.declaredUncompressedSize !== undefined ? f.declaredUncompressedSize : rawData.length;
4262
+ const compSize = f.declaredCompressedSize !== undefined ? f.declaredCompressedSize : compData.length;
4263
+
4264
+ let localOffset = offset;
4265
+ if (f.shareLocalOffsetWithIndex !== undefined) {
4266
+ localOffset = offsets[f.shareLocalOffsetWithIndex];
4267
+ } else {
4268
+ const lh = Buffer.alloc(30 + nameBuf.length);
4269
+ lh.writeUInt32LE(0x04034b50, 0);
4270
+ lh.writeUInt16LE(20, 4);
4271
+ lh.writeUInt16LE(f.flags ?? 0, 6);
4272
+ lh.writeUInt16LE(method, 8);
4273
+ lh.writeUInt32LE(0, 14);
4274
+ lh.writeUInt32LE(compSize, 18);
4275
+ lh.writeUInt32LE(uncompSize, 22);
4276
+ lh.writeUInt16LE(nameBuf.length, 26);
4277
+ nameBuf.copy(lh, 30);
4278
+ locals.push(lh, compData);
4279
+ offsets.push(offset);
4280
+ offset += lh.length + compData.length;
4281
+ }
4282
+
4283
+ if (f.customLocalOffset !== undefined) {
4284
+ localOffset = f.customLocalOffset;
4285
+ }
4286
+
4287
+ const cd = Buffer.alloc(46 + nameBuf.length);
4288
+ cd.writeUInt32LE(0x02014b50, 0);
4289
+ cd.writeUInt16LE(20, 4);
4290
+ cd.writeUInt16LE(20, 6);
4291
+ cd.writeUInt16LE(f.flags ?? 0, 8);
4292
+ cd.writeUInt16LE(method, 10);
4293
+ cd.writeUInt32LE(0, 16);
4294
+ cd.writeUInt32LE(compSize, 20);
4295
+ cd.writeUInt32LE(uncompSize, 24);
4296
+ cd.writeUInt16LE(nameBuf.length, 28);
4297
+ cd.writeUInt32LE(localOffset, 42);
4298
+ nameBuf.copy(cd, 46);
4299
+ centrals.push(cd);
4300
+ }
4301
+
4302
+ const cdBuf = Buffer.concat(centrals);
4303
+ const totalCount = eocdEntryCountOverride !== null ? eocdEntryCountOverride : entries.length;
4304
+ const eocd = Buffer.alloc(22);
4305
+ eocd.writeUInt32LE(0x06054b50, 0);
4306
+ eocd.writeUInt16LE(totalCount, 8);
4307
+ eocd.writeUInt16LE(totalCount, 10);
4308
+ eocd.writeUInt32LE(cdBuf.length, 12);
4309
+ eocd.writeUInt32LE(offset, 16);
4310
+ return Buffer.concat([...locals, cdBuf, eocd]);
4311
+ }
4312
+
4313
+ // 1 & 12. Normal valid DOCX + legitimate multi-header/footer DOCX succeed
4314
+ const validMultiPartDocx = buildCustomDocxZip([
4315
+ { name: '[Content_Types].xml', method: 0, rawData: '<Types/>' },
4316
+ { name: 'word/header1.xml', method: 8, rawData: '<w:hdr><w:p><w:t>Alex Rivera Header</w:t></w:p></w:hdr>' },
4317
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:body><w:p><w:t>Senior Backend Engineer building Node.js systems (38% faster).</w:t></w:p></w:body></w:document>' },
4318
+ { name: 'word/footer1.xml', method: 8, rawData: '<w:ftr><w:p><w:t>Page 1 Footer</w:t></w:p></w:ftr>' },
4319
+ ]);
4320
+ const extractedText = extractDocxText(validMultiPartDocx);
4321
+ assert.match(extractedText, /Senior Backend Engineer building Node\.js systems/);
4322
+ assert.match(extractedText, /Alex Rivera Header/);
4323
+ assert.match(extractedText, /Page 1 Footer/);
4324
+
4325
+ // 2. Oversized DOCX input buffer rejected before parsing
4326
+ const tinyValid = buildCustomDocxZip([
4327
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:p><w:t>Valid Text</w:t></w:p></w:document>' },
4328
+ ]);
4329
+ assert.throws(
4330
+ () => extractDocxText(tinyValid, { maxInputBytes: 50 }),
4331
+ /Oversized \.docx file/i,
4332
+ );
4333
+
4334
+ // 3a. Excessive total ZIP central directory entry count
4335
+ const manyEntriesDocx = buildCustomDocxZip([
4336
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:p><w:t>Hello</w:t></w:p></w:document>' },
4337
+ { name: 'word/extra1.xml', method: 0, rawData: '<x/>' },
4338
+ { name: 'word/extra2.xml', method: 0, rawData: '<x/>' },
4339
+ { name: 'word/extra3.xml', method: 0, rawData: '<x/>' },
4340
+ ]);
4341
+ assert.throws(
4342
+ () => extractDocxText(manyEntriesDocx, { maxTotalEntries: 3 }),
4343
+ /Excessive \.docx ZIP entry count/i,
4344
+ );
4345
+
4346
+ // 3b. Excessive accepted word/(document|header*|footer*).xml parts
4347
+ const manyXmlPartsDocx = buildCustomDocxZip([
4348
+ { name: 'word/document.xml', method: 8, rawData: '<w:p><w:t>Body</w:t></w:p>' },
4349
+ { name: 'word/header1.xml', method: 8, rawData: '<w:p><w:t>H1</w:t></w:p>' },
4350
+ { name: 'word/header2.xml', method: 8, rawData: '<w:p><w:t>H2</w:t></w:p>' },
4351
+ { name: 'word/footer1.xml', method: 8, rawData: '<w:p><w:t>F1</w:t></w:p>' },
4352
+ ]);
4353
+ assert.throws(
4354
+ () => extractDocxText(manyXmlPartsDocx, { maxXmlEntries: 2 }),
4355
+ /Excessive \.docx XML document\/header\/footer parts/i,
4356
+ );
4357
+
4358
+ // 4. Oversized compressed entry
4359
+ assert.throws(
4360
+ () => extractDocxText(tinyValid, { maxCompressedEntryBytes: 10 }),
4361
+ /Oversized compressed \.docx entry/i,
4362
+ );
4363
+
4364
+ // 5. Small compressed entry expanding to excessive decompressed output (classic single-entry zip bomb)
4365
+ // Also tests spoofed declaredUncompressedSize (declaring 100 bytes when actual payload inflates to 64 KB)
4366
+ const bombPayload = Buffer.from('<w:document><w:p><w:t>' + 'A'.repeat(65536) + '</w:t></w:p></w:document>', 'utf8');
4367
+ const spoofedBombDocx = buildCustomDocxZip([
4368
+ {
4369
+ name: 'word/document.xml',
4370
+ method: 8,
4371
+ rawData: bombPayload,
4372
+ declaredUncompressedSize: 100, // spoofing a tiny header size
4373
+ },
4374
+ ]);
4375
+ assert.throws(
4376
+ () => extractDocxText(spoofedBombDocx, { maxEntryUncompressedBytes: 4096, maxTotalUncompressedBytes: 8192 }),
4377
+ /Decompression limit exceeded/i,
4378
+ );
4379
+
4380
+ // 5b. Honest declared uncompressed size exceeding per-entry cap rejected before inflate
4381
+ const declaredHugeDocx = buildCustomDocxZip([
4382
+ {
4383
+ name: 'word/document.xml',
4384
+ method: 8,
4385
+ rawData: bombPayload,
4386
+ },
4387
+ ]);
4388
+ assert.throws(
4389
+ () => extractDocxText(declaredHugeDocx, { maxEntryUncompressedBytes: 4096 }),
4390
+ /Oversized uncompressed \.docx entry/i,
4391
+ );
4392
+
4393
+ // 6. Multiple entries whose cumulative uncompressed size exceeds total cap while each entry is individually under per-entry cap
4394
+ const part20k = '<w:p><w:t>' + 'B'.repeat(20000) + '</w:t></w:p>';
4395
+ const cumulativeOverflowDocx = buildCustomDocxZip([
4396
+ { name: 'word/document.xml', method: 8, rawData: part20k },
4397
+ { name: 'word/header1.xml', method: 8, rawData: part20k },
4398
+ { name: 'word/footer1.xml', method: 8, rawData: part20k },
4399
+ ]);
4400
+ assert.throws(
4401
+ () => extractDocxText(cumulativeOverflowDocx, {
4402
+ maxEntryUncompressedBytes: 30000,
4403
+ maxTotalUncompressedBytes: 45000,
4404
+ }),
4405
+ /Cumulative \.docx uncompressed size exceeds/i,
4406
+ );
4407
+
4408
+ // 7a. Duplicate entry names in central directory
4409
+ const duplicateNameDocx = buildCustomDocxZip([
4410
+ { name: 'word/document.xml', method: 8, rawData: '<w:p><w:t>First</w:t></w:p>' },
4411
+ { name: 'word/document.xml', method: 8, rawData: '<w:p><w:t>Second</w:t></w:p>' },
4412
+ ]);
4413
+ assert.throws(
4414
+ () => extractDocxText(duplicateNameDocx),
4415
+ /Duplicate \.docx ZIP entry/i,
4416
+ );
4417
+
4418
+ // 7b & 8. Shared/overlapping local file header offsets (classic non-recursive zip bomb where N central directory headers point to the same compressed stream)
4419
+ const sharedOffsetBombDocx = buildCustomDocxZip([
4420
+ { name: 'word/document.xml', method: 8, rawData: '<w:p><w:t>Shared Bomb Payload</w:t></w:p>' },
4421
+ { name: 'word/header1.xml', method: 8, rawData: '<w:p><w:t>Shared Bomb Payload</w:t></w:p>', shareLocalOffsetWithIndex: 0 },
4422
+ ]);
4423
+ assert.throws(
4424
+ () => extractDocxText(sharedOffsetBombDocx),
4425
+ /overlapping or shared local file header\/data offsets/i,
4426
+ );
4427
+
4428
+ // 9. Truncated ZIP / invalid central directory
4429
+ const truncatedDocx = tinyValid.subarray(0, tinyValid.length - 10);
4430
+ assert.throws(
4431
+ () => extractDocxText(truncatedDocx),
4432
+ /Corrupted \.docx/i,
4433
+ );
4434
+
4435
+ // 10. Malformed compression stream
4436
+ const corruptDeflateDocx = buildCustomDocxZip([
4437
+ {
4438
+ name: 'word/document.xml',
4439
+ method: 8,
4440
+ compressedData: Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff]),
4441
+ declaredUncompressedSize: 50,
4442
+ },
4443
+ ]);
4444
+ assert.throws(
4445
+ () => extractDocxText(corruptDeflateDocx),
4446
+ /Corrupted deflate stream/i,
4447
+ );
4448
+
4449
+ // 11. Boundary-size cases: exact limit succeeds, 1 byte over limit fails closed
4450
+ const boundaryXml = '<w:document><w:p><w:t>ExactBoundaryCheck</w:t></w:p></w:document>';
4451
+ const boundaryLen = Buffer.byteLength(boundaryXml, 'utf8');
4452
+ const boundaryDocx = buildCustomDocxZip([
4453
+ { name: 'word/document.xml', method: 8, rawData: boundaryXml },
4454
+ ]);
4455
+ assert.equal(
4456
+ extractDocxText(boundaryDocx, {
4457
+ maxInputBytes: boundaryDocx.length,
4458
+ maxEntryUncompressedBytes: boundaryLen,
4459
+ maxTotalUncompressedBytes: boundaryLen,
4460
+ }),
4461
+ 'ExactBoundaryCheck',
4462
+ );
4463
+ assert.throws(
4464
+ () => extractDocxText(boundaryDocx, {
4465
+ maxInputBytes: boundaryDocx.length - 1,
4466
+ }),
4467
+ /Oversized \.docx file/i,
4468
+ );
4469
+ assert.throws(
4470
+ () => extractDocxText(boundaryDocx, {
4471
+ maxEntryUncompressedBytes: boundaryLen - 1,
4472
+ }),
4473
+ /Oversized uncompressed \.docx entry/i,
4474
+ );
4475
+ assert.throws(
4476
+ () => extractDocxText(boundaryDocx, {
4477
+ maxEntryUncompressedBytes: boundaryLen,
4478
+ maxTotalUncompressedBytes: boundaryLen - 1,
4479
+ }),
4480
+ /Cumulative \.docx uncompressed size exceeds/i,
4481
+ );
4482
+ });
4483
+
4484
+ // ===========================================================================
4485
+ // Test 22b: SEC-03 Closure — F-07 (pre-read bounded DOCX size limit in audit/verify)
4486
+ // and F-09 (Central Directory gap-overlap rejection & zero-byte deflated XML at budget=0)
4487
+ // ===========================================================================
4488
+ test('22b. SEC-03 closure: F-07 pre-read DOCX size enforcement in audit/verify + F-09 CD gap-overlap & zero-byte inflate edge case', () => {
4489
+ function buildAdvancedZip(entries, { cdPaddingBeforeEocd = 0, dataDescriptor = false } = {}) {
4490
+ const locals = [];
4491
+ const centrals = [];
4492
+ let offset = 0;
4493
+
4494
+ for (const f of entries) {
4495
+ const nameBuf = Buffer.from(f.name, 'utf8');
4496
+ const method = f.method ?? 8;
4497
+ const rawData = Buffer.isBuffer(f.rawData) ? f.rawData : Buffer.from(String(f.rawData || ''), 'utf8');
4498
+ const compData = f.compressedData || (method === 8 ? zlib.deflateRawSync(rawData) : rawData);
4499
+ const flags = f.flags ?? (dataDescriptor ? 0x0008 : 0);
4500
+ const lh = Buffer.alloc(30 + nameBuf.length);
4501
+ lh.writeUInt32LE(0x04034b50, 0);
4502
+ lh.writeUInt16LE(20, 4);
4503
+ lh.writeUInt16LE(flags, 6);
4504
+ lh.writeUInt16LE(method, 8);
4505
+ lh.writeUInt32LE(dataDescriptor ? 0 : compData.length, 18);
4506
+ lh.writeUInt32LE(dataDescriptor ? 0 : rawData.length, 22);
4507
+ lh.writeUInt16LE(nameBuf.length, 26);
4508
+ nameBuf.copy(lh, 30);
4509
+
4510
+ const dd = dataDescriptor ? Buffer.alloc(16) : Buffer.alloc(0);
4511
+ if (dataDescriptor) {
4512
+ dd.writeUInt32LE(0x08074b50, 0);
4513
+ dd.writeUInt32LE(compData.length, 8);
4514
+ dd.writeUInt32LE(rawData.length, 12);
4515
+ }
4516
+ locals.push(lh, compData, dd);
4517
+
4518
+ const cd = Buffer.alloc(46 + nameBuf.length);
4519
+ cd.writeUInt32LE(0x02014b50, 0);
4520
+ cd.writeUInt16LE(20, 4);
4521
+ cd.writeUInt16LE(20, 6);
4522
+ cd.writeUInt16LE(flags, 8);
4523
+ cd.writeUInt16LE(method, 10);
4524
+ cd.writeUInt32LE(f.cdCompSize ?? compData.length, 20);
4525
+ cd.writeUInt32LE(f.cdUncompSize ?? rawData.length, 24);
4526
+ cd.writeUInt16LE(nameBuf.length, 28);
4527
+ cd.writeUInt32LE(offset, 42);
4528
+ nameBuf.copy(cd, 46);
4529
+ centrals.push(cd);
4530
+
4531
+ offset += lh.length + compData.length + dd.length;
4532
+ }
4533
+
4534
+ const cdBuf = Buffer.concat(centrals);
4535
+ const pad = Buffer.alloc(cdPaddingBeforeEocd);
4536
+ const eocd = Buffer.alloc(22);
4537
+ eocd.writeUInt32LE(0x06054b50, 0);
4538
+ eocd.writeUInt16LE(entries.length, 8);
4539
+ eocd.writeUInt16LE(entries.length, 10);
4540
+ eocd.writeUInt32LE(cdBuf.length, 12);
4541
+ eocd.writeUInt32LE(offset, 16);
4542
+ return Buffer.concat([...locals, cdBuf, pad, eocd]);
4543
+ }
4544
+
4545
+ // F-09a: Central Directory gap-overlap (padding before EOCD + local entry data extending past cdStart) MUST be rejected
4546
+ const cdGapOverlapZip = buildAdvancedZip([
4547
+ { name: 'word/document.xml', method: 8, rawData: '<w:p><w:t>Valid</w:t></w:p>' },
4548
+ { name: 'word/other.bin', method: 0, rawData: 'A'.repeat(10), cdCompSize: 60, cdUncompSize: 60 },
4549
+ ], { cdPaddingBeforeEocd: 100 });
4550
+ assert.throws(
4551
+ () => extractDocxText(cdGapOverlapZip),
4552
+ /Truncated or out-of-bounds \.docx entry data/i,
4553
+ );
4554
+
4555
+ // F-09b: Zero-byte deflated XML part when remainingBudget === 0 succeeds (no false positive)
4556
+ const exactDocXml = '<w:p><w:t>ExactBudgetOk</w:t></w:p>';
4557
+ const exactDocLen = Buffer.byteLength(exactDocXml, 'utf8');
4558
+ const zeroByteFooterZip = buildAdvancedZip([
4559
+ { name: 'word/document.xml', method: 8, rawData: exactDocXml },
4560
+ { name: 'word/footer1.xml', method: 8, rawData: '' },
4561
+ ]);
4562
+ assert.equal(
4563
+ extractDocxText(zeroByteFooterZip, { maxTotalUncompressedBytes: exactDocLen }),
4564
+ 'ExactBudgetOk',
4565
+ );
4566
+
4567
+ // Spoofed 0-byte declared entry that actually inflates to >0 bytes when remainingBudget === 0 MUST still fail closed
4568
+ const spoofedZeroFooterZip = buildAdvancedZip([
4569
+ { name: 'word/document.xml', method: 8, rawData: exactDocXml },
4570
+ { name: 'word/footer1.xml', method: 8, rawData: 'X', cdUncompSize: 0 },
4571
+ ]);
4572
+ assert.throws(
4573
+ () => extractDocxText(spoofedZeroFooterZip, { maxTotalUncompressedBytes: exactDocLen }),
4574
+ /Decompression limit exceeded/i,
4575
+ );
4576
+
4577
+ // Existing Data Descriptor (bit 3) compatibility & ordinary DOCX extraction preserved
4578
+ const ddZip = buildAdvancedZip([
4579
+ { name: 'word/', method: 0, rawData: '' },
4580
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:p><w:t>Alex Rivera Data Descriptor Resume 38%</w:t></w:p></w:document>' },
4581
+ { name: 'word/header1.xml', method: 8, rawData: '<w:hdr><w:p><w:t>Header DD</w:t></w:p></w:hdr>' },
4582
+ ], { dataDescriptor: true });
4583
+ const ddText = extractDocxText(ddZip);
4584
+ assert.match(ddText, /Alex Rivera Data Descriptor Resume 38%/);
4585
+ assert.match(ddText, /Header DD/);
4586
+
4587
+ // F-07: Pre-read bounded file reader & CLI audit/verify enforce DOCX_LIMITS.MAX_INPUT_BYTES before full file allocation
4588
+ const { dir, home, work } = makeTempWorkspace('veycraft-sec03-closure-');
4589
+ try {
4590
+ const exactLimitFile = path.join(work, 'logs', 'exact-limit.bin');
4591
+ fs.writeFileSync(exactLimitFile, Buffer.alloc(1024, 0x41));
4592
+ assert.equal(readFileBoundedSync(exactLimitFile, 1024, '.docx file').length, 1024);
4593
+ assert.throws(
4594
+ () => readFileBoundedSync(exactLimitFile, 1023, '.docx file'),
4595
+ /Oversized \.docx file/i,
4596
+ );
4597
+
4598
+ // Sparse oversized file (> DOCX_LIMITS.MAX_INPUT_BYTES) created via ftruncateSync without allocating huge heap buffer
4599
+ const oversizedDocx = path.join(work, 'logs', 'oversized.docx');
4600
+ const fd = fs.openSync(oversizedDocx, 'w');
4601
+ try {
4602
+ fs.writeSync(fd, Buffer.from('PK\x03\x04', 'latin1'));
4603
+ fs.ftruncateSync(fd, DOCX_LIMITS.MAX_INPUT_BYTES + 1);
4604
+ } finally {
4605
+ fs.closeSync(fd);
4606
+ }
4607
+ assert.throws(
4608
+ () => readFileBoundedSync(oversizedDocx, DOCX_LIMITS.MAX_INPUT_BYTES, '.docx file'),
4609
+ /Oversized \.docx file/i,
4610
+ );
4611
+
4612
+ // CLI audit and verify reject oversized .docx via bounded pre-read check
4613
+ const rAuditOver = runCli(['audit', 'logs/oversized.docx'], { cwd: work, home });
4614
+ assert.notEqual(rAuditOver.status, 0, 'audit must reject oversized .docx');
4615
+ assert.match(rAuditOver.stderr, /Oversized \.docx file/i);
4616
+
4617
+ const rVerifyOver = runCli(['verify', 'logs/oversized.docx'], { cwd: work, home });
4618
+ assert.notEqual(rVerifyOver.status, 0, 'verify must reject oversized .docx');
4619
+ assert.match(rVerifyOver.stdout + rVerifyOver.stderr, /Oversized \.docx file/i);
4620
+
4621
+ // Valid ordinary .docx and normal text files continue to pass audit and verify
4622
+ const validDocxPath = path.join(work, 'logs', 'valid.docx');
4623
+ fs.writeFileSync(validDocxPath, ddZip);
4624
+ const rAuditOk = runCli(['audit', 'logs/valid.docx'], { cwd: work, home });
4625
+ assert.equal(rAuditOk.status, 0, rAuditOk.stderr);
4626
+ const rVerifyOk = runCli(['verify', 'logs/valid.docx'], { cwd: work, home });
4627
+ assert.equal(rVerifyOk.status, 0, rVerifyOk.stdout + rVerifyOk.stderr);
4628
+
4629
+ // Exact maximum permitted DOCX size (padded ZIP comment up to DOCX_LIMITS.MAX_INPUT_BYTES) passes readFileBoundedSync + verify
4630
+ const baseZip = buildAdvancedZip([
4631
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:p><w:t>Exact Max Size Resume 38%</w:t></w:p></w:document>' },
4632
+ ]);
4633
+ const exactMaxPadFile = path.join(work, 'logs', 'exact-max.docx');
4634
+ // Put a harmless stored padding entry so total file size equals DOCX_LIMITS.MAX_INPUT_BYTES exactly
4635
+ const padSize = DOCX_LIMITS.MAX_INPUT_BYTES - baseZip.length - (30 + 46 + 'word/pad.bin'.length * 2);
4636
+ const exactMaxZip = buildAdvancedZip([
4637
+ { name: 'word/document.xml', method: 8, rawData: '<w:document><w:p><w:t>Exact Max Size Resume 38%</w:t></w:p></w:document>' },
4638
+ { name: 'word/pad.bin', method: 0, rawData: Buffer.alloc(padSize, 0x20) },
4639
+ ]);
4640
+ assert.equal(exactMaxZip.length, DOCX_LIMITS.MAX_INPUT_BYTES);
4641
+ fs.writeFileSync(exactMaxPadFile, exactMaxZip);
4642
+ const rVerifyExactMax = runCli(['verify', 'logs/exact-max.docx'], { cwd: work, home });
4643
+ assert.equal(rVerifyExactMax.status, 0, rVerifyExactMax.stdout + rVerifyExactMax.stderr);
4644
+ } finally {
4645
+ fs.rmSync(dir, { recursive: true, force: true });
4646
+ }
4647
+ });