veycraft 0.0.0-stage → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,1855 @@
1
+ // Pure, zero-stdout deterministic operations shared by bin/cli.mjs and bin/mcp-server.mjs.
2
+ // Uses Node.js built-in modules and local pure helpers only.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import { validateProfileUpdatePlan, validateProfileVault } from './profile-intelligence.mjs';
7
+ import {
8
+ validateApplicationLedger,
9
+ validateCvVersionsRegistry,
10
+ validateCareerInsights,
11
+ validateDailyRun,
12
+ validateSessionCheckpoint,
13
+ BANNED_AI_CLICHES,
14
+ evaluatePreSubmitGate,
15
+ } from './career-intelligence.mjs';
16
+ import {
17
+ validateNotionSyncPlan,
18
+ verifySyncStateIntegrity,
19
+ } from './notion-sync.mjs';
20
+ import {
21
+ isSamePath,
22
+ isObj,
23
+ isWithinDir,
24
+ refuseSymlink as refuseSymlinkBase,
25
+ writeAtomic as writeAtomicBase,
26
+ readJsonSafe as readJsonSafeBase,
27
+ isBlockedSsrfUrl,
28
+ fetchUrlWithSafeRedirects,
29
+ DOCX_LIMITS,
30
+ readFileBoundedSync,
31
+ extractDocxText,
32
+ decodeXmlHtmlEntities,
33
+ stripHtmlBlocks,
34
+ stripMarkupTags,
35
+ } from './fs-safety.mjs';
36
+
37
+ export const PINNED_SIGNING_PRINCIPAL = '192090175+redasalem@users.noreply.github.com';
38
+ export const PLACEHOLDER_RE = /\b(?:Jane Doe|John Doe|YOUR_NAME|YOUR_EMAIL|your-handle|your-site|replace-with|Acme Fintech|Nile Commerce)\b|(?:example\.com|example\.invalid|reda@example\.com)/i;
39
+ export const SECRET_LEAK_RE = /(ntn_[A-Za-z0-9]{12,}|sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/;
40
+
41
+ export function resolveGlobalRoot(home = os.homedir(), env = process.env, platform = process.platform) {
42
+ const customHome = env.VEYCRAFT_HOME && env.VEYCRAFT_HOME.trim();
43
+ if (customHome) return path.resolve(customHome);
44
+ const primary = path.join(home, '.veycraft');
45
+ const legacy = path.join(home, '.job-hunter-os');
46
+ if (fs.existsSync(primary)) return primary;
47
+ if (fs.existsSync(legacy)) return legacy;
48
+ if (platform === 'linux' && env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME.trim())) {
49
+ return path.join(env.XDG_DATA_HOME.trim(), 'veycraft');
50
+ }
51
+ return primary;
52
+ }
53
+
54
+ export function hasInstallMarker(dir) {
55
+ return (
56
+ fs.existsSync(path.join(dir, '.veycraft-install.json')) ||
57
+ fs.existsSync(path.join(dir, '.job-hunter-install.json'))
58
+ );
59
+ }
60
+
61
+ export function isGlobalRoot(root, home = os.homedir()) {
62
+ const candidates = [
63
+ path.join(home, '.veycraft'),
64
+ path.join(home, '.job-hunter-os'),
65
+ resolveGlobalRoot(home),
66
+ ];
67
+ return candidates.some(c => isSamePath(root, c));
68
+ }
69
+
70
+ export function resolveCodexHome(home = os.homedir(), env = process.env) {
71
+ const custom = env.CODEX_HOME && env.CODEX_HOME.trim();
72
+ return custom ? path.resolve(custom) : path.join(home, '.codex');
73
+ }
74
+
75
+ export function mcpTargetFiles(root, isGlobal, home = os.homedir()) {
76
+ if (isGlobal) {
77
+ return [
78
+ path.join(home, '.claude.json'),
79
+ path.join(home, '.cursor', 'mcp.json'),
80
+ path.join(home, '.gemini', 'antigravity', 'mcp_config.json'),
81
+ path.join(home, '.gemini', 'settings.json'),
82
+ path.join(home, '.codeium', 'windsurf', 'mcp_config.json'),
83
+ path.join(home, '.copilot', 'mcp-config.json'),
84
+ ];
85
+ }
86
+ return [
87
+ path.join(root, '.mcp.json'),
88
+ path.join(root, '.cursor', 'mcp.json'),
89
+ path.join(root, '.gemini', 'settings.json'),
90
+ ];
91
+ }
92
+
93
+ export function codexConfigTomlPath(root, isGlobal, home = os.homedir()) {
94
+ return isGlobal ? path.join(resolveCodexHome(home), 'config.toml') : path.join(root, '.codex', 'config.toml');
95
+ }
96
+
97
+ export function readPackageMeta(root, source) {
98
+ const pkgPath = [path.join(root, 'package.json'), path.join(source, 'package.json')].find(f => fs.existsSync(f));
99
+ let pkg = {};
100
+ if (pkgPath) {
101
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch { /* ignore */ }
102
+ }
103
+ return {
104
+ version: pkg.version || '1.4.1',
105
+ runtimeDeps: Object.keys(pkg.dependencies || {}).length,
106
+ devDeps: Object.keys(pkg.devDependencies || {}).length,
107
+ };
108
+ }
109
+
110
+ export function escapeRegex(str) {
111
+ return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
112
+ }
113
+
114
+ export function buildSkillRegex(skill) {
115
+ const escaped = escapeRegex(skill);
116
+ const left = /^[A-Za-z0-9_]/.test(skill) ? '(?<![A-Za-z0-9_])' : '(?<!\\.)';
117
+ const right = /[A-Za-z0-9_]$/.test(skill) ? '(?![A-Za-z0-9_])' : '(?![A-Za-z0-9_+])';
118
+ return new RegExp(`${left}${escaped}${right}`, 'i');
119
+ }
120
+
121
+ export function hasParentTraversalSegment(rawPath) {
122
+ if (typeof rawPath !== 'string') return true;
123
+ const slashNorm = rawPath.trim().replace(/\\/g, '/');
124
+ return slashNorm.split('/').some(seg => seg === '..');
125
+ }
126
+
127
+ export function assertSafeCliInputPath(rawPath, {
128
+ label = 'file path',
129
+ allowDirectory = false,
130
+ root,
131
+ source,
132
+ home = os.homedir(),
133
+ cwd = process.cwd(),
134
+ } = {}) {
135
+ if (typeof rawPath !== 'string' || !rawPath.trim()) {
136
+ throw new Error(`Invalid ${label}: path must be a non-empty string.`);
137
+ }
138
+ if (/[\x00-\x1f\x7f]/.test(rawPath)) {
139
+ throw new Error(`Refusing ${label} containing control characters.`);
140
+ }
141
+ const trimmed = rawPath.trim();
142
+ if (trimmed.startsWith('\\\\') || trimmed.startsWith('//')) {
143
+ throw new Error(`Refusing UNC or network ${label}: "${rawPath}"`);
144
+ }
145
+ const afterDrive = /^[A-Za-z]:/.test(trimmed) ? trimmed.slice(2) : trimmed;
146
+ if (afterDrive.includes(':')) {
147
+ throw new Error(`Refusing ${label} containing unsafe alternate data stream or colon syntax: "${rawPath}"`);
148
+ }
149
+ if (hasParentTraversalSegment(trimmed)) {
150
+ throw new Error(`Refusing ${label} with ".." parent traversal segments: "${rawPath}"`);
151
+ }
152
+ const cwdResolved = path.resolve(cwd);
153
+ const rootResolved = path.resolve(root);
154
+ const sourceResolved = path.resolve(source);
155
+ const resolved = path.resolve(cwdResolved, trimmed);
156
+
157
+ const allowedRoots = [rootResolved, cwdResolved, sourceResolved];
158
+ for (const b of [rootResolved, cwdResolved, sourceResolved]) {
159
+ for (const fn of [fs.realpathSync, fs.realpathSync?.native].filter(Boolean)) {
160
+ try {
161
+ const rp = fn(b);
162
+ if (rp && !allowedRoots.some(x => isSamePath(x, rp))) {
163
+ allowedRoots.push(rp);
164
+ }
165
+ if (process.platform === 'darwin' && rp.startsWith('/private/')) {
166
+ const alias = rp.slice('/private'.length);
167
+ if (alias && !allowedRoots.some(x => isSamePath(x, alias))) {
168
+ allowedRoots.push(alias);
169
+ }
170
+ }
171
+ } catch { /* ignore */ }
172
+ }
173
+ }
174
+
175
+ let matchedBoundary = allowedRoots.find(b => isWithinDir(resolved, b));
176
+ if (!matchedBoundary) {
177
+ let probe = resolved;
178
+ while (probe && !fs.existsSync(probe)) {
179
+ const parent = path.dirname(probe);
180
+ if (parent === probe) break;
181
+ probe = parent;
182
+ }
183
+ if (probe && fs.existsSync(probe)) {
184
+ let hasSymlinkInChain = false;
185
+ let cursor = probe;
186
+ while (cursor) {
187
+ try {
188
+ if (fs.lstatSync(cursor).isSymbolicLink()) {
189
+ hasSymlinkInChain = true;
190
+ break;
191
+ }
192
+ } catch {
193
+ break;
194
+ }
195
+ const parent = path.dirname(cursor);
196
+ if (parent === cursor) break;
197
+ cursor = parent;
198
+ }
199
+ if (!hasSymlinkInChain) {
200
+ for (const fn of [fs.realpathSync?.native, fs.realpathSync].filter(Boolean)) {
201
+ try {
202
+ const realProbe = fn(probe);
203
+ const relTail = path.relative(probe, resolved);
204
+ const canonicalCandidate = relTail ? path.resolve(realProbe, relTail) : realProbe;
205
+ const realMatched = allowedRoots.find(b => isWithinDir(canonicalCandidate, b));
206
+ if (realMatched) {
207
+ matchedBoundary = probe;
208
+ break;
209
+ }
210
+ } catch { /* ignore */ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+ if (!matchedBoundary) {
216
+ throw new Error(`Refusing ${label} outside workspace boundary: "${rawPath}"`);
217
+ }
218
+
219
+ refuseSymlinkBase(resolved, matchedBoundary, home);
220
+ if (!fs.existsSync(resolved)) {
221
+ return { resolved, boundary: matchedBoundary, exists: false, stat: null };
222
+ }
223
+ const lstat = fs.lstatSync(resolved);
224
+ if (lstat.isSymbolicLink()) {
225
+ throw new Error(`Refusing symbolic-link ${label}: ${resolved}`);
226
+ }
227
+ if (!allowDirectory && !lstat.isFile()) {
228
+ throw new Error(`Expected regular file for ${label}: ${resolved}`);
229
+ }
230
+ if (allowDirectory && !lstat.isFile() && !lstat.isDirectory()) {
231
+ throw new Error(`Expected regular file or directory for ${label}: ${resolved}`);
232
+ }
233
+ return { resolved, boundary: matchedBoundary, exists: true, stat: lstat };
234
+ }
235
+
236
+ export function loadSkillManifest(root, source) {
237
+ const manifestPath = [
238
+ path.join(root, 'skills', 'skills-manifest.json'),
239
+ path.join(source, 'skills', 'skills-manifest.json'),
240
+ ].find(f => fs.existsSync(f));
241
+ if (!manifestPath) {
242
+ throw new Error('skills/skills-manifest.json not found.');
243
+ }
244
+ const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
245
+ if (!isObj(parsed) || !Array.isArray(parsed.skills)) {
246
+ throw new Error('Invalid skills/skills-manifest.json structure.');
247
+ }
248
+ const baseDir = path.dirname(path.dirname(manifestPath));
249
+ return { manifestPath, baseDir, manifest: parsed };
250
+ }
251
+
252
+ export function readSkillByName(name, { root, source, home = os.homedir() } = {}) {
253
+ const trimmed = typeof name === 'string' ? name.trim() : '';
254
+ if (!trimmed) {
255
+ throw new Error('Skill name must be a non-empty string.');
256
+ }
257
+ const { baseDir, manifest } = loadSkillManifest(root, source);
258
+ const entry = manifest.skills.find(s => s && s.name === trimmed);
259
+ if (!entry) {
260
+ throw new Error(`Unknown skill "${trimmed}".`);
261
+ }
262
+ const skillsDir = path.join(baseDir, 'skills');
263
+ const skillPath = path.resolve(baseDir, entry.path);
264
+ if (!isWithinDir(skillPath, skillsDir)) {
265
+ throw new Error(`Refusing skill path outside skills/ directory: ${entry.path}`);
266
+ }
267
+ refuseSymlinkBase(skillPath, baseDir, home);
268
+ if (!fs.existsSync(skillPath) || fs.lstatSync(skillPath).isSymbolicLink() || !fs.lstatSync(skillPath).isFile()) {
269
+ throw new Error(`Skill file missing or invalid: ${entry.path}`);
270
+ }
271
+ const content = fs.readFileSync(skillPath, 'utf8');
272
+ return {
273
+ skill: entry,
274
+ uri: `veycraft://skill/${entry.name}`,
275
+ content,
276
+ };
277
+ }
278
+
279
+ export function isGitPreCommitHookActive(root) {
280
+ const gitDir = path.join(root, '.git');
281
+ try {
282
+ if (!fs.existsSync(gitDir) || !fs.lstatSync(gitDir).isDirectory()) return false;
283
+ const hookFile = path.join(gitDir, 'hooks', 'pre-commit');
284
+ if (!fs.existsSync(hookFile) || fs.lstatSync(hookFile).isSymbolicLink()) return false;
285
+ return fs.lstatSync(hookFile).isFile();
286
+ } catch {
287
+ return false;
288
+ }
289
+ }
290
+
291
+ export function installGitPreCommitHook(root, home = os.homedir()) {
292
+ const gitDir = path.join(root, '.git');
293
+ try {
294
+ if (!fs.existsSync(gitDir) || !fs.lstatSync(gitDir).isDirectory()) return false;
295
+ } catch {
296
+ return false;
297
+ }
298
+ const hookFile = path.join(gitDir, 'hooks', 'pre-commit');
299
+ const marker = '# veycraft pre-commit pii shield';
300
+ const legacyMarker = '# job-hunter-os pre-commit pii shield';
301
+ if (fs.existsSync(hookFile)) {
302
+ try {
303
+ const existing = fs.readFileSync(hookFile, 'utf8');
304
+ if (!existing.includes(marker) && !existing.includes(legacyMarker)) return true;
305
+ } catch {
306
+ return false;
307
+ }
308
+ }
309
+ const script = [
310
+ '#!/usr/bin/env sh',
311
+ marker,
312
+ 'set -e',
313
+ 'STAGED=$(git diff --cached --name-only --diff-filter=ACM || true)',
314
+ 'if [ -z "$STAGED" ]; then exit 0; fi',
315
+ 'for f in $STAGED; do',
316
+ ' case "$f" in',
317
+ ' context/*.example|context/DROP_YOUR_FILES_HERE.md) ;;',
318
+ ' context/*|logs/*|browser-profile/*|*.pdf|.env|.env.*|*.veycraft.bak|.mcp.json|.cursor/mcp.json|.codex/config.toml|.gemini/settings.json|.vscode/mcp.json)',
319
+ ' echo "[veycraft PII Shield] BLOCKED commit of private file: $f" >&2',
320
+ ' exit 1',
321
+ ' ;;',
322
+ ' esac',
323
+ 'done',
324
+ 'if git diff --cached -U0 | grep -E "^\\+.*(ntn_[A-Za-z0-9]{12,}|sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})" >/dev/null 2>&1; then',
325
+ ' echo "[veycraft PII Shield] BLOCKED commit containing an API token signature (ntn_ / sk- / ghp_)." >&2',
326
+ ' exit 1',
327
+ 'fi',
328
+ 'exit 0',
329
+ '',
330
+ ].join('\n');
331
+ writeAtomicBase(hookFile, script, { preserve: false, mode: 0o755, boundary: root, home });
332
+ return true;
333
+ }
334
+
335
+ export function isPopulated(root, relPath) {
336
+ const file = path.join(root, relPath);
337
+ if (!fs.existsSync(file)) return { exists: false, ready: false };
338
+ const text = fs.readFileSync(file, 'utf8');
339
+ const ex = path.join(root, `${relPath}.example`);
340
+ const sameAsEx = fs.existsSync(ex) && text === fs.readFileSync(ex, 'utf8');
341
+ const ready = text.trim().length > 20 && !sameAsEx && !PLACEHOLDER_RE.test(text);
342
+ return { exists: true, ready };
343
+ }
344
+
345
+ export function extractProfileUrls(root) {
346
+ const urls = new Set();
347
+ for (const rel of ['context/profile.md', 'context/resume-data.json']) {
348
+ const f = path.join(root, rel);
349
+ if (!fs.existsSync(f)) continue;
350
+ const text = fs.readFileSync(f, 'utf8');
351
+ const matches = text.match(/https?:\/\/[^\s)"'>\],]+/gi) || [];
352
+ for (const raw of matches) {
353
+ const cleaned = raw.replace(/[.;:]+$/, '');
354
+ if (cleaned) urls.add(cleaned);
355
+ }
356
+ }
357
+ return [...urls];
358
+ }
359
+
360
+ export async function verifyProfileLinks(root, isProfileReady, { offline = false } = {}) {
361
+ const urls = extractProfileUrls(root);
362
+ if (!urls.length) {
363
+ return { validSyntax: 0, placeholderCount: 0, deadUrls: [], checkedReachable: 0, total: 0 };
364
+ }
365
+ let validSyntax = 0;
366
+ let placeholderCount = 0;
367
+ let checkedReachable = 0;
368
+ const deadUrls = [];
369
+
370
+ for (const u of urls) {
371
+ let parsed;
372
+ try {
373
+ parsed = new URL(u);
374
+ validSyntax++;
375
+ } catch {
376
+ deadUrls.push(`${u} (malformed URL)`);
377
+ continue;
378
+ }
379
+ const ssrfReason = isBlockedSsrfUrl(parsed);
380
+ if (ssrfReason) {
381
+ deadUrls.push(`${u} (blocked by SSRF guard: ${ssrfReason})`);
382
+ continue;
383
+ }
384
+ if (PLACEHOLDER_RE.test(u) || /example\.|your-handle|your-site/i.test(parsed.hostname)) {
385
+ placeholderCount++;
386
+ continue;
387
+ }
388
+ if (!offline && isProfileReady && typeof fetch === 'function' && !process.env.CI) {
389
+ checkedReachable++;
390
+ try {
391
+ let { response: res } = await fetchUrlWithSafeRedirects(u, {
392
+ method: 'HEAD',
393
+ maxRedirects: 5,
394
+ timeoutMs: 3500,
395
+ headers: { 'User-Agent': 'veycraft-link-check/2.0' },
396
+ });
397
+ if (res.status === 405 || res.status === 403) {
398
+ ({ response: res } = await fetchUrlWithSafeRedirects(u, {
399
+ method: 'GET',
400
+ maxRedirects: 5,
401
+ timeoutMs: 3500,
402
+ headers: { 'User-Agent': 'veycraft-link-check/2.0' },
403
+ }));
404
+ }
405
+ if (res.status === 404 || res.status === 410 || res.status >= 500) {
406
+ deadUrls.push(`${u} (HTTP ${res.status})`);
407
+ }
408
+ } catch (err) {
409
+ const msg = err instanceof Error ? err.message : String(err);
410
+ if (/SSRF guard/i.test(msg)) {
411
+ deadUrls.push(`${u} (${msg})`);
412
+ } else {
413
+ deadUrls.push(`${u} (unreachable)`);
414
+ }
415
+ }
416
+ }
417
+ }
418
+ return { validSyntax, placeholderCount, deadUrls, checkedReachable, total: urls.length };
419
+ }
420
+
421
+ export function evaluateGates(root) {
422
+ const prof = isPopulated(root, 'context/profile.md');
423
+ const cv = isPopulated(root, 'context/cv.md');
424
+ const hasPdf = ['assets/resume.pdf', 'context/resume.pdf'].some(rel => {
425
+ const f = path.join(root, rel);
426
+ try { return fs.existsSync(f) && fs.readFileSync(f).subarray(0, 5).toString() === '%PDF-'; } catch { return false; }
427
+ });
428
+ const g1 = prof.ready && cv.ready && hasPdf;
429
+ const g2 = isPopulated(root, 'context/preferences.yaml').ready;
430
+ const ansFile = path.join(root, 'context', 'form-answers.yaml');
431
+ const ans = isPopulated(root, 'context/form-answers.yaml');
432
+ const ownerVerified = fs.existsSync(ansFile) && /^\s*owner_verified:\s*true\b(?:\s*#.*)?$/im.test(fs.readFileSync(ansFile, 'utf8'));
433
+ const g3 = ans.ready && ownerVerified;
434
+ const targetsFile = path.join(root, 'context', 'targets.yaml');
435
+ const g5 = fs.existsSync(targetsFile) && /^\s*enabled:\s*true\b(?:\s*#.*)?$/im.test(fs.readFileSync(targetsFile, 'utf8'));
436
+ const gates = [g1, g2, g3, g5];
437
+ const passed = gates.filter(Boolean).length;
438
+ return { g1, g2, g3, g5, passed, total: gates.length, profReady: prof.ready };
439
+ }
440
+
441
+ export async function evaluateDoctorSnapshot({
442
+ root,
443
+ source,
444
+ home = os.homedir(),
445
+ isGlobal = false,
446
+ strict = false,
447
+ offline = false,
448
+ readOnly = false,
449
+ env = process.env,
450
+ } = {}) {
451
+ let criticalFailures = 0;
452
+ let readinessPending = 0;
453
+ const events = [];
454
+ const logOk = message => events.push({ level: 'ok', message });
455
+ const logWarn = message => events.push({ level: 'warn', message });
456
+ const logInfo = message => events.push({ level: 'info', message });
457
+ const logFail = message => events.push({ level: 'fail', message });
458
+
459
+ const { version, runtimeDeps, devDeps } = readPackageMeta(root, source);
460
+ const nodeMajor = Number(process.versions.node.split('.')[0]);
461
+ const nodeOk = nodeMajor >= 18;
462
+ if (nodeOk) logOk(`OS & Runtime: ${process.platform} (${os.arch()}) · Node ${process.versions.node}`);
463
+ else { logFail(`Node.js >= 18 required (found ${process.versions.node}). Upgrade from https://nodejs.org/.`); criticalFailures++; }
464
+
465
+ const installed = hasInstallMarker(root) || fs.existsSync(path.join(root, 'AGENTS.md'));
466
+ if (installed) {
467
+ logOk(`Agent Home: ${root} (${isGlobal ? 'global' : 'local'})`);
468
+ } else {
469
+ logWarn(`Agent Home: not yet initialized at ${root} — run \`veycraft init --global\` (recommended) or \`veycraft init\``);
470
+ readinessPending++;
471
+ }
472
+
473
+ const registryRoot = fs.existsSync(path.join(root, 'skills', 'REGISTRY.md'))
474
+ ? root
475
+ : (fs.existsSync(path.join(source, 'skills', 'REGISTRY.md')) ? source : null);
476
+ let manifestCount = null;
477
+ if (registryRoot) {
478
+ try {
479
+ const mPath = [path.join(registryRoot, 'skills', 'skills-manifest.json'), path.join(source, 'skills', 'skills-manifest.json')].find(f => fs.existsSync(f));
480
+ if (mPath) {
481
+ const parsed = JSON.parse(fs.readFileSync(mPath, 'utf8'));
482
+ if (Array.isArray(parsed?.skills)) manifestCount = parsed.skills.length;
483
+ }
484
+ } catch { /* ignore */ }
485
+ const suffix = registryRoot === root ? '' : ' (bundled in CLI package)';
486
+ logOk(`Skill Registry: skills/REGISTRY.md present${manifestCount !== null ? ` (${manifestCount} skills in manifest)` : ''}${suffix}`);
487
+ } else {
488
+ logFail('Missing skills/REGISTRY.md');
489
+ criticalFailures++;
490
+ }
491
+
492
+ const provenanceRoot = installed ? root : source;
493
+ const missingOrTampered = [];
494
+ for (const rel of ['NOTICE', 'AUTHORS.md', 'PROVENANCE.json']) {
495
+ const f = path.join(provenanceRoot, rel);
496
+ if (!fs.existsSync(f)) {
497
+ missingOrTampered.push(`${rel} (missing)`);
498
+ continue;
499
+ }
500
+ try {
501
+ const txt = fs.readFileSync(f, 'utf8');
502
+ if (rel === 'PROVENANCE.json') {
503
+ const prov = JSON.parse(txt);
504
+ if (prov?.github_handle !== 'redasalem') {
505
+ missingOrTampered.push('PROVENANCE.json (github_handle mismatch)');
506
+ }
507
+ if (prov?.original_author !== 'Reda Salem') {
508
+ missingOrTampered.push('PROVENANCE.json (original_author mismatch)');
509
+ }
510
+ if (prov?.canonical_repository !== 'https://github.com/redasalem/veycraft') {
511
+ missingOrTampered.push('PROVENANCE.json (canonical_repository mismatch)');
512
+ }
513
+ if (prov?.verified_noreply_email !== PINNED_SIGNING_PRINCIPAL) {
514
+ missingOrTampered.push('PROVENANCE.json (verified_noreply_email mismatch)');
515
+ }
516
+ } else if (rel === 'NOTICE') {
517
+ if (!txt.includes('Copyright (c) 2026 Reda Salem (@redasalem)') || !hasCanonicalGitHubUrl(txt, '/redasalem/veycraft')) {
518
+ missingOrTampered.push('NOTICE (canonical copyright or repository URL missing/tampered)');
519
+ }
520
+ } else if (rel === 'AUTHORS.md') {
521
+ if (!txt.includes('Reda Salem') || !hasCanonicalGitHubUrl(txt, '/redasalem', { allowSubpath: true })) {
522
+ missingOrTampered.push('AUTHORS.md (canonical author attribution missing/tampered)');
523
+ }
524
+ }
525
+ } catch {
526
+ missingOrTampered.push(`${rel} (unreadable/invalid)`);
527
+ }
528
+ }
529
+ const provenanceVerified = missingOrTampered.length === 0;
530
+ if (!provenanceVerified) {
531
+ logFail(`Provenance verification FAILED (tampered or uncredited clone): ${missingOrTampered.join(', ')}`);
532
+ criticalFailures++;
533
+ } else {
534
+ logOk(`Provenance & Attribution: NOTICE, AUTHORS.md & PROVENANCE.json canonical fields verified (@redasalem)${installed ? '' : ' [package]'}`);
535
+ }
536
+
537
+ const platDir = [path.join(root, 'skills', 'platforms'), path.join(source, 'skills', 'platforms')].find(d => fs.existsSync(d));
538
+ let verifiedPlaybooks = 0;
539
+ const stalePlaybooks = [];
540
+ if (platDir) {
541
+ for (const entry of fs.readdirSync(platDir, { withFileTypes: true })) {
542
+ if (!entry.isFile() || !entry.name.endsWith('.md') || entry.name.startsWith('_') || entry.name === 'README.md') continue;
543
+ const text = fs.readFileSync(path.join(platDir, entry.name), 'utf8');
544
+ const m = text.match(/^last_verified:\s*"?(\d{4}-\d{2}-\d{2})"?/m);
545
+ if (!m) {
546
+ stalePlaybooks.push(`${entry.name} (missing last_verified)`);
547
+ continue;
548
+ }
549
+ const ageDays = (Date.now() - Date.parse(`${m[1]}T00:00:00Z`)) / 86400000;
550
+ if (Number.isNaN(ageDays) || ageDays > 60) {
551
+ stalePlaybooks.push(`${entry.name} (${Math.floor(ageDays)}d old)`);
552
+ } else {
553
+ verifiedPlaybooks++;
554
+ }
555
+ }
556
+ if (stalePlaybooks.length > 0) {
557
+ logWarn(`Platform Playbook Freshness (>60d stale): ${stalePlaybooks.join(', ')}`);
558
+ } else if (verifiedPlaybooks > 0) {
559
+ logOk(`Platform Playbook Freshness: ${verifiedPlaybooks} playbook(s) verified within 60 days`);
560
+ }
561
+ }
562
+
563
+ const checkGate = (label, cond, hint) => {
564
+ if (cond) logOk(label);
565
+ else { logWarn(`${label} — ${hint}`); readinessPending++; }
566
+ };
567
+
568
+ const gates = evaluateGates(root);
569
+ checkGate('Gate 1 · CV & Profile', gates.g1, 'run /setup in your IDE to confirm CV & add resume.pdf');
570
+ checkGate('Gate 2 · Target Preferences', gates.g2, 'confirm target roles, regions & work modes in /setup');
571
+ checkGate('Gate 3/4 · Legal, Comp & Skills', gates.g3, 'confirm salary, visa, and skill years in /setup');
572
+ checkGate('Gate 5 · Enabled Targets', gates.g5, 'enable at least one board in context/targets.yaml via /setup');
573
+
574
+ const linkAudit = await verifyProfileLinks(root, gates.profReady, { offline });
575
+ if (linkAudit.deadUrls.length > 0) {
576
+ logWarn(`Profile & Resume Links: ${linkAudit.deadUrls.length} broken/dead URL(s): ${linkAudit.deadUrls.join(', ')}`);
577
+ readinessPending++;
578
+ } else if (linkAudit.placeholderCount > 0) {
579
+ logInfo(`Profile & Resume Links: ${linkAudit.placeholderCount} placeholder URL(s) in context/ (replace via /setup)`);
580
+ } else if (linkAudit.validSyntax > 0) {
581
+ logOk(`Profile & Resume Links: ${linkAudit.validSyntax} well-formed URL(s) verified`);
582
+ }
583
+
584
+ const profileExists = fs.existsSync(path.join(root, 'browser-profile'));
585
+ checkGate('Browser Profile Directory', profileExists, 'run `login` to initialize browser-profile/');
586
+
587
+ const preCommitActive = readOnly
588
+ ? isGitPreCommitHookActive(root)
589
+ : installGitPreCommitHook(root, home);
590
+ if (preCommitActive) {
591
+ logOk('Git Pre-Commit PII Shield: .git/hooks/pre-commit active');
592
+ }
593
+
594
+ const mcpStatus = [];
595
+ for (const file of mcpTargetFiles(root, isGlobal, home)) {
596
+ if (!fs.existsSync(file)) {
597
+ logInfo(`MCP Config: ${file} (not created yet — run sync-mcp if using this IDE)`);
598
+ mcpStatus.push({ file, status: 'not_created' });
599
+ continue;
600
+ }
601
+ try {
602
+ const cfg = readJsonSafeBase(file, { boundary: root, home });
603
+ const args = cfg?.mcpServers?.playwright?.args || [];
604
+ const hasDir = Array.isArray(args) && args.some(a => typeof a === 'string' && a.startsWith('--user-data-dir='));
605
+ if (hasDir) {
606
+ logOk(`MCP Config: ${file}`);
607
+ mcpStatus.push({ file, status: 'ok' });
608
+ } else {
609
+ logWarn(`MCP Config: ${file} missing playwright --user-data-dir`);
610
+ mcpStatus.push({ file, status: 'missing_user_data_dir' });
611
+ readinessPending++;
612
+ }
613
+ } catch {
614
+ logFail(`MCP Config invalid JSON: ${file}`);
615
+ mcpStatus.push({ file, status: 'invalid_json' });
616
+ criticalFailures++;
617
+ }
618
+ }
619
+ if (!isGlobal) {
620
+ const vsFile = path.join(root, '.vscode', 'mcp.json');
621
+ if (fs.existsSync(vsFile)) {
622
+ try {
623
+ const cfg = readJsonSafeBase(vsFile, { boundary: root, home });
624
+ const args = cfg?.servers?.playwright?.args || [];
625
+ if (Array.isArray(args) && args.some(a => typeof a === 'string' && a.startsWith('--user-data-dir='))) {
626
+ logOk(`VS Code MCP Config: ${vsFile}`);
627
+ mcpStatus.push({ file: vsFile, status: 'ok' });
628
+ } else {
629
+ logWarn(`VS Code MCP Config: ${vsFile} missing playwright --user-data-dir`);
630
+ mcpStatus.push({ file: vsFile, status: 'missing_user_data_dir' });
631
+ }
632
+ } catch {
633
+ logFail(`VS Code MCP Config invalid JSON: ${vsFile}`);
634
+ mcpStatus.push({ file: vsFile, status: 'invalid_json' });
635
+ criticalFailures++;
636
+ }
637
+ } else {
638
+ logInfo(`VS Code MCP Config: ${vsFile} (not created yet — run sync-mcp if using VS Code/Copilot)`);
639
+ mcpStatus.push({ file: vsFile, status: 'not_created' });
640
+ }
641
+ }
642
+ const codexToml = codexConfigTomlPath(root, isGlobal, home);
643
+ if (fs.existsSync(codexToml)) {
644
+ const toml = fs.readFileSync(codexToml, 'utf8');
645
+ if (/^\s*\[mcp_servers\.playwright\]/m.test(toml) && toml.includes('--user-data-dir=')) {
646
+ logOk(`Codex MCP Config: ${codexToml}`);
647
+ mcpStatus.push({ file: codexToml, status: 'ok' });
648
+ } else {
649
+ logWarn(`Codex MCP Config: ${codexToml} missing [mcp_servers.playwright] --user-data-dir`);
650
+ mcpStatus.push({ file: codexToml, status: 'missing_user_data_dir' });
651
+ }
652
+ } else {
653
+ logInfo(`Codex MCP Config: ${codexToml} (not created yet — run sync-mcp if using OpenAI Codex CLI)`);
654
+ mcpStatus.push({ file: codexToml, status: 'not_created' });
655
+ }
656
+
657
+ const globalIdePaths = [];
658
+ if (isGlobal) {
659
+ for (const [label, p] of [
660
+ ['~/.agents/skills', path.join(home, '.agents', 'skills')],
661
+ ['~/.codex/AGENTS.md', path.join(resolveCodexHome(home, env), 'AGENTS.md')],
662
+ ['~/.gemini/GEMINI.md', path.join(home, '.gemini', 'GEMINI.md')],
663
+ ['~/.gemini/skills', path.join(home, '.gemini', 'skills')],
664
+ ['~/.copilot/copilot-instructions.md', path.join(home, '.copilot', 'copilot-instructions.md')],
665
+ ['~/.claude/skills', path.join(home, '.claude', 'skills')],
666
+ ['~/.cursor/rules/job-hunter.mdc', path.join(home, '.cursor', 'rules', 'job-hunter.mdc')],
667
+ ['~/.gemini/antigravity/global_workflows', path.join(home, '.gemini', 'antigravity', 'global_workflows')],
668
+ ]) {
669
+ const exists = fs.existsSync(p);
670
+ globalIdePaths.push({ label, path: p, present: exists });
671
+ if (exists) logOk(`Global IDE Path: ${label}`);
672
+ else logWarn(`Global IDE Path missing: ${label} (run init --global)`);
673
+ }
674
+ }
675
+
676
+ logInfo(`Optional NOTION_TOKEN: ${env.NOTION_TOKEN ? 'present (value hidden)' : 'not set (local JSON mode active)'}`);
677
+ const nextSteps = [];
678
+ if (!installed) {
679
+ nextSteps.push('Run `veycraft init --global` (recommended) or `veycraft init` in your workspace to scaffold skills and IDE configs.');
680
+ }
681
+ nextSteps.push('Start safely in your AI IDE with `/demo` (zero personal data) or `/quick-tailor` (1 CV + 1 JD, no browser login).');
682
+ if (gates.passed < gates.total) {
683
+ nextSteps.push('For full browser-assisted workflows later, run `veycraft login` and `/setup` in your AI IDE.');
684
+ }
685
+
686
+ const okFlag = criticalFailures === 0 && (!strict || readinessPending === 0);
687
+ const payload = {
688
+ product: 'veycraft',
689
+ version,
690
+ node: process.versions.node,
691
+ node_ok: nodeOk,
692
+ platform: process.platform,
693
+ arch: os.arch(),
694
+ scope: isGlobal ? 'global' : 'local',
695
+ root,
696
+ global_root: resolveGlobalRoot(home, env, process.platform),
697
+ package_source: source,
698
+ initialized: installed,
699
+ skills_count: manifestCount,
700
+ provenance_verified: provenanceVerified,
701
+ provenance_source: provenanceRoot,
702
+ provenance_issues: missingOrTampered,
703
+ playbooks_verified: verifiedPlaybooks,
704
+ stale_playbooks: stalePlaybooks,
705
+ gates: {
706
+ cv_and_profile: gates.g1,
707
+ target_preferences: gates.g2,
708
+ legal_comp_skills: gates.g3,
709
+ enabled_targets: gates.g5,
710
+ passed: gates.passed,
711
+ total: gates.total,
712
+ },
713
+ browser_profile_present: profileExists,
714
+ git_pre_commit_shield: preCommitActive,
715
+ notion_token_set: Boolean(env.NOTION_TOKEN),
716
+ mcp_configs: mcpStatus,
717
+ global_ide_paths: globalIdePaths,
718
+ zero_dependencies: { runtime: runtimeDeps, dev: devDeps },
719
+ safe_defaults: { dry_run_default: true, explicit_approve_required: true },
720
+ readiness_pending: readinessPending,
721
+ critical_failures: criticalFailures,
722
+ ok: okFlag,
723
+ next_steps: nextSteps,
724
+ };
725
+ if (offline) {
726
+ payload.offline_mode = true;
727
+ payload.link_audit = {
728
+ valid_syntax: linkAudit.validSyntax,
729
+ placeholder_count: linkAudit.placeholderCount,
730
+ dead_urls: linkAudit.deadUrls,
731
+ checked_reachable: linkAudit.checkedReachable,
732
+ };
733
+ }
734
+
735
+ return {
736
+ payload,
737
+ events,
738
+ installed,
739
+ readinessPending,
740
+ criticalFailures,
741
+ exitCode: okFlag ? 0 : 1,
742
+ };
743
+ }
744
+
745
+ function hasCanonicalGitHubUrl(text, expectedPath, { allowSubpath = false } = {}) {
746
+ const matches = String(text || '').match(/https:\/\/[^\s)"'>\],]+/gi) || [];
747
+ for (const raw of matches) {
748
+ const cleaned = raw.replace(/[.;:]+$/, '');
749
+ try {
750
+ const parsed = new URL(cleaned);
751
+ if (parsed.origin !== 'https://github.com') continue;
752
+ const normPath = parsed.pathname.replace(/\/+$/, '');
753
+ if (normPath === expectedPath || (allowSubpath && normPath.startsWith(`${expectedPath}/`))) {
754
+ return true;
755
+ }
756
+ } catch { /* ignore invalid URL */ }
757
+ }
758
+ return false;
759
+ }
760
+
761
+ export function decodeHtmlEntities(str) {
762
+ return decodeXmlHtmlEntities(str);
763
+ }
764
+
765
+ export function extractHtmlText(html) {
766
+ const withoutBlocks = stripHtmlBlocks(String(html || ''), ['style', 'script']);
767
+ const withNewlines = withoutBlocks.replace(/<\/?(?:p|div|li|tr|h[1-6]|br|section|header|main|article)\b[^>]*>/gi, '\n');
768
+ return decodeHtmlEntities(stripMarkupTags(withNewlines, ' '))
769
+ .split(/\r?\n/)
770
+ .map(l => l.replace(/[ \t]+/g, ' ').trim())
771
+ .filter(Boolean)
772
+ .join('\n');
773
+ }
774
+
775
+ export function readCvInputText(resolved) {
776
+ const ext = path.extname(resolved).toLowerCase();
777
+ if (ext === '.docx') {
778
+ const rawBuf = readFileBoundedSync(resolved, DOCX_LIMITS.MAX_INPUT_BYTES, '.docx file');
779
+ return { text: extractDocxText(rawBuf), format: 'docx' };
780
+ }
781
+ const rawBuf = fs.readFileSync(resolved);
782
+ if (rawBuf.subarray(0, 5).toString('utf8') === '%PDF-' || ext === '.pdf') {
783
+ throw new Error('Binary/PDF file detected. Read natively if your AI IDE supports PDFs, open via Playwright MCP file:///..., or paste/export as .md/.txt/.docx for instant CLI audit.');
784
+ }
785
+ if (ext === '.doc' && rawBuf.length >= 4 && rawBuf[0] === 0xd0 && rawBuf[1] === 0xcf && rawBuf[2] === 0x11 && rawBuf[3] === 0xe0) {
786
+ throw new Error('Legacy binary .doc (OLE2) detected. Save as .docx/.txt/.md or paste your CV text in chat.');
787
+ }
788
+ if (rawBuf.includes(0)) {
789
+ throw new Error('Binary file detected. Pass a readable .md, .txt, .docx, .html, or Word-compatible .doc CV file.');
790
+ }
791
+ const rawText = rawBuf.toString('utf8');
792
+ if (ext === '.html' || ext === '.htm' || (ext === '.doc' && /<html|<body|<p|<div/i.test(rawText))) {
793
+ return { text: extractHtmlText(rawText), format: ext === '.doc' ? 'word-html-doc' : 'html' };
794
+ }
795
+ if (ext && ext !== '.md' && ext !== '.txt' && ext !== '.markdown' && ext !== '.doc') {
796
+ throw new Error(`Unsupported file extension "${ext}". Pass .md, .txt, .docx, .html, or Word-compatible .doc.`);
797
+ }
798
+ return { text: rawText, format: ext.replace(/^\./, '') || 'txt' };
799
+ }
800
+
801
+ export function auditCvText(rawText, {
802
+ format = 'md',
803
+ resolved = '<inline>',
804
+ root = process.cwd(),
805
+ source = root,
806
+ isPreExtracted = false,
807
+ } = {}) {
808
+ if (typeof rawText !== 'string') {
809
+ throw new Error('CV text must be a string.');
810
+ }
811
+ const normFormat = String(format || 'md').toLowerCase().replace(/^\./, '') || 'txt';
812
+ const extracted = !isPreExtracted && (normFormat === 'html' || normFormat === 'htm' || normFormat === 'word-html-doc')
813
+ ? extractHtmlText(rawText)
814
+ : rawText;
815
+ const trimmed = extracted.trim();
816
+ if (!trimmed) {
817
+ throw new Error(`CV file is empty: ${resolved}`);
818
+ }
819
+
820
+ const clichesFound = BANNED_AI_CLICHES.filter(cl => buildSkillRegex(cl).test(trimmed));
821
+ const emDashCount = (trimmed.match(/—/g) || []).length;
822
+ const tonePenalty = Math.min(25, clichesFound.length * 6 + Math.min(10, emDashCount * 2));
823
+ const toneScore = 25 - tonePenalty;
824
+
825
+ const lines = trimmed.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
826
+ const bullets = lines.filter(l => /^[-*•]\s+/.test(l));
827
+ const metricPattern = '(?<![A-Za-z0-9_])(?:\\$?\\d[\\d,]*(?:\\.\\d+)?(?:\\s*(?:%|k|m|b|x|ms|sec|seconds|min|minutes|hrs|hours|days|weeks|months|years)\\b|%|[KMBX]\\b|\\+))';
828
+ const metricGlobalRe = new RegExp(metricPattern, 'gi');
829
+ const metricSingleRe = new RegExp(metricPattern, 'i');
830
+ const totalMetrics = (trimmed.match(metricGlobalRe) || []).length;
831
+ const quantifiedBullets = bullets.filter(b => metricSingleRe.test(b)).length;
832
+ let impactScore = 0;
833
+ if (bullets.length > 0) {
834
+ const ratio = quantifiedBullets / bullets.length;
835
+ impactScore = Math.min(30, Math.round(ratio * 24) + Math.min(6, totalMetrics));
836
+ } else {
837
+ impactScore = Math.min(30, totalMetrics * 5);
838
+ }
839
+
840
+ const words = trimmed.split(/\s+/).filter(Boolean);
841
+ const wordCount = words.length;
842
+ const lineCount = lines.length;
843
+ let lengthStatus = '1-Page A4 Fit';
844
+ let lengthCategory = '1-Page A4 Fit';
845
+ let lengthScore = 25;
846
+ if (wordCount < 120) {
847
+ lengthStatus = 'Too Short (<120 words)';
848
+ lengthCategory = 'Too Short';
849
+ lengthScore = 12;
850
+ } else if (wordCount > 750 || lineCount > 55) {
851
+ lengthStatus = `Overflow Risk (${wordCount} words / ${lineCount} lines)`;
852
+ lengthCategory = 'Overflow Risk';
853
+ lengthScore = 15;
854
+ } else if (wordCount > 620 || lineCount > 45) {
855
+ lengthStatus = `Tight 1-Page (${wordCount} words / ${lineCount} lines)`;
856
+ lengthCategory = 'Tight 1-Page';
857
+ lengthScore = 21;
858
+ }
859
+
860
+ const hasPlaceholder = PLACEHOLDER_RE.test(trimmed);
861
+ const hasSecretLeak = SECRET_LEAK_RE.test(trimmed);
862
+ const rawUrls = trimmed.match(/https?:\/\/[^\s)"'>\],]+/gi) || [];
863
+ let badUrls = 0;
864
+ for (const raw of rawUrls) {
865
+ const cleaned = raw.replace(/[.;:]+$/, '');
866
+ try {
867
+ const parsed = new URL(cleaned);
868
+ if (isBlockedSsrfUrl(parsed)) badUrls++;
869
+ } catch {
870
+ badUrls++;
871
+ }
872
+ }
873
+ let hygieneScore = 20;
874
+ if (hasPlaceholder) hygieneScore -= 8;
875
+ if (hasSecretLeak) hygieneScore -= 12;
876
+ if (badUrls > 0) hygieneScore -= Math.min(8, badUrls * 4);
877
+ hygieneScore = Math.max(0, hygieneScore);
878
+
879
+ const totalScore = toneScore + impactScore + lengthScore + hygieneScore;
880
+ const { version } = readPackageMeta(root, source);
881
+ const hygieneLabel = hasSecretLeak
882
+ ? 'token flagged'
883
+ : (hasPlaceholder ? 'placeholders' : 'clean');
884
+
885
+ return {
886
+ resolved,
887
+ format: normFormat === 'htm' ? 'html' : normFormat,
888
+ version,
889
+ total_score: totalScore,
890
+ tone_score: toneScore,
891
+ impact_score: impactScore,
892
+ length_score: lengthScore,
893
+ hygiene_score: hygieneScore,
894
+ cliches_found: clichesFound,
895
+ em_dash_count: emDashCount,
896
+ total_metrics: totalMetrics,
897
+ quantified_bullets: quantifiedBullets,
898
+ bullet_count: bullets.length,
899
+ word_count: wordCount,
900
+ line_count: lineCount,
901
+ length_status: lengthStatus,
902
+ length_category: lengthCategory,
903
+ has_placeholder: hasPlaceholder,
904
+ has_secret_leak: hasSecretLeak,
905
+ bad_urls: badUrls,
906
+ hygiene_label: hygieneLabel,
907
+ scope: 'Local heuristic CV hygiene check — not an ATS acceptance probability or verification of factual claims.',
908
+ };
909
+ }
910
+
911
+ export function auditCvFile(targetArg, { root, source, home = os.homedir(), cwd = process.cwd() } = {}) {
912
+ const targetInfo = assertSafeCliInputPath(targetArg, { label: 'resume file', root, source, home, cwd });
913
+ if (!targetInfo.exists) {
914
+ throw new Error(`Resume file not found: ${targetInfo.resolved}`);
915
+ }
916
+ const resolved = targetInfo.resolved;
917
+ const { text, format } = readCvInputText(resolved);
918
+ return auditCvText(text, { format, resolved, root, source, isPreExtracted: true });
919
+ }
920
+
921
+ export const ROUTE_RULES = [
922
+ {
923
+ intent: 'sandbox-demo',
924
+ matches: q => /(^|\s)\/demo\b|\bsandbox demo\b/i.test(q),
925
+ skills: ['02-discover-and-triage', '03-tailor-resume-and-verify', '13-company-due-diligence', '14-privacy-pii-shield', '21-ats-keyword-heatmap'],
926
+ workflow: '.agent/workflows/demo.md',
927
+ readiness: 'none (zero personal data or browser login required)',
928
+ required_inputs: [],
929
+ optional_tools: [],
930
+ fallback: 'Works offline from examples/sandbox-demo/',
931
+ outputs: ['Mission Control table', 'Synthetic Job #1 tailored preview'],
932
+ },
933
+ {
934
+ intent: 'setup-full-career-os',
935
+ matches: q => /(^|\s)\/setup\b|\bcheck my folder\b|\b5 readiness gates\b/i.test(q),
936
+ skills: ['00-interrogate-and-onboard', '01-resume-ingestion', '11-portfolio-and-github-auditor'],
937
+ workflow: '.agent/workflows/setup.md',
938
+ readiness: 'full-5-gate-onboarding',
939
+ required_inputs: ['CV file or pasted CV', 'target roles/regions', 'comp/legal/skills_years', 'enabled platforms'],
940
+ optional_tools: ['playwright (for live login & PDF)'],
941
+ fallback: 'Gates 1-4 complete locally without Playwright; standalone tasks never require /setup',
942
+ outputs: ['context/profile.md', 'context/cv.md', 'context/resume-data.json', 'context/preferences.yaml', 'context/form-answers.yaml', 'context/targets.yaml'],
943
+ },
944
+ {
945
+ intent: 'daily-run',
946
+ matches: q => /(^|\s)\/daily-run\b|\brun today'?s job run\b|\bstart applying\b/i.test(q),
947
+ skills: ['00-daily-run', '00-interrogate-and-onboard', '02-discover-and-triage', '03-tailor-resume-and-verify', '04-fill-and-apply', '05-outreach-and-interview-prep', '06-log-and-insights'],
948
+ workflow: '.agent/workflows/daily-run.md',
949
+ readiness: 'full-5-gate-readiness + launch consent + browser auth',
950
+ required_inputs: ['5 passed readiness gates', 'fresh launch confirmation'],
951
+ optional_tools: ['playwright (required for live board automation)', 'notion'],
952
+ fallback: 'If Playwright is absent, offer /quick-tailor or URL/pasted-JD manual prep',
953
+ outputs: ['Mission Control table', 'logs/resumes/<job>/', 'logs/applications-log.json', 'logs/runs/YYYY-MM-DD.json'],
954
+ },
955
+ {
956
+ intent: 'linkedin-profile',
957
+ matches: q =>
958
+ /(^|\s)\/linkedin-growth\b/i.test(q) ||
959
+ (
960
+ /\blinkedin\b/i.test(q) &&
961
+ /\b(profile|headline|about|consistent|optimize|audit|review|improve|fix|seo|setup|branding|post|posts|outreach|algorithm|reach|impressions|dwell time|carousel|pdf document|comment[- ]first|comment strategy|comments?|content strategy|content pillars?|topical authority|growth|grow|engagement|funnel|services?|service page|freelance|inbound clients?|client requests?|proposal|reviews?|credibility|trust signals?)\b/i.test(q) &&
962
+ !/\b(job|apply|jobs)\b/i.test(q)
963
+ ) ||
964
+ (
965
+ /(?:لينكد\s?[إاأ]ن|لينكدان|\blinkedin\b)/i.test(q) &&
966
+ /(?:ظبط|ضبط|تظبيط|تضبيط|عدل|عدّل|تعديل|حسن|حسّن|تحسين|راجع|مراجعة|طور|طوّر|تطوير|تجهيز|خدمات|صفحة\s+الخدمات|فريلانس|عملاء|بوست|منشور|خوارزمية|بروفايل|ملف|حساب)/i.test(q) &&
967
+ !/(?:وظيف|وظائف|تقديم\s+على|\bjobs?\b|\bapply\b)/i.test(q)
968
+ ) ||
969
+ /\b(profile consistent with my cv|optimize my profile|grow my linkedin)\b/i.test(q),
970
+ skills: ['linkedin-growth', 'profile-intelligence-engine', '03-tailor-resume-and-verify', '05-outreach-and-interview-prep', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
971
+ workflow: '.agent/workflows/linkedin-growth.md',
972
+ readiness: 'task-specific (profile text/PDF/screenshot or signed-in Playwright + CV facts; no /setup required)',
973
+ required_inputs: ['LinkedIn profile (pasted, PDF, screenshot, or signed-in Playwright)', 'verified CV facts'],
974
+ optional_tools: ['playwright (for read-only profile read or APPROVE-gated live edit)'],
975
+ fallback: 'Works 100% offline from pasted profile text, Save-to-PDF, or screenshots as DRAFT_ONLY',
976
+ outputs: ['0-100 Recruiter-SEO & Credibility scorecard, 3-stage funnel & CV consistency gaps', 'Engine D LinkedIn Services Page & EN/AR <=75-word proposals + Feed/Comment-First/Carousel drafts in logs/insights/linkedin-seo-audit-YYYY-MM-DD.md'],
977
+ },
978
+ {
979
+ intent: 'profile-intelligence',
980
+ matches: q =>
981
+ /(^|\s)\/profile-update\b/i.test(q) ||
982
+ /(?:بروفايل|ملفي المهني|الملف المهني)/i.test(q) ||
983
+ (
984
+ /\b(optimize|improve|update|sync|tailor|review|fill|audit)\b/i.test(q) &&
985
+ /\b(professional profile|career profile|job profile|job board profiles?|linkedin profile|github profile|portfolio profile|my profile|profile fields?|profiles? across|headline and about)\b/i.test(q) &&
986
+ !/\bfind\b.*\bjobs?\b/i.test(q)
987
+ ),
988
+ skills: ['profile-intelligence-engine', '01-resume-ingestion', '03-tailor-resume-and-verify', '11-portfolio-and-github-auditor', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
989
+ workflow: '.agent/workflows/profile-update.md',
990
+ readiness: 'task-specific (verified CV/profile facts + target role/goal; no /setup required)',
991
+ required_inputs: ['verified CV/profile facts', 'target role, JD, or positioning goal'],
992
+ optional_tools: ['playwright (optional for live platform read, batch-fill, and read-back verification)', 'gh CLI (optional for GitHub repo audits, marketing edits, and safe cleanup)'],
993
+ fallback: 'Works 100% offline as a DRAFT_ONLY Profile Update Plan (schemas/profile-update-plan.schema.json) from pasted/exported profile data',
994
+ outputs: ['logs/insights/profile-update-plan-<platform>-YYYY-MM-DD.json', 'Consolidated field-level diff & truthful verification summary'],
995
+ },
996
+ {
997
+ intent: 'portfolio-design-qa',
998
+ matches: q =>
999
+ /(^|\s)\/portfolio-design\b/i.test(q) ||
1000
+ (
1001
+ /\bportfolio\b/i.test(q) &&
1002
+ /\b(design system|color palettes?|palettes?|colors?|typography|design tokens?|tokens?|wcag|contrast|unit tests?|component tests?|visual qa|responsive qa|overflow|console errors?|self-heal|wireframe|blueprint)\b/i.test(q) &&
1003
+ !/\b(deploy|host|publish|launch|vercel|wrangler|cloudflare|netlify|github pages|firebase|surge|audit|check\s+(?:my\s+)?portfolio\s+links?)\b/i.test(q)
1004
+ ),
1005
+ skills: ['30-portfolio-design-system-and-qa', '29-portfolio-builder-and-deployer', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
1006
+ workflow: '.agent/workflows/portfolio-design.md',
1007
+ readiness: 'task-specific (verified candidate facts + isolated logs/portfolio/<site-slug>/; no /setup or Playwright required)',
1008
+ required_inputs: ['verified candidate facts / Domain Archetype', 'isolated portfolio workspace path'],
1009
+ optional_tools: ['playwright (optional for live 375px/768px/1440px viewport, overflow, and console QA)'],
1010
+ fallback: 'Works 100% offline with node --test / isolated Vitest unit suites and an automated local Node DOM/CSS verification script writing qa-report.md',
1011
+ outputs: ['DESIGN_PLAN.md & separated portfolio-data', 'WCAG-validated design-tokens.json + tokens.css', '3-layer qa-report.md within <= 3 self-healing cycles'],
1012
+ },
1013
+ {
1014
+ intent: 'build-portfolio',
1015
+ matches: q =>
1016
+ /(^|\s)\/build-portfolio\b/i.test(q) ||
1017
+ (/\bportfolio\b/i.test(q) && /\b(build|create|generate|design|scaffold|make|deploy|host|publish|launch|vercel|wrangler|cloudflare|netlify|firebase|surge)\b/i.test(q) && !/\b(audit|check)\b/i.test(q)) ||
1018
+ (/\b(update|edit|customize|redesign)\b/i.test(q) && /\bportfolio\s+(?:site|website|page|theme|layout)\b/i.test(q)),
1019
+ skills: ['29-portfolio-builder-and-deployer', '30-portfolio-design-system-and-qa', '01-resume-ingestion', '03-tailor-resume-and-verify', '11-portfolio-and-github-auditor', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
1020
+ workflow: '.agent/workflows/build-portfolio.md',
1021
+ readiness: 'task-specific (verified CV/project facts + batched style/stack/hosting choices; no /setup or Playwright required)',
1022
+ required_inputs: ['verified CV/profile facts', 'style/stack/public-contact/hosting choices'],
1023
+ optional_tools: ['hosting CLI (vercel, wrangler, netlify, gh, firebase, surge)', 'playwright (optional for local/live visual preview)'],
1024
+ fallback: 'Builds locally inside isolated logs/portfolio/<site-slug>/ (LOCAL_PREVIEW_ONLY default) and exports ready-to-upload static dist/ + DNS/HTTPS instructions when no hosting CLI is used',
1025
+ outputs: ['Isolated portfolio project in logs/portfolio/<site-slug>/', 'Pre-publish PII/secret scan + local preview', 'Optional APPROVE-gated live HTTPS deployment + HTTP 200 verification'],
1026
+ },
1027
+ {
1028
+ intent: 'github-remote-ops',
1029
+ matches: q =>
1030
+ /(^|\s)\/github-remote\b|\b(no[- ]clone|without cloning|gh api|contents api|git data api|pull requests?|gh pr|gh issue|gh workflow|github actions?|workflow runs?|push commit remotely)\b/i.test(q) ||
1031
+ (/\bgithub\b/i.test(q) && /\b(license|workflows?|branches?|tags?|releases?|issues?|prs?)\b/i.test(q) && !/\b(cv|resume|portfolio|recruiter|audit)\b/i.test(q)),
1032
+ skills: ['54-github-cli-remote-manager', '14-privacy-pii-shield', 'meta-self-verification'],
1033
+ workflow: '.agent/workflows/github-remote.md',
1034
+ readiness: 'task-specific (authenticated gh CLI session + explicit target <owner>/<repo>; no /setup or local clone required)',
1035
+ required_inputs: ['authenticated gh CLI session (`gh auth status`)', 'target <owner>/<repo> and requested remote operation'],
1036
+ optional_tools: ['gh CLI (required for remote execution)'],
1037
+ fallback: 'Generates exact copy-pasteable `gh` CLI / `gh api` commands if `gh` is unavailable or unauthenticated',
1038
+ outputs: ['Zero-clone `gh api` file/tree commits, topics/visibility/license edits, or PR/CI status with fresh read-back verification'],
1039
+ },
1040
+ {
1041
+ intent: 'github-portfolio-audit',
1042
+ matches: q =>
1043
+ /(^|\s)\/github-audit\b/i.test(q) ||
1044
+ /\b(github audit|portfolio audit|audit (?:my )?(?:github|portfolio)|check (?:my )?portfolio links?|clean\s?up (?:my )?github|delete (?:junk|old|unused) repos?|archive (?:old|unused) repos?|extract (?:real )?projects from github|github readme|profile readme)\b/i.test(q) ||
1045
+ (/\bgithub\b/i.test(q) && /\b(repos?|repositories|readme|topics?|pinned|archive|private|delete|clean\s?up|extract|audit|optimize|polish)\b/i.test(q)),
1046
+ skills: ['11-portfolio-and-github-auditor', '01-resume-ingestion', '03-tailor-resume-and-verify', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
1047
+ workflow: '.agent/workflows/github-audit.md',
1048
+ readiness: 'task-specific (gh CLI auth or GitHub/portfolio URLs + target role/goal; no /setup or Playwright required)',
1049
+ required_inputs: ['authenticated gh CLI session or GitHub/portfolio URLs', 'target role or positioning goal'],
1050
+ optional_tools: ['gh CLI (for full repo inventory, codebase inspection, and APPROVE-gated edits/cleanup)', 'playwright (optional for live portfolio visual/link verification)'],
1051
+ fallback: 'Works read-only from Playwright or pasted repo URLs/READMEs if gh CLI is unavailable; all mutations default to DRAFT_ONLY with APPROVE (and per-repo typed DELETE <owner>/<repo> for deletions)',
1052
+ outputs: ['5-tier GitHub Inventory Scorecard', 'context/github-projects.md verified CV project dossier', 'DRAFT_ONLY Before/After marketing diff & tiered cleanup matrix'],
1053
+ },
1054
+ {
1055
+ intent: 'freelance-service-publisher',
1056
+ matches: q =>
1057
+ /(^|\s)\/freelance-service\b/i.test(q) ||
1058
+ (
1059
+ !/\blinkedin\b/i.test(q) &&
1060
+ (/\b(fiverr|khamsat|upwork|mostaql|freelancer(?:\.com)?|malt)\b/i.test(q) || /\b(?:freelance|gig)\b/i.test(q) || /(?:خمسات|مستقل|فريلانس|خدمة\s+فريلانس)/i.test(q)) &&
1061
+ (/\b(publish|create|launch|build|write|setup|set up|list|listing|gig|service|package|cover image|pricing tiers?)\b/i.test(q) || /(?:انشر|نشر|انشاء|إنشاء|اضافة|إضافة|خدمة|باقات|غلاف)/i.test(q)) &&
1062
+ !/\b(bid|bids|bidding|proposal|proposals|open projects?|offers?|radar|filter|rank|batch)\b/i.test(q) &&
1063
+ !/(?:عروض|تقديم\s+عرض|فلترة|مشاريع\s+مفتوحة)/i.test(q)
1064
+ ),
1065
+ skills: ['55-freelance-profile-and-service-publisher', '14-privacy-pii-shield', '18-condition-based-browser-waiting', '24-circuit-breaker-and-antiban', 'meta-self-verification'],
1066
+ workflow: '.agent/workflows/freelance-service.md',
1067
+ readiness: 'task-specific (service description + target freelance platform URL + verified CV/project facts; no /setup required)',
1068
+ required_inputs: ['plain-language service description', 'target freelance marketplace URL or platform name', 'verified CV/project facts'],
1069
+ optional_tools: ['playwright (optional for live profile audit, cover upload, and form filling)', 'native image generator (optional for cover artwork)'],
1070
+ fallback: 'Generates complete SEO service copy, pricing tiers, FAQs, and cover visual prompt/HTML asset locally as DRAFT_ONLY',
1071
+ outputs: ['SEO service package + pricing tiers + FAQs', 'Custom cover image asset', 'Live DOM Read-Back Table paused for APPROVE PUBLISH'],
1072
+ },
1073
+ {
1074
+ intent: 'freelance-offer-radar',
1075
+ matches: q =>
1076
+ /(^|\s)\/freelance-bid\b/i.test(q) ||
1077
+ (
1078
+ !/\blinkedin\b/i.test(q) &&
1079
+ (/\b(fiverr|khamsat|upwork|mostaql|freelancer(?:\.com)?|malt|freelance)\b/i.test(q) || /(?:مستقل|خمسات|فريلانس|عروض\s+المشاريع|تقديم\s+عرض)/i.test(q)) &&
1080
+ (/\b(bid|bids|bidding|proposal|proposals|open projects?|offers?|radar|filter|rank|batch)\b/i.test(q) || /(?:عروض|عرض|تقديم|فلترة|مشاريع\s+مفتوحة)/i.test(q))
1081
+ ),
1082
+ skills: ['56-freelance-offer-radar-and-batch-bidder', '14-privacy-pii-shield', '18-condition-based-browser-waiting', '24-circuit-breaker-and-antiban', '25-prompt-injection-defense', 'meta-self-verification'],
1083
+ workflow: '.agent/workflows/freelance-bid.md',
1084
+ readiness: 'task-specific (target freelance feed URL or pasted listings + verified stack/rate floor; no /setup required)',
1085
+ required_inputs: ['target marketplace open-projects URL or pasted listings', 'verified stack & minimum rate/budget floor'],
1086
+ optional_tools: ['playwright (optional for live feed scanning and APPROVE-gated batch bidding)'],
1087
+ fallback: 'Scores pasted open projects offline and produces concise DRAFT_ONLY proposals + tracker/freelance-proposals.md rows',
1088
+ outputs: ['Numbered Freelance Offer Radar Table (Fit Score 0-100%)', 'Concise IP-safe proposal drafts', 'tracker/freelance-proposals.md log after APPROVE <numbers>'],
1089
+ },
1090
+ {
1091
+ intent: 'interview-prep',
1092
+ matches: q => /\b(interview|take-home|coding challenge|system design)\b/i.test(q) && !/\b(rejected|rejection|rate|offer|history)\b/i.test(q),
1093
+ skills: ['05-outreach-and-interview-prep', '22-technical-assessment-architect'],
1094
+ workflow: null,
1095
+ readiness: 'task-specific (target JD/prompt + CV facts; no prior application submission required)',
1096
+ required_inputs: ['target job description / company / prompt', 'verified CV facts'],
1097
+ optional_tools: ['playwright'],
1098
+ fallback: 'Works 100% locally from pasted JD/prompt and CV facts',
1099
+ outputs: ['logs/resumes/<folder>/interview-dossier.md or assessment-blueprint.md', 'targeted technical & behavioral prep Q&As'],
1100
+ },
1101
+ {
1102
+ intent: 'offer-and-contract',
1103
+ matches: q => /\b(job offer|negotiate|salary expectation|rate check|contract|nda|msa|sow|agreement)\b/i.test(q),
1104
+ skills: ['09-offer-negotiator', '23-contract-and-nda-auditor'],
1105
+ workflow: null,
1106
+ readiness: 'task-specific (offer/contract text + verified compensation/notice floor; no /setup required)',
1107
+ required_inputs: ['offer/rate message or contract/NDA text', 'verified comp/work terms'],
1108
+ optional_tools: [],
1109
+ fallback: 'Works 100% locally as DRAFT_ONLY comparison and redline proposals',
1110
+ outputs: ['Grounded offer comparison or 6-category contract red-flag audit', 'DRAFT_ONLY reply/counter-clauses'],
1111
+ },
1112
+ {
1113
+ intent: 'application-prep-and-fill',
1114
+ matches: q => /(^|\s)\/apply-url\b|\b(prepare (?:my |an )?application|upload (?:my |the tailored )?resume to|answer (?:this |these )?application question|ats form|easy apply)\b/i.test(q),
1115
+ skills: ['03-tailor-resume-and-verify', '04-fill-and-apply', '05-outreach-and-interview-prep', '06-log-and-insights', 'meta-self-verification'],
1116
+ workflow: '.agent/workflows/apply-url.md',
1117
+ readiness: 'task-specific for prep (CV + JD + relevant answers); full gate + DOM Read-Back + explicit APPROVE for live ATS Submit',
1118
+ required_inputs: ['target job URL or JD', 'verified CV facts', 'application question answers'],
1119
+ optional_tools: ['playwright (required for live ATS upload/submit; manual prep fallback if unavailable)'],
1120
+ fallback: 'Generates complete manual package (resume.html/.doc/.txt, cover letter, answers, dossier, local tracking) via skills/fallback-no-mcp.md',
1121
+ outputs: ['logs/resumes/<folder>/ artifacts', 'Live DOM Read-Back Table + APPROVE gate (or manual upload guide)', 'logs/applications-log.json entry'],
1122
+ },
1123
+ {
1124
+ intent: 'tracking-and-insights',
1125
+ matches: q => /(^|\s)\/weekly-report\b|\b(track (?:my )?applications|application history|analy[sz]e (?:my )?rejections|why am i getting rejected|ghosted|export (?:my )?application report|update (?:an )?existing application|follow-?up|calibrate|recruiter (?:email|message|replied))\b/i.test(q),
1126
+ skills: ['06-log-and-insights', '08-follow-up-radar', '12-recruiter-inbox-triage', '16-rejection-pattern-analyzer', '17-score-calibration'],
1127
+ workflow: '.agent/workflows/weekly-report.md',
1128
+ readiness: 'task-specific (logs/applications-log.json; no Playwright or Notion required)',
1129
+ required_inputs: ['local logs/applications-log.json (and update/message if provided)'],
1130
+ optional_tools: ['notion'],
1131
+ fallback: 'Local JSON is primary truth; exports Markdown/CSV/JSON/HTML dashboard without Notion',
1132
+ outputs: ['Updated logs/applications-log.json', 'logs/insights/ or logs/exports/ report'],
1133
+ },
1134
+ {
1135
+ intent: 'job-discovery-and-triage',
1136
+ matches: q => /\b(find .*jobs?|jobs? in |remote .*jobs?|analy[sz]e this .*job|should i apply|compare these jobs|rank them|discover jobs)\b/i.test(q),
1137
+ skills: ['02-discover-and-triage', '25-prompt-injection-defense', '26-deduplication-and-blacklist-guard', '28-recruiter-brand-and-domain-intelligence', 'platforms/linkedin'],
1138
+ workflow: null,
1139
+ readiness: 'task-specific (verified CV facts + query or URLs/JDs/screenshots; no /setup wall for read-only analysis)',
1140
+ required_inputs: ['verified CV facts', 'search query or job URLs/pasted JDs/screenshots'],
1141
+ optional_tools: ['playwright (for live multi-board search; URL/JD/screenshot fallback if absent or unauthenticated)'],
1142
+ fallback: 'Searches legitimate accessible boards when authorized; otherwise scores/ranks user-supplied URLs, JDs, or screenshots without fabricating live listings',
1143
+ outputs: ['Evidence-backed shortlist/ranking with source URL + verification date', 'Verified matches vs. unknown requirements'],
1144
+ },
1145
+ {
1146
+ intent: 'tailor-cv',
1147
+ matches: q => /(^|\s)\/(?:quick-tailor|tailor-cv)\b|\b(tailor (?:my )?cv|compare (?:my )?cv against)\b/i.test(q),
1148
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify', '21-ats-keyword-heatmap', '28-recruiter-brand-and-domain-intelligence'],
1149
+ workflow: '.agent/workflows/quick-tailor.md',
1150
+ readiness: 'task-specific (CV + 1 JD; zero browser login or /setup required)',
1151
+ required_inputs: ['candidate CV', 'target job description (or URL)'],
1152
+ optional_tools: ['playwright (optional for PDF print or URL read)'],
1153
+ fallback: 'Ask for pasted JD if URL blocked; deliver HTML + Word-compatible .doc + TXT + Print-to-PDF guidance',
1154
+ outputs: ['resume.html', 'resume.doc (Word-compatible HTML)', 'resume.txt', 'tailoring-notes.md (Evidence Map, ATS Heatmap, True Gaps)', 'optional resume.pdf'],
1155
+ },
1156
+ {
1157
+ intent: 'cv-translate',
1158
+ matches: q => /\b(arabic|english|german|french|spanish|rtl|translate)\b/i.test(q) && /\b(cv|resume)\b/i.test(q),
1159
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify', '15-multilingual-adaptation'],
1160
+ workflow: null,
1161
+ readiness: 'task-specific (source CV + target language; preserves original file)',
1162
+ required_inputs: ['source CV', 'target language'],
1163
+ optional_tools: ['playwright (optional for PDF export)'],
1164
+ fallback: 'Outputs translated HTML/Word-compatible .doc/TXT locally without browser',
1165
+ outputs: ['Preserved original CV', 'Translated resume.html / resume.doc / resume.txt in logs/resumes/<slug>-<lang>/'],
1166
+ },
1167
+ {
1168
+ intent: 'cv-convert',
1169
+ matches: q => /\b(convert|export|make|create)\b/i.test(q) && /\b(pdf|word|word-compatible|docx|doc|html|txt)\b/i.test(q) && /\b(cv|resume)\b/i.test(q),
1170
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify'],
1171
+ workflow: null,
1172
+ readiness: 'task-specific (source CV; no /setup required)',
1173
+ required_inputs: ['source CV'],
1174
+ optional_tools: ['playwright (for PDF export)'],
1175
+ fallback: 'If PDF/native DOCX unavailable, outputs HTML + Word-compatible .doc + TXT + Print-to-PDF instructions (never renames HTML to .docx)',
1176
+ outputs: ['resume.html', 'resume.doc (Word-compatible HTML)', 'resume.txt', 'resume.pdf (when PDF export exists)'],
1177
+ },
1178
+ {
1179
+ intent: 'cv-create',
1180
+ matches: q => /\b(create|build|write|make)\b/i.test(q) && /\b(new cv|cv from scratch|resume from scratch|from scratch)\b/i.test(q),
1181
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify', '28-recruiter-brand-and-domain-intelligence'],
1182
+ workflow: null,
1183
+ readiness: 'task-specific (guided interview; zero /setup or browser login required)',
1184
+ required_inputs: ['guided interview answers (contact, roles/dates, projects, skills, education)'],
1185
+ optional_tools: ['playwright (optional for PDF export)'],
1186
+ fallback: 'Writes confirmed profile + ATS HTML/Word-compatible .doc/TXT locally',
1187
+ outputs: ['Confirmed Fact Table', 'context/profile.md + cv.md (when saving)', 'ATS resume.html / resume.doc / resume.txt'],
1188
+ },
1189
+ {
1190
+ intent: 'cv-edit',
1191
+ matches: q => /\b(improve|edit|update|rewrite|strengthen|shorten|reorder|remove|add .*project|change .*summary|summary|bullet)\b/i.test(q) && /\b(cv|resume|summary|project|skills|bullets|section|page)\b/i.test(q),
1192
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify', '28-recruiter-brand-and-domain-intelligence', 'meta-self-verification'],
1193
+ workflow: null,
1194
+ readiness: 'task-specific (existing CV or session CV + requested edit; preserves original)',
1195
+ required_inputs: ['existing CV (if not already loaded)', 'requested section change'],
1196
+ optional_tools: ['playwright (optional for PDF export)'],
1197
+ fallback: 'Modifies only requested sections locally, preserves original, re-reads outputs to verify',
1198
+ outputs: ['Preserved original CV', 'Verified revised resume.html / resume.doc / resume.txt + diff summary'],
1199
+ },
1200
+ {
1201
+ intent: 'cv-review-import',
1202
+ matches: q => /\b(upload|import|review|audit|check|read|parse)\b/i.test(q) && /\b(cv|resume)\b/i.test(q),
1203
+ skills: ['01-resume-ingestion', '14-privacy-pii-shield'],
1204
+ workflow: null,
1205
+ readiness: 'task-specific (CV file or pasted text; no /setup or browser login required)',
1206
+ required_inputs: ['CV file (.md/.txt/.docx/.html/readable .pdf) or pasted text'],
1207
+ optional_tools: ['playwright (optional only for PDF reading when native PDF reader unavailable)'],
1208
+ fallback: 'Built-in CLI/text extraction; warns if PDF is scanned/unreadable and requests pasted text',
1209
+ outputs: ['Extracted Fact Table for confirmation', 'Actionable CV hygiene & structure review'],
1210
+ },
1211
+ ];
1212
+
1213
+ export function matchNaturalLanguageRoute(query) {
1214
+ const q = String(query || '').trim();
1215
+ if (!q) {
1216
+ throw new Error('Usage: veycraft route "<natural-language request>" [--json]');
1217
+ }
1218
+ const hit = ROUTE_RULES.find(r => r.matches(q)) || {
1219
+ intent: 'general-career-assistant',
1220
+ skills: ['01-resume-ingestion', '03-tailor-resume-and-verify'],
1221
+ workflow: null,
1222
+ readiness: 'task-specific (ask one clarifying question for missing goal/file)',
1223
+ required_inputs: ['clarify desired career outcome or share CV/JD'],
1224
+ optional_tools: ['playwright', 'notion'],
1225
+ fallback: 'Inspect context/ first and ask 1 targeted question',
1226
+ outputs: ['Focused next step without forcing /setup'],
1227
+ };
1228
+ return { query: q, ...hit };
1229
+ }
1230
+
1231
+ export function verifyArtifactFile(filePath, factsConfig = null) {
1232
+ const errors = [];
1233
+ const warnings = [];
1234
+ const ext = path.extname(filePath).toLowerCase();
1235
+ const name = path.basename(filePath);
1236
+ if (ext === '.docx') {
1237
+ let rawBuf;
1238
+ try {
1239
+ rawBuf = readFileBoundedSync(filePath, DOCX_LIMITS.MAX_INPUT_BYTES, '.docx file');
1240
+ } catch (e) {
1241
+ errors.push(`${name}: ${e.message}`);
1242
+ return { name, errors, warnings };
1243
+ }
1244
+ if (rawBuf.length === 0) {
1245
+ errors.push(`${name}: file is empty (0 bytes)`);
1246
+ return { name, errors, warnings };
1247
+ }
1248
+ try {
1249
+ extractDocxText(rawBuf);
1250
+ } catch (e) {
1251
+ errors.push(`${name}: ${e.message}`);
1252
+ }
1253
+ return { name, errors, warnings };
1254
+ }
1255
+ const rawBuf = fs.readFileSync(filePath);
1256
+
1257
+ if (rawBuf.length === 0) {
1258
+ errors.push(`${name}: file is empty (0 bytes)`);
1259
+ return { name, errors, warnings };
1260
+ }
1261
+ if (ext === '.pdf') {
1262
+ if (rawBuf.subarray(0, 5).toString('utf8') !== '%PDF-') {
1263
+ errors.push(`${name}: invalid PDF header (does not start with %PDF-)`);
1264
+ } else if (rawBuf.length > 200 * 1024) {
1265
+ warnings.push(`${name}: PDF size is ${Math.round(rawBuf.length / 1024)} KB (target <= 200 KB)`);
1266
+ }
1267
+ return { name, errors, warnings };
1268
+ }
1269
+ if (ext === '.json') {
1270
+ let parsed;
1271
+ try {
1272
+ parsed = JSON.parse(rawBuf.toString('utf8'));
1273
+ } catch (e) {
1274
+ errors.push(`${name}: invalid JSON (${e.message})`);
1275
+ return { name, errors, warnings };
1276
+ }
1277
+ if (isObj(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'schema_version') && Object.prototype.hasOwnProperty.call(parsed, 'changes')) {
1278
+ const res = validateProfileUpdatePlan(parsed, { factsConfig });
1279
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1280
+ }
1281
+ if (isObj(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'fact_provenance')) {
1282
+ const res = validateProfileVault(parsed);
1283
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1284
+ }
1285
+ const isSkippedJobsArray = Array.isArray(parsed) && (
1286
+ /^skipped-jobs\.json$/i.test(name) ||
1287
+ (parsed.length > 0 && parsed.every(item => isObj(item) && (Object.prototype.hasOwnProperty.call(item, 'skip_reason') || Object.prototype.hasOwnProperty.call(item, 'skipped_at')) && !Object.prototype.hasOwnProperty.call(item, 'status')))
1288
+ );
1289
+ const isApplicationLedgerArray = Array.isArray(parsed) && !isSkippedJobsArray && (
1290
+ /^applications-log\.json$/i.test(name) ||
1291
+ (parsed.length > 0 && parsed.some(item => isObj(item) && (Object.prototype.hasOwnProperty.call(item, 'application_id') || (Object.prototype.hasOwnProperty.call(item, 'job_id') && Object.prototype.hasOwnProperty.call(item, 'status')))))
1292
+ );
1293
+ if (isApplicationLedgerArray) {
1294
+ const res = validateApplicationLedger(parsed);
1295
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1296
+ }
1297
+ if (isObj(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'schema_version') && Array.isArray(parsed.versions)) {
1298
+ const res = validateCvVersionsRegistry(parsed);
1299
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1300
+ }
1301
+ if (isObj(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'run_id') && Object.prototype.hasOwnProperty.call(parsed, 'counts')) {
1302
+ const res = validateDailyRun(parsed);
1303
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1304
+ }
1305
+ if (isObj(parsed) && parsed.kind === 'session_checkpoint') {
1306
+ const res = validateSessionCheckpoint(parsed);
1307
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1308
+ }
1309
+ if (isObj(parsed) && Object.prototype.hasOwnProperty.call(parsed, 'type') && Object.prototype.hasOwnProperty.call(parsed, 'period') && Object.prototype.hasOwnProperty.call(parsed, 'generated_at')) {
1310
+ const res = validateCareerInsights(parsed);
1311
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1312
+ }
1313
+ if (isObj(parsed) && parsed.eligibility_policy === 'submitted_only' && Array.isArray(parsed.operations)) {
1314
+ const res = validateNotionSyncPlan(parsed);
1315
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1316
+ }
1317
+ if (isObj(parsed) && parsed.schema_version === '1.0' && isObj(parsed.records) && Object.prototype.hasOwnProperty.call(parsed, 'updated_at')) {
1318
+ const res = verifySyncStateIntegrity(parsed);
1319
+ return { name, errors: res.errors.map(err => `${name}: ${err}`), warnings: res.warnings };
1320
+ }
1321
+ return { name, errors, warnings };
1322
+ }
1323
+
1324
+ const rawText = rawBuf.toString('utf8');
1325
+ const textRes = verifyArtifactText(rawText, { format: ext, name, factsConfig });
1326
+ return { name: textRes.name, errors: textRes.errors, warnings: textRes.warnings };
1327
+ }
1328
+
1329
+ export function verifyArtifactText(rawText, {
1330
+ format = 'html',
1331
+ name = 'inline.html',
1332
+ factsConfig = null,
1333
+ factsText = null,
1334
+ factsJson = null,
1335
+ } = {}) {
1336
+ if (typeof rawText !== 'string') {
1337
+ throw new Error('Artifact text must be a string.');
1338
+ }
1339
+ const errors = [];
1340
+ const warnings = [];
1341
+ const cleanFormat = String(format || path.extname(name) || 'html').toLowerCase().replace(/^\./, '') || 'html';
1342
+ const ext = `.${cleanFormat}`;
1343
+ if (rawText.length === 0) {
1344
+ errors.push(`${name}: file is empty (0 bytes)`);
1345
+ return { name, format: cleanFormat, ok: false, errors, warnings };
1346
+ }
1347
+
1348
+ let effectiveFacts = factsConfig;
1349
+ if (!effectiveFacts && isObj(factsJson)) {
1350
+ const allowedMetrics = new Set(
1351
+ (Array.isArray(factsJson.ground_truth_metrics) ? factsJson.ground_truth_metrics : []).map(m => String(m).trim().toLowerCase()),
1352
+ );
1353
+ const forbiddenSkills = Array.isArray(factsJson.forbidden_skills)
1354
+ ? factsJson.forbidden_skills.filter(s => typeof s === 'string' && s.trim())
1355
+ : [];
1356
+ effectiveFacts = { allowedMetrics, forbiddenSkills };
1357
+ } else if (!effectiveFacts && typeof factsText === 'string' && factsText.trim()) {
1358
+ const metricTokenRe = /(?<![A-Za-z0-9_])\$?\d[\d,]*(?:\.\d+)?(?:\s*(?:%|k|m|b|x|ms|sec|seconds|min|minutes|hrs|hours|days|weeks|months|years)\b|%|[KMBX]\b|\+)/gi;
1359
+ const allowedMetrics = new Set((factsText.match(metricTokenRe) || []).map(m => m.trim().toLowerCase()));
1360
+ effectiveFacts = { allowedMetrics, forbiddenSkills: [] };
1361
+ }
1362
+
1363
+ if (/\{\{[A-Za-z0-9_]+\}\}/.test(rawText)) {
1364
+ const matches = rawText.match(/\{\{[A-Za-z0-9_]+\}\}/g) || [];
1365
+ errors.push(`${name}: unresolved template placeholder(s): ${[...new Set(matches)].join(', ')}`);
1366
+ }
1367
+
1368
+ let prose = rawText;
1369
+ const isNotesDoc = /^(?:tailoring-notes|interview-dossier)\b/i.test(name);
1370
+ const isLinkedinAudit = /^linkedin-seo-audit\b/i.test(name);
1371
+ if (ext === '.html' || ext === '.htm' || (ext === '.doc' && /<html|<body/i.test(rawText))) {
1372
+ const bodyWithoutTitle = rawText.replace(/<title\b[^>]*>[\s\S]*?<\/title>/gi, ' ');
1373
+ const proseMatches = [...bodyWithoutTitle.matchAll(/<(?:p|li)\b[^>]*>([\s\S]*?)<\/(?:p|li)>/gi)];
1374
+ prose = proseMatches.map(m => extractHtmlText(m[1])).join('\n') || extractHtmlText(bodyWithoutTitle);
1375
+ const fullPlain = extractHtmlText(bodyWithoutTitle);
1376
+ const cliches = BANNED_AI_CLICHES.filter(cl => buildSkillRegex(cl).test(fullPlain));
1377
+ if (cliches.length > 0) errors.push(`${name}: banned AI cliché(s) found: ${cliches.join(', ')}`);
1378
+ } else if (!isNotesDoc) {
1379
+ const nonHeadingLines = rawText
1380
+ .split(/\r?\n/)
1381
+ .filter(l => !/^\s*(?:#{1,6}\s|\*\*[^*]+—[^*]+\*\*)/.test(l));
1382
+ prose = nonHeadingLines.join('\n');
1383
+ const cliches = BANNED_AI_CLICHES.filter(cl => buildSkillRegex(cl).test(rawText));
1384
+ if (cliches.length > 0) errors.push(`${name}: banned AI cliché(s) found: ${cliches.join(', ')}`);
1385
+ }
1386
+
1387
+ if (!isNotesDoc && prose.includes('—')) {
1388
+ errors.push(`${name}: prose em-dash (—) detected inside paragraph/bullet text`);
1389
+ }
1390
+
1391
+ if (effectiveFacts && (ext === '.html' || ext === '.htm' || ext === '.doc' || ext === '.txt' || ext === '.md') && !isNotesDoc) {
1392
+ let plain = (ext === '.html' || ext === '.htm' || ext === '.doc') ? extractHtmlText(rawText) : rawText;
1393
+ if (isLinkedinAudit) {
1394
+ plain = plain.split(/\r?\n/).filter(l => !/True Gaps/i.test(l)).join('\n');
1395
+ }
1396
+ const metricTokenRe = /(?<![A-Za-z0-9_])\$?\d[\d,]*(?:\.\d+)?(?:\s*(?:%|k|m|b|x|ms|sec|seconds|min|minutes|hrs|hours|days|weeks|months|years)\b|%|[KMBX]\b|\+)/gi;
1397
+ const foundMetrics = plain.match(metricTokenRe) || [];
1398
+ const unverified = foundMetrics.filter(tok => !effectiveFacts.allowedMetrics.has(tok.trim().toLowerCase()));
1399
+ if (unverified.length > 0) {
1400
+ errors.push(`${name}: unverified metric token(s) not in source facts: ${[...new Set(unverified)].join(', ')}`);
1401
+ }
1402
+ const forbidden = effectiveFacts.forbiddenSkills.filter(sk => buildSkillRegex(sk).test(plain));
1403
+ if (forbidden.length > 0) {
1404
+ errors.push(`${name}: forbidden/unclaimed skill(s) found: ${forbidden.join(', ')}`);
1405
+ }
1406
+ }
1407
+ return { name, format: cleanFormat, ok: errors.length === 0, errors, warnings };
1408
+ }
1409
+
1410
+ export function loadFactsConfig(factsPath, { root, source, home = os.homedir(), cwd = process.cwd() } = {}) {
1411
+ const factsInfo = assertSafeCliInputPath(factsPath, { label: 'facts file', root, source, home, cwd });
1412
+ if (!factsInfo.exists) throw new Error(`Facts file not found: ${factsInfo.resolved}`);
1413
+ const resolved = factsInfo.resolved;
1414
+ const text = fs.readFileSync(resolved, 'utf8');
1415
+ if (resolved.endsWith('.json')) {
1416
+ const parsed = JSON.parse(text);
1417
+ const allowedMetrics = new Set(
1418
+ (Array.isArray(parsed.ground_truth_metrics) ? parsed.ground_truth_metrics : []).map(m => String(m).trim().toLowerCase()),
1419
+ );
1420
+ const forbiddenSkills = Array.isArray(parsed.forbidden_skills) ? parsed.forbidden_skills : [];
1421
+ return { allowedMetrics, forbiddenSkills };
1422
+ }
1423
+ const metricTokenRe = /(?<![A-Za-z0-9_])\$?\d[\d,]*(?:\.\d+)?(?:\s*(?:%|k|m|b|x|ms|sec|seconds|min|minutes|hrs|hours|days|weeks|months|years)\b|%|[KMBX]\b|\+)/gi;
1424
+ const allowedMetrics = new Set((text.match(metricTokenRe) || []).map(m => m.trim().toLowerCase()));
1425
+ return { allowedMetrics, forbiddenSkills: [] };
1426
+ }
1427
+
1428
+ export function verifyArtifactTarget(targetArg, {
1429
+ factsPath = null,
1430
+ root,
1431
+ source,
1432
+ home = os.homedir(),
1433
+ cwd = process.cwd(),
1434
+ } = {}) {
1435
+ const targetInfo = assertSafeCliInputPath(targetArg, {
1436
+ label: 'verify target',
1437
+ allowDirectory: true,
1438
+ root,
1439
+ source,
1440
+ home,
1441
+ cwd,
1442
+ });
1443
+ if (!targetInfo.exists) {
1444
+ throw new Error(`Target path not found: ${targetInfo.resolved}`);
1445
+ }
1446
+ const resolved = targetInfo.resolved;
1447
+ const factsConfig = factsPath ? loadFactsConfig(factsPath, { root, source, home, cwd }) : null;
1448
+ const stat = targetInfo.stat;
1449
+ const files = stat.isDirectory()
1450
+ ? fs.readdirSync(resolved)
1451
+ .filter(f => /\.(html|doc|docx|txt|pdf|md)$/i.test(f))
1452
+ .sort()
1453
+ .map(f => {
1454
+ const childPath = path.join(resolved, f);
1455
+ refuseSymlinkBase(childPath, targetInfo.boundary, home);
1456
+ const childStat = fs.lstatSync(childPath);
1457
+ if (childStat.isSymbolicLink() || !childStat.isFile()) {
1458
+ throw new Error(`Refusing symbolic-link or non-regular file in verify directory: ${childPath}`);
1459
+ }
1460
+ return childPath;
1461
+ })
1462
+ : [resolved];
1463
+
1464
+ if (files.length === 0) {
1465
+ throw new Error(`No resume/deliverable files found in ${resolved}`);
1466
+ }
1467
+
1468
+ let errorCount = 0;
1469
+ let warningCount = 0;
1470
+ const results = [];
1471
+ for (const f of files) {
1472
+ const res = verifyArtifactFile(f, factsConfig);
1473
+ errorCount += res.errors.length;
1474
+ warningCount += res.warnings.length;
1475
+ results.push({
1476
+ name: res.name,
1477
+ path: f,
1478
+ ok: res.errors.length === 0,
1479
+ errors: res.errors,
1480
+ warnings: res.warnings,
1481
+ });
1482
+ }
1483
+
1484
+ return {
1485
+ resolved,
1486
+ file_count: files.length,
1487
+ error_count: errorCount,
1488
+ warning_count: warningCount,
1489
+ ok: errorCount === 0,
1490
+ results,
1491
+ };
1492
+ }
1493
+
1494
+ export function evaluatePreSubmitWithDraft(root, {
1495
+ platform = null,
1496
+ company = null,
1497
+ title = null,
1498
+ url = null,
1499
+ jobId = null,
1500
+ draft = null,
1501
+ text = null,
1502
+ maxWords = 75,
1503
+ } = {}, {
1504
+ home = os.homedir(),
1505
+ source,
1506
+ cwd = process.cwd(),
1507
+ } = {}) {
1508
+ const gate = evaluatePreSubmitGate(root, {
1509
+ platform,
1510
+ company,
1511
+ title,
1512
+ url,
1513
+ job_id: jobId,
1514
+ }, { home, sourceRoot: source });
1515
+
1516
+ const violations = [...gate.violations];
1517
+ const warnings = [];
1518
+ let draftReport = null;
1519
+
1520
+ let draftContent = null;
1521
+ let draftSource = null;
1522
+ if (draft) {
1523
+ const draftInfo = assertSafeCliInputPath(draft, { label: 'draft file', root, source, home, cwd });
1524
+ if (!draftInfo.exists) {
1525
+ throw new Error(`Draft file not found: ${draftInfo.resolved}`);
1526
+ }
1527
+ draftContent = fs.readFileSync(draftInfo.resolved, 'utf8');
1528
+ draftSource = draftInfo.resolved;
1529
+ } else if (text !== null && text !== undefined) {
1530
+ draftContent = String(text);
1531
+ draftSource = '--text';
1532
+ }
1533
+
1534
+ if (draftContent !== null) {
1535
+ const words = draftContent.trim().split(/\s+/).filter(Boolean);
1536
+ const wordCount = words.length;
1537
+ const hasEmDash = draftContent.includes('—');
1538
+ const bannedCliches = BANNED_AI_CLICHES.filter(cl => buildSkillRegex(cl).test(draftContent));
1539
+ draftReport = {
1540
+ source: draftSource,
1541
+ word_count: wordCount,
1542
+ max_words: maxWords,
1543
+ ok: wordCount > 0 && wordCount <= maxWords && bannedCliches.length === 0 && !hasEmDash,
1544
+ has_em_dash: hasEmDash,
1545
+ banned_cliches: bannedCliches,
1546
+ };
1547
+ if (wordCount === 0) {
1548
+ violations.push({ code: 'draft_empty', message: `Draft (${draftSource}) is empty (0 words).` });
1549
+ } else if (wordCount > maxWords) {
1550
+ violations.push({ code: 'draft_word_cap_exceeded', message: `Draft Word Cap EXCEEDED: ${wordCount}/${maxWords} words (${draftSource}). Trim before sending.` });
1551
+ }
1552
+ if (bannedCliches.length > 0) {
1553
+ violations.push({
1554
+ code: 'draft_banned_cliches',
1555
+ message: `Draft contains banned AI cliché(s) in ${draftSource}: ${bannedCliches.join(', ')}. Rewrite with plain, grounded language.`,
1556
+ });
1557
+ }
1558
+ if (hasEmDash) {
1559
+ violations.push({
1560
+ code: 'draft_prose_em_dash',
1561
+ message: `Draft contains prose em-dash (—) in ${draftSource}; replace with periods or commas before sending.`,
1562
+ });
1563
+ }
1564
+ }
1565
+
1566
+ const invFile = [path.join(root, 'config', 'invariants.txt'), path.join(source, 'config', 'invariants.txt')].find(f => fs.existsSync(f));
1567
+ const invariantsText = invFile ? fs.readFileSync(invFile, 'utf8').trim() : null;
1568
+
1569
+ return {
1570
+ root,
1571
+ allowed: violations.length === 0,
1572
+ dry_run: gate.dry_run,
1573
+ violations,
1574
+ warnings,
1575
+ checks: { ...gate.checks, draft: draftReport },
1576
+ invariants_file: invFile || null,
1577
+ invariants_text: invariantsText,
1578
+ };
1579
+ }
1580
+
1581
+ export const MCP_QUIET_NPM_ENV = Object.freeze({
1582
+ NPM_CONFIG_UPDATE_NOTIFIER: 'false',
1583
+ NPM_CONFIG_FUND: 'false',
1584
+ NPM_CONFIG_AUDIT: 'false',
1585
+ NPM_CONFIG_LOGLEVEL: 'error',
1586
+ });
1587
+
1588
+ export function toPlatformMcpServer(cfg, platform = process.platform) {
1589
+ const env = { ...MCP_QUIET_NPM_ENV, ...(isObj(cfg.env) ? cfg.env : {}) };
1590
+ if (platform === 'win32' && cfg.command === 'npx') {
1591
+ return {
1592
+ ...cfg,
1593
+ command: 'cmd',
1594
+ args: ['/c', 'npx', ...cfg.args],
1595
+ env,
1596
+ };
1597
+ }
1598
+ return { ...cfg, env };
1599
+ }
1600
+
1601
+ export function formatTomlMcpSection(name, cfg) {
1602
+ const q = v => JSON.stringify(String(v));
1603
+ const argsList = (cfg.args || []).map(q).join(', ');
1604
+ const envEntries = Object.entries(cfg.env || {})
1605
+ .map(([k, v]) => `${q(k)} = ${q(v)}`)
1606
+ .join(', ');
1607
+ const lines = [
1608
+ `[mcp_servers.${name}]`,
1609
+ `command = ${q(cfg.command)}`,
1610
+ `args = [${argsList}]`,
1611
+ ];
1612
+ if (envEntries) lines.push(`env = { ${envEntries} }`);
1613
+ return lines.join('\n') + '\n';
1614
+ }
1615
+
1616
+ export function findTomlSectionRange(lines, sectionHeader) {
1617
+ const start = lines.findIndex(line => line.trim() === sectionHeader);
1618
+ if (start === -1) return null;
1619
+ let end = lines.length;
1620
+ for (let i = start + 1; i < lines.length; i++) {
1621
+ if (/^\s*\[[^\]]+\]\s*$/.test(lines[i])) {
1622
+ end = i;
1623
+ break;
1624
+ }
1625
+ }
1626
+ return { start, end };
1627
+ }
1628
+
1629
+ export function upsertTomlMcpServer(tomlText, name, cfg) {
1630
+ const section = formatTomlMcpSection(name, cfg);
1631
+ const lines = tomlText ? tomlText.replace(/\r\n/g, '\n').split('\n') : [];
1632
+ const header = `[mcp_servers.${name}]`;
1633
+ const range = findTomlSectionRange(lines, header);
1634
+ if (range) {
1635
+ const existingBlock = lines
1636
+ .slice(range.start, range.end)
1637
+ .filter(l => l.trim() !== '')
1638
+ .join('\n') + '\n';
1639
+ const expectedBlock = section.trimEnd() + '\n';
1640
+ if (existingBlock === expectedBlock) return { status: 'unchanged', text: tomlText };
1641
+ return { status: 'preserved', text: tomlText };
1642
+ }
1643
+ const trimmed = tomlText.replace(/\r\n/g, '\n').trimEnd();
1644
+ const next = trimmed ? `${trimmed}\n\n${section}` : section;
1645
+ return { status: 'added', text: next };
1646
+ }
1647
+
1648
+ export function syncMcpConfigs({
1649
+ root,
1650
+ isGlobal = false,
1651
+ source = root,
1652
+ home = os.homedir(),
1653
+ env = process.env,
1654
+ platform = process.platform,
1655
+ withVeycraft = false,
1656
+ dryRun = false,
1657
+ backup = true,
1658
+ } = {}) {
1659
+ const resolvedRoot = path.resolve(root);
1660
+ const resolvedSource = path.resolve(source);
1661
+ const templatePath = [
1662
+ path.join(resolvedRoot, 'mcp', 'mcp.template.json'),
1663
+ path.join(resolvedSource, 'mcp', 'mcp.template.json'),
1664
+ ].find(f => fs.existsSync(f));
1665
+ if (!templatePath) throw new Error('mcp/mcp.template.json not found. Run init first.');
1666
+ const template = JSON.parse(fs.readFileSync(templatePath, 'utf8'));
1667
+ const tplPlaywright = template?.mcpServers?.playwright;
1668
+ if (!isObj(tplPlaywright) || !Array.isArray(tplPlaywright.args)) {
1669
+ throw new Error('Invalid mcp/mcp.template.json playwright server definition.');
1670
+ }
1671
+
1672
+ const profileDir = path.join(resolvedRoot, 'browser-profile');
1673
+ const rawPlaywrightCfg = {
1674
+ ...tplPlaywright,
1675
+ args: tplPlaywright.args.map(a => (a.startsWith('--user-data-dir=') ? `--user-data-dir=${profileDir}` : a)),
1676
+ };
1677
+ if (!rawPlaywrightCfg.args.some(a => a.startsWith('--user-data-dir='))) {
1678
+ rawPlaywrightCfg.args.push(`--user-data-dir=${profileDir}`);
1679
+ }
1680
+ const playwrightCfg = toPlatformMcpServer(rawPlaywrightCfg, platform);
1681
+ const notionCfg = isObj(template.mcpServers?.notion) && Array.isArray(template.mcpServers.notion.args)
1682
+ ? toPlatformMcpServer(template.mcpServers.notion, platform)
1683
+ : null;
1684
+
1685
+ let veycraftCfg = null;
1686
+ if (withVeycraft) {
1687
+ const rawVeycraftArgs = ['-y', 'veycraft', 'mcp', ...(isGlobal ? ['--global'] : [])];
1688
+ const rawVeycraftEnv = env.VEYCRAFT_HOME && String(env.VEYCRAFT_HOME).trim()
1689
+ ? { VEYCRAFT_HOME: path.resolve(String(env.VEYCRAFT_HOME).trim()) }
1690
+ : {};
1691
+ veycraftCfg = toPlatformMcpServer({
1692
+ command: 'npx',
1693
+ args: rawVeycraftArgs,
1694
+ env: rawVeycraftEnv,
1695
+ }, platform);
1696
+ }
1697
+
1698
+ let updated = 0;
1699
+ const warnings = [];
1700
+ const operations = [];
1701
+
1702
+ function writeTargetSafe(file, nextText, label) {
1703
+ refuseSymlinkBase(file, resolvedRoot, home);
1704
+ const existed = fs.existsSync(file);
1705
+ const prevText = existed ? fs.readFileSync(file, 'utf8') : null;
1706
+ if (existed && prevText === nextText) {
1707
+ operations.push({ file, label, action: 'unchanged', backup_path: null });
1708
+ return false;
1709
+ }
1710
+ const backupPath = existed && backup ? `${file}.veycraft.bak` : null;
1711
+ if (dryRun) {
1712
+ updated++;
1713
+ operations.push({
1714
+ file,
1715
+ label,
1716
+ action: existed ? 'would_update' : 'would_create',
1717
+ backup_path: backupPath,
1718
+ });
1719
+ return true;
1720
+ }
1721
+ if (existed && backupPath) {
1722
+ refuseSymlinkBase(backupPath, resolvedRoot, home);
1723
+ writeAtomicBase(backupPath, prevText, { preserve: false, mode: 0o600, boundary: resolvedRoot, home });
1724
+ }
1725
+ writeAtomicBase(file, nextText, { preserve: false, mode: 0o600, boundary: resolvedRoot, home });
1726
+ updated++;
1727
+ operations.push({
1728
+ file,
1729
+ label,
1730
+ action: existed ? 'updated' : 'created',
1731
+ backup_path: backupPath,
1732
+ });
1733
+ return true;
1734
+ }
1735
+
1736
+ const targets = mcpTargetFiles(resolvedRoot, isGlobal, home);
1737
+ for (const file of targets) {
1738
+ const current = readJsonSafeBase(file, { boundary: resolvedRoot, home });
1739
+ const servers = isObj(current.mcpServers) ? { ...current.mcpServers } : {};
1740
+ let allowPlaywrightMerge = true;
1741
+ if (servers.playwright && JSON.stringify(servers.playwright) !== JSON.stringify(playwrightCfg)) {
1742
+ warnings.push(`Preserved existing custom playwright MCP server in ${file}`);
1743
+ allowPlaywrightMerge = false;
1744
+ if (!withVeycraft) {
1745
+ operations.push({ file, label: 'Playwright MCP', action: 'preserved', backup_path: null });
1746
+ continue;
1747
+ }
1748
+ }
1749
+ if (allowPlaywrightMerge) {
1750
+ servers.playwright = playwrightCfg;
1751
+ if (env.NOTION_TOKEN && notionCfg && !servers.notion) {
1752
+ servers.notion = notionCfg;
1753
+ }
1754
+ }
1755
+ if (withVeycraft && veycraftCfg) {
1756
+ if (servers.veycraft && JSON.stringify(servers.veycraft) !== JSON.stringify(veycraftCfg)) {
1757
+ warnings.push(`Preserved existing custom veycraft MCP server in ${file}`);
1758
+ } else {
1759
+ servers.veycraft = veycraftCfg;
1760
+ }
1761
+ }
1762
+ const nextText = JSON.stringify({ ...current, mcpServers: servers }, null, 2) + '\n';
1763
+ writeTargetSafe(file, nextText, withVeycraft ? 'Playwright + Veycraft MCP' : 'Playwright MCP');
1764
+ }
1765
+
1766
+ if (!isGlobal) {
1767
+ const vscodeMcp = path.join(resolvedRoot, '.vscode', 'mcp.json');
1768
+ const current = readJsonSafeBase(vscodeMcp, { boundary: resolvedRoot, home });
1769
+ const servers = isObj(current.servers) ? { ...current.servers } : {};
1770
+ const vsPlaywright = { type: 'stdio', ...playwrightCfg };
1771
+ let allowVsPlaywright = true;
1772
+ if (servers.playwright && JSON.stringify(servers.playwright) !== JSON.stringify(vsPlaywright)) {
1773
+ warnings.push(`Preserved existing custom playwright MCP server in ${vscodeMcp}`);
1774
+ allowVsPlaywright = false;
1775
+ }
1776
+ if (allowVsPlaywright) {
1777
+ servers.playwright = vsPlaywright;
1778
+ if (env.NOTION_TOKEN && notionCfg && !servers.notion) {
1779
+ servers.notion = { type: 'stdio', ...notionCfg };
1780
+ }
1781
+ }
1782
+ if (withVeycraft && veycraftCfg) {
1783
+ const vsVeycraft = { type: 'stdio', ...veycraftCfg };
1784
+ if (servers.veycraft && JSON.stringify(servers.veycraft) !== JSON.stringify(vsVeycraft)) {
1785
+ warnings.push(`Preserved existing custom veycraft MCP server in ${vscodeMcp}`);
1786
+ } else {
1787
+ servers.veycraft = vsVeycraft;
1788
+ }
1789
+ }
1790
+ if (allowVsPlaywright || withVeycraft) {
1791
+ const nextText = JSON.stringify({ ...current, servers }, null, 2) + '\n';
1792
+ writeTargetSafe(vscodeMcp, nextText, 'VS Code MCP');
1793
+ } else {
1794
+ operations.push({ file: vscodeMcp, label: 'VS Code MCP', action: 'preserved', backup_path: null });
1795
+ }
1796
+ }
1797
+
1798
+ const codexToml = isGlobal
1799
+ ? path.join(resolveCodexHome(home, env), 'config.toml')
1800
+ : path.join(resolvedRoot, '.codex', 'config.toml');
1801
+ refuseSymlinkBase(codexToml, resolvedRoot, home);
1802
+ let tomlText = fs.existsSync(codexToml) ? fs.readFileSync(codexToml, 'utf8') : '';
1803
+ let tomlChanged = false;
1804
+ const pwRes = upsertTomlMcpServer(tomlText, 'playwright', playwrightCfg);
1805
+ if (pwRes.status === 'preserved') {
1806
+ warnings.push(`Preserved existing custom playwright MCP server in ${codexToml}`);
1807
+ } else {
1808
+ tomlText = pwRes.text;
1809
+ if (pwRes.status === 'added') tomlChanged = true;
1810
+ if (env.NOTION_TOKEN && notionCfg) {
1811
+ const notionRes = upsertTomlMcpServer(tomlText, 'notion', notionCfg);
1812
+ if (notionRes.status === 'added') {
1813
+ tomlText = notionRes.text;
1814
+ tomlChanged = true;
1815
+ }
1816
+ }
1817
+ }
1818
+ if (withVeycraft && veycraftCfg) {
1819
+ const vcRes = upsertTomlMcpServer(tomlText, 'veycraft', veycraftCfg);
1820
+ if (vcRes.status === 'preserved') {
1821
+ warnings.push(`Preserved existing custom veycraft MCP server in ${codexToml}`);
1822
+ } else if (vcRes.status === 'added') {
1823
+ tomlText = vcRes.text;
1824
+ tomlChanged = true;
1825
+ }
1826
+ }
1827
+ if (tomlChanged) {
1828
+ writeTargetSafe(codexToml, tomlText, 'Codex CLI MCP');
1829
+ } else {
1830
+ operations.push({
1831
+ file: codexToml,
1832
+ label: 'Codex CLI MCP',
1833
+ action: pwRes.status === 'preserved' ? 'preserved' : 'unchanged',
1834
+ backup_path: null,
1835
+ });
1836
+ }
1837
+
1838
+ if (!dryRun && notionCfg) {
1839
+ writeAtomicBase(
1840
+ path.join(resolvedRoot, 'mcp', 'notion.import.json'),
1841
+ JSON.stringify({ mcpServers: { notion: notionCfg } }, null, 2) + '\n',
1842
+ { preserve: true, mode: 0o600, boundary: resolvedRoot, home },
1843
+ );
1844
+ }
1845
+
1846
+ return {
1847
+ root: resolvedRoot,
1848
+ is_global: Boolean(isGlobal),
1849
+ dry_run: Boolean(dryRun),
1850
+ with_veycraft: Boolean(withVeycraft),
1851
+ updated,
1852
+ operations,
1853
+ warnings,
1854
+ };
1855
+ }