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,1392 @@
1
+ // Zero-dependency Token-Efficiency Fast-Path Engine for Veycraft:
2
+ // 1. Compact Candidate Brief compiler (context/brief.json < 400 tokens, mtime+sha256 cache-invalidated, zero PII).
3
+ // 2. Zero-Token Public RSS/Atom/JSON Feed Scanner (SEC-01 SSRF-pinned, deduped, prompt-injection sanitized, local fit-scored).
4
+ // 3. Scoped CLI dispatcher for `veycraft brief`, `veycraft feed-scan`, and `veycraft browser-script`.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import readline from 'node:readline/promises';
10
+ import {
11
+ isObj,
12
+ isWithinDir,
13
+ refuseSymlink,
14
+ writeAtomic,
15
+ readFileBoundedSync,
16
+ fetchTextWithSafeRedirects,
17
+ decodeXmlHtmlEntities,
18
+ stripMarkupTags,
19
+ } from './fs-safety.mjs';
20
+ import { PAYLOAD_NAMES, getBrowserPayload } from './browser-payloads.mjs';
21
+
22
+ const TEMPLATE_PLACEHOLDER_RE = /\{\{[^{}\r\n]+\}\}|\[\s*(?:YOUR|INSERT|REPLACE|TODO)[^\]\r\n]*\]/i;
23
+
24
+ export const BRIEF_SCHEMA_VERSION = 1;
25
+ export const BRIEF_MAX_BYTES = 1550; // Strictly < 400 tokens (~bytes/4)
26
+ const MAX_LOCAL_FEED_BYTES = 2 * 1024 * 1024; // 2 MB
27
+
28
+ const BRIEF_SOURCES = [
29
+ 'context/cv.md',
30
+ 'context/profile.md',
31
+ 'context/preferences.yaml',
32
+ 'context/form-answers.yaml',
33
+ 'context/resume-facts.json',
34
+ 'context/github-projects.md',
35
+ ];
36
+
37
+ const INJECTION_PATTERNS = [
38
+ { code: 'ignore_instructions', re: /\bignore\s+(?:all\s+)?(?:previous|prior)\s+instructions?\b/i },
39
+ { code: 'system_prompt_ref', re: /\b(?:system\s+prompt|developer\s+message|disregard\s+guardrails)\b/i },
40
+ { code: 'secret_exfil', re: /\b(?:reveal|print|send|exfiltrate)\s+(?:your\s+)?(?:\.env|api\s+key|token|cookie|password)\b/i },
41
+ { code: 'forced_submit', re: /\b(?:auto[- ]?submit|click\s+submit\s+immediately|bypass\s+approve)\b/i },
42
+ ];
43
+
44
+ const PII_LINE_RE = /\b(?:phone|mobile|tel|whatsapp|passport|ssn|national\s+id|street\s+address|home\s+address|date\s+of\s+birth)\b|\+\d[\d\s()-]{7,}|\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/i;
45
+
46
+ function stripInvisibleAndBiDi(str) {
47
+ let out = '';
48
+ const s = String(str || '');
49
+ for (let i = 0; i < s.length; i++) {
50
+ const cp = s.codePointAt(i);
51
+ if (cp > 0xffff) i++;
52
+ if ((cp >= 0xe0000 && cp <= 0xe007f) || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069)) {
53
+ continue;
54
+ }
55
+ out += String.fromCodePoint(cp);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ export function sanitizeUntrustedSnippet(raw, maxLen = 220) {
61
+ const cleaned = stripInvisibleAndBiDi(decodeXmlHtmlEntities(stripMarkupTags(String(raw || ''))))
62
+ .replace(/\s+/g, ' ')
63
+ .trim();
64
+ const injectionFlags = [];
65
+ for (const { code, re } of INJECTION_PATTERNS) {
66
+ if (re.test(cleaned)) injectionFlags.push(code);
67
+ }
68
+ return {
69
+ text: cleaned.slice(0, maxLen),
70
+ injection_flags: injectionFlags,
71
+ };
72
+ }
73
+
74
+ function sha256Short(bufOrStr) {
75
+ return crypto.createHash('sha256').update(bufOrStr).digest('hex').slice(0, 12);
76
+ }
77
+
78
+ function readOptionalText(absPath, root, home) {
79
+ if (!fs.existsSync(absPath)) return null;
80
+ refuseSymlink(absPath, root, home);
81
+ const st = fs.lstatSync(absPath);
82
+ if (!st.isFile()) return null;
83
+ const content = readFileBoundedSync(absPath, 512 * 1024, path.basename(absPath)).toString('utf8');
84
+ return { content, mtimeMs: Math.floor(st.mtimeMs), size: st.size, sha: sha256Short(content) };
85
+ }
86
+
87
+ function extractSimpleYamlList(yamlText, key) {
88
+ if (!yamlText) return [];
89
+ const lines = yamlText.split(/\r?\n/);
90
+ const out = [];
91
+ let inBlock = false;
92
+ let baseIndent = 0;
93
+ for (const raw of lines) {
94
+ const line = raw.replace(/\s+#.*$/, '');
95
+ if (!inBlock) {
96
+ const m = line.match(new RegExp(`^(\\s*)${key}\\s*:\\s*(.*)$`));
97
+ if (m) {
98
+ baseIndent = m[1].length;
99
+ const inline = m[2].trim();
100
+ if (inline.startsWith('[') && inline.endsWith(']')) {
101
+ return inline.slice(1, -1).split(',').map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
102
+ }
103
+ inBlock = true;
104
+ }
105
+ continue;
106
+ }
107
+ if (!line.trim()) continue;
108
+ const indent = line.match(/^(\s*)/)[1].length;
109
+ if (indent <= baseIndent && !line.trim().startsWith('-')) break;
110
+ const item = line.trim().match(/^-\s*(.+)$/);
111
+ if (item) {
112
+ const val = item[1].trim().replace(/^["']|["']$/g, '');
113
+ if (val && !TEMPLATE_PLACEHOLDER_RE.test(val)) out.push(val);
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+
119
+ function extractSimpleYamlScalar(yamlText, key) {
120
+ if (!yamlText) return null;
121
+ const m = yamlText.match(new RegExp(`^\\s*${key}\\s*:\\s*([^\\n#]+)`, 'm'));
122
+ if (!m) return null;
123
+ const val = m[1].trim().replace(/^["']|["']$/g, '');
124
+ if (!val || TEMPLATE_PLACEHOLDER_RE.test(val)) return null;
125
+ return val;
126
+ }
127
+
128
+ function extractHeadline(profileText, cvText) {
129
+ for (const src of [profileText, cvText]) {
130
+ if (!src) continue;
131
+ const roleMatch = src.match(/(?:Headline|Title|Role)\s*:\s*([^\n]+)/i);
132
+ if (roleMatch && !TEMPLATE_PLACEHOLDER_RE.test(roleMatch[1]) && !PII_LINE_RE.test(roleMatch[1])) {
133
+ return roleMatch[1].replace(/[*_`#]/g, '').trim().slice(0, 100);
134
+ }
135
+ for (const line of src.split(/\r?\n/).slice(0, 12)) {
136
+ const t = line.replace(/^#+\s*/, '').replace(/[*_`]/g, '').trim();
137
+ if (!t || t.length < 10 || t.length > 120) continue;
138
+ if (PII_LINE_RE.test(t) || TEMPLATE_PLACEHOLDER_RE.test(t)) continue;
139
+ if (/\b(engineer|developer|architect|designer|manager|analyst|consultant|specialist|scientist|full[- ]?stack|backend|frontend)\b/i.test(t)) {
140
+ return t.slice(0, 100);
141
+ }
142
+ }
143
+ }
144
+ return 'Verified Candidate Profile';
145
+ }
146
+
147
+ function extractSkills(factsObj, cvText, prefText) {
148
+ const skills = [];
149
+ const add = (s) => {
150
+ const clean = String(s || '').replace(/[*_`]/g, '').trim();
151
+ if (!clean || clean.length > 32 || TEMPLATE_PLACEHOLDER_RE.test(clean) || PII_LINE_RE.test(clean)) return;
152
+ if (!skills.some(x => x.toLowerCase() === clean.toLowerCase())) skills.push(clean);
153
+ };
154
+
155
+ if (factsObj) {
156
+ for (const arrKey of ['verified_skills', 'skills', 'core_skills', 'tech_stack']) {
157
+ if (Array.isArray(factsObj[arrKey])) {
158
+ for (const item of factsObj[arrKey]) {
159
+ add(typeof item === 'string' ? item : item?.name || item?.skill);
160
+ }
161
+ }
162
+ }
163
+ if (isObj(factsObj.skills_years)) {
164
+ for (const k of Object.keys(factsObj.skills_years)) add(k);
165
+ }
166
+ }
167
+
168
+ for (const s of extractSimpleYamlList(prefText, 'skills')) add(s);
169
+ for (const s of extractSimpleYamlList(prefText, 'core_skills')) add(s);
170
+
171
+ if (cvText) {
172
+ const lines = cvText.split(/\r?\n/);
173
+ for (const line of lines) {
174
+ if (/\b(skills|technologies|stack|languages|frameworks|tools)\b\s*[:|]/i.test(line)) {
175
+ const rhs = line.split(/[:|]/).slice(1).join(',');
176
+ for (const tok of rhs.split(/[,•·/]/)) {
177
+ const clean = tok.replace(/[*_`()]/g, '').trim();
178
+ if (clean.length >= 2 && clean.length <= 28 && !/\b(and|with|years?|months?)\b/i.test(clean)) {
179
+ add(clean);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ }
185
+ return skills.slice(0, 12);
186
+ }
187
+
188
+ function extractTopProofs(cvText, ghProjectsText) {
189
+ const proofs = [];
190
+ const sources = [cvText, ghProjectsText].filter(Boolean);
191
+ for (const src of sources) {
192
+ for (const raw of src.split(/\r?\n/)) {
193
+ const m = raw.trim().match(/^[-*•]\s+(.+)$/);
194
+ if (!m) continue;
195
+ const clean = m[1].replace(/\[[^\]]+\]\([^)]+\)/g, '').replace(/[*_`]/g, '').replace(/\s+/g, ' ').trim();
196
+ if (clean.length < 24 || TEMPLATE_PLACEHOLDER_RE.test(clean) || PII_LINE_RE.test(clean)) continue;
197
+ const hasSignal = /\d+%|\$\d|\d+\+|\d+x\b|\b(built|shipped|reduced|improved|launched|architected|designed|delivered)\b/i.test(clean);
198
+ if (hasSignal && !proofs.includes(clean.slice(0, 105))) {
199
+ proofs.push(clean.slice(0, 105));
200
+ }
201
+ if (proofs.length >= 4) return proofs;
202
+ }
203
+ }
204
+ return proofs;
205
+ }
206
+
207
+ function extractVerifiedLinks(profileText, cvText) {
208
+ const combined = `${profileText || ''}\n${cvText || ''}`;
209
+ const urls = combined.match(/https:\/\/[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=-]+/g) || [];
210
+ const links = {};
211
+ for (const raw of urls) {
212
+ const u = raw.replace(/[),.;]+$/, '');
213
+ if (TEMPLATE_PLACEHOLDER_RE.test(u) || /example\.com|your-?handle|username/i.test(u)) continue;
214
+ if (/github\.com\/[A-Za-z0-9_-]+/i.test(u) && !links.github) links.github = u;
215
+ else if (/linkedin\.com\/in\//i.test(u) && !links.linkedin) links.linkedin = u;
216
+ else if (!/github\.com|linkedin\.com/i.test(u) && !links.portfolio) links.portfolio = u;
217
+ }
218
+ return links;
219
+ }
220
+
221
+ function trimBriefToBudget(brief, maxBytes = BRIEF_MAX_BYTES) {
222
+ const copy = JSON.parse(JSON.stringify(brief));
223
+ const sizeOf = (obj) => Buffer.byteLength(JSON.stringify(obj), 'utf8');
224
+ while (sizeOf(copy) > maxBytes && copy.top_proofs.length > 1) {
225
+ copy.top_proofs.pop();
226
+ }
227
+ while (sizeOf(copy) > maxBytes && copy.core_stack.length > 6) {
228
+ copy.core_stack.pop();
229
+ }
230
+ if (sizeOf(copy) > maxBytes) {
231
+ copy.top_proofs = copy.top_proofs.map(p => p.slice(0, 72));
232
+ copy.headline = copy.headline.slice(0, 72);
233
+ }
234
+ while (sizeOf(copy) > maxBytes && copy.constraints?.blacklist?.length > 0) {
235
+ copy.constraints.blacklist.pop();
236
+ }
237
+ if (sizeOf(copy) > maxBytes && copy.forbidden_unverified_claims?.length > 4) {
238
+ copy.forbidden_unverified_claims = copy.forbidden_unverified_claims.slice(0, 4);
239
+ }
240
+ return copy;
241
+ }
242
+
243
+ export function compileCandidateBrief(root, { refresh = false, write = true, home = os.homedir() } = {}) {
244
+ const resolvedRoot = path.resolve(root);
245
+ const briefPath = path.join(resolvedRoot, 'context', 'brief.json');
246
+
247
+ const sourceMap = {};
248
+ const loaded = {};
249
+ const missingSources = [];
250
+ let hasRealSource = false;
251
+
252
+ for (const rel of BRIEF_SOURCES) {
253
+ const abs = path.join(resolvedRoot, rel);
254
+ const data = readOptionalText(abs, resolvedRoot, home);
255
+ if (!data) {
256
+ missingSources.push(rel);
257
+ continue;
258
+ }
259
+ loaded[rel] = data.content;
260
+ sourceMap[rel] = { mtimeMs: data.mtimeMs, sha: data.sha };
261
+ if (!TEMPLATE_PLACEHOLDER_RE.test(data.content)) hasRealSource = true;
262
+ }
263
+
264
+ if (Object.keys(loaded).length === 0 || !hasRealSource) {
265
+ return {
266
+ ok: true,
267
+ brief_ready: false,
268
+ cached: false,
269
+ path: briefPath,
270
+ missing_sources: missingSources,
271
+ reason: Object.keys(loaded).length === 0
272
+ ? 'No context/ source files found (cv.md, profile.md, preferences.yaml, resume-facts.json).'
273
+ : 'All detected context/ files still contain unresolved {{PLACEHOLDER}} template markers.',
274
+ brief: null,
275
+ };
276
+ }
277
+
278
+ const combinedHash = sha256Short(JSON.stringify(sourceMap));
279
+
280
+ if (!refresh && fs.existsSync(briefPath)) {
281
+ try {
282
+ refuseSymlink(briefPath, resolvedRoot, home);
283
+ const existingRaw = fs.readFileSync(briefPath, 'utf8');
284
+ const existing = JSON.parse(existingRaw);
285
+ if (
286
+ isObj(existing) &&
287
+ existing.schema_version === BRIEF_SCHEMA_VERSION &&
288
+ existing._cache?.hash === combinedHash &&
289
+ Buffer.byteLength(existingRaw, 'utf8') <= BRIEF_MAX_BYTES + 64
290
+ ) {
291
+ return {
292
+ ok: true,
293
+ brief_ready: true,
294
+ cached: true,
295
+ path: briefPath,
296
+ bytes: Buffer.byteLength(existingRaw, 'utf8'),
297
+ est_tokens: Math.ceil(Buffer.byteLength(existingRaw, 'utf8') / 4),
298
+ brief: existing,
299
+ };
300
+ }
301
+ } catch {
302
+ // Cache corrupt or unreadable; recompile cleanly below.
303
+ }
304
+ }
305
+
306
+ let factsObj = null;
307
+ if (loaded['context/resume-facts.json']) {
308
+ try { factsObj = JSON.parse(loaded['context/resume-facts.json']); } catch { factsObj = null; }
309
+ }
310
+
311
+ const prefText = loaded['context/preferences.yaml'] || '';
312
+ const formText = loaded['context/form-answers.yaml'] || '';
313
+ const minSalaryRaw = extractSimpleYamlScalar(prefText, 'min_salary') || extractSimpleYamlScalar(formText, 'min_salary') || extractSimpleYamlScalar(prefText, 'min_budget');
314
+ const minHourlyRaw = extractSimpleYamlScalar(prefText, 'min_hourly_rate') || extractSimpleYamlScalar(prefText, 'min_hourly');
315
+ const currency = extractSimpleYamlScalar(prefText, 'currency') || extractSimpleYamlScalar(formText, 'currency') || 'USD';
316
+ const remoteRaw = extractSimpleYamlScalar(prefText, 'work_mode') || extractSimpleYamlScalar(prefText, 'remote_only');
317
+ const blacklist = [
318
+ ...extractSimpleYamlList(prefText, 'blacklisted_companies'),
319
+ ...extractSimpleYamlList(prefText, 'blacklisted_domains'),
320
+ ].slice(0, 8);
321
+ const languages = extractSimpleYamlList(prefText, 'languages');
322
+ const forbidden = Array.isArray(factsObj?.forbidden_skills)
323
+ ? factsObj.forbidden_skills.filter(s => typeof s === 'string').slice(0, 8)
324
+ : [];
325
+
326
+ const rawBrief = {
327
+ schema_version: BRIEF_SCHEMA_VERSION,
328
+ generated_at: new Date().toISOString(),
329
+ headline: extractHeadline(loaded['context/profile.md'], loaded['context/cv.md']),
330
+ core_stack: extractSkills(factsObj, loaded['context/cv.md'], prefText),
331
+ top_proofs: extractTopProofs(loaded['context/cv.md'], loaded['context/github-projects.md']),
332
+ rate_floor: {
333
+ currency,
334
+ ...(minSalaryRaw && Number.isFinite(Number(minSalaryRaw)) ? { min_budget: Number(minSalaryRaw) } : {}),
335
+ ...(minHourlyRaw && Number.isFinite(Number(minHourlyRaw)) ? { min_hourly: Number(minHourlyRaw) } : {}),
336
+ },
337
+ constraints: {
338
+ remote_only: remoteRaw ? /remote|true/i.test(remoteRaw) : true,
339
+ languages: languages.length ? languages.slice(0, 4) : ['en'],
340
+ blacklist,
341
+ },
342
+ verified_links: extractVerifiedLinks(loaded['context/profile.md'], loaded['context/cv.md']),
343
+ forbidden_unverified_claims: forbidden,
344
+ _cache: {
345
+ schema_version: BRIEF_SCHEMA_VERSION,
346
+ hash: combinedHash,
347
+ },
348
+ };
349
+
350
+ const finalBrief = trimBriefToBudget(rawBrief, BRIEF_MAX_BYTES);
351
+ const serialized = `${JSON.stringify(finalBrief)}\n`;
352
+ if (write) {
353
+ writeAtomic(briefPath, serialized, { boundary: resolvedRoot, home });
354
+ }
355
+
356
+ return {
357
+ ok: true,
358
+ brief_ready: true,
359
+ cached: false,
360
+ path: briefPath,
361
+ bytes: Buffer.byteLength(serialized, 'utf8'),
362
+ est_tokens: Math.ceil(Buffer.byteLength(serialized, 'utf8') / 4),
363
+ brief: finalBrief,
364
+ };
365
+ }
366
+
367
+ // ---------------- Zero-Token Public RSS/Atom/JSON Feed Parser & Local Ranker ----------------
368
+
369
+ function extractXmlTag(block, tagName) {
370
+ const lower = block.toLowerCase();
371
+ const openTag = `<${tagName.toLowerCase()}`;
372
+ const startIdx = lower.indexOf(openTag);
373
+ if (startIdx < 0) return '';
374
+ const gtIdx = block.indexOf('>', startIdx + openTag.length);
375
+ if (gtIdx < 0) return '';
376
+ if (block[gtIdx - 1] === '/') {
377
+ // Self-closing tag (e.g. Atom <link href="..."/>)
378
+ const attrs = block.slice(startIdx + openTag.length, gtIdx);
379
+ const hrefMatch = attrs.match(/\bhref\s*=\s*["']([^"']+)["']/i);
380
+ return hrefMatch ? hrefMatch[1].trim() : '';
381
+ }
382
+ const closeTag = `</${tagName.toLowerCase()}>`;
383
+ const endIdx = lower.indexOf(closeTag, gtIdx + 1);
384
+ if (endIdx < 0) return '';
385
+ let inner = block.slice(gtIdx + 1, endIdx).trim();
386
+ if (inner.startsWith('<![CDATA[') && inner.endsWith(']]>')) {
387
+ inner = inner.slice(9, -3);
388
+ }
389
+ return inner.trim();
390
+ }
391
+
392
+ function splitXmlBlocks(xmlText, tagName) {
393
+ const out = [];
394
+ const lower = xmlText.toLowerCase();
395
+ const openToken = `<${tagName}`;
396
+ const closeToken = `</${tagName}>`;
397
+ let cursor = 0;
398
+ while (cursor < xmlText.length && out.length < 250) {
399
+ const start = lower.indexOf(openToken, cursor);
400
+ if (start < 0) break;
401
+ const nextChar = lower[start + openToken.length];
402
+ if (nextChar !== '>' && nextChar !== ' ' && nextChar !== '\t' && nextChar !== '\r' && nextChar !== '\n') {
403
+ cursor = start + openToken.length;
404
+ continue;
405
+ }
406
+ const end = lower.indexOf(closeToken, start + openToken.length);
407
+ if (end < 0) break;
408
+ out.push(xmlText.slice(start, end + closeToken.length));
409
+ cursor = end + closeToken.length;
410
+ }
411
+ return out;
412
+ }
413
+
414
+ function parseBudgetNumber(raw) {
415
+ if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
416
+ const s = String(raw || '');
417
+ const m = s.match(/(?:\$|€|£|USD|EUR|SAR|AED)\s?(\d[\d,]*)/i) || s.match(/\b(\d{2,6})\b/);
418
+ if (!m) return null;
419
+ const n = Number(m[1].replace(/,/g, ''));
420
+ return Number.isFinite(n) ? n : null;
421
+ }
422
+
423
+ export function parseFeedText(rawText, { sourceUrl = '' } = {}) {
424
+ const trimmed = String(rawText || '').trim();
425
+ if (!trimmed) return [];
426
+
427
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
428
+ let parsed;
429
+ try {
430
+ parsed = JSON.parse(trimmed);
431
+ } catch {
432
+ throw new Error('Feed content looked like JSON but failed to parse.');
433
+ }
434
+ const list = Array.isArray(parsed)
435
+ ? parsed
436
+ : (Array.isArray(parsed.jobs) ? parsed.jobs
437
+ : Array.isArray(parsed.items) ? parsed.items
438
+ : Array.isArray(parsed.data) ? parsed.data
439
+ : Array.isArray(parsed.postings) ? parsed.postings : []);
440
+
441
+ return list.filter(isObj).map((row) => {
442
+ const titleClean = sanitizeUntrustedSnippet(row.title || row.position || row.text || row.name || '', 110);
443
+ const descClean = sanitizeUntrustedSnippet(row.description || row.snippet || row.summary || row.body || '', 220);
444
+ const companyClean = sanitizeUntrustedSnippet(row.company || row.company_name || row.organization || row.client || '', 60);
445
+ const urlVal = String(row.url || row.apply_url || row.hostedUrl || row.link || '').trim();
446
+ const budgetRaw = row.budget || row.salary || row.compensation || row.salary_max || row.salary_min || null;
447
+ const tags = Array.isArray(row.tags)
448
+ ? row.tags.map(t => sanitizeUntrustedSnippet(t, 28).text).filter(Boolean).slice(0, 8)
449
+ : [];
450
+ return {
451
+ title: titleClean.text,
452
+ url: urlVal || null,
453
+ company: companyClean.text || null,
454
+ budget_raw: budgetRaw ? String(budgetRaw).slice(0, 48) : null,
455
+ budget_num: parseBudgetNumber(budgetRaw),
456
+ tags,
457
+ posted_at: row.posted_at || row.date || row.publication_date || row.createdAt || row.posted || null,
458
+ snippet: descClean.text,
459
+ injection_flags: [...new Set([...titleClean.injection_flags, ...descClean.injection_flags])],
460
+ };
461
+ }).filter(item => item.title.length >= 3);
462
+ }
463
+
464
+ // RSS 2.0 (<item>) or Atom (<entry>)
465
+ const blocks = splitXmlBlocks(trimmed, 'item');
466
+ const entries = blocks.length > 0 ? blocks : splitXmlBlocks(trimmed, 'entry');
467
+ return entries.map((block) => {
468
+ const titleClean = sanitizeUntrustedSnippet(extractXmlTag(block, 'title'), 110);
469
+ const linkVal = decodeXmlHtmlEntities(extractXmlTag(block, 'link')).trim();
470
+ const rawDesc = extractXmlTag(block, 'description') || extractXmlTag(block, 'summary') || extractXmlTag(block, 'content');
471
+ const descClean = sanitizeUntrustedSnippet(rawDesc, 220);
472
+ const pubDate = extractXmlTag(block, 'pubDate') || extractXmlTag(block, 'updated') || extractXmlTag(block, 'published') || null;
473
+ const author = sanitizeUntrustedSnippet(extractXmlTag(block, 'author') || extractXmlTag(block, 'dc:creator') || '', 60).text || null;
474
+ const budgetMatch = descClean.text.match(/(?:\$|€|£|USD|EUR|SAR|AED)\s?\d[\d,]*(?:\s*[-–]\s*(?:\$|€|£|USD|EUR|SAR|AED)?\s?\d[\d,]*)?/i);
475
+ return {
476
+ title: titleClean.text,
477
+ url: linkVal || (sourceUrl || null),
478
+ company: author,
479
+ budget_raw: budgetMatch ? budgetMatch[0] : null,
480
+ budget_num: budgetMatch ? parseBudgetNumber(budgetMatch[0]) : null,
481
+ tags: [],
482
+ posted_at: pubDate,
483
+ snippet: descClean.text,
484
+ injection_flags: [...new Set([...titleClean.injection_flags, ...descClean.injection_flags])],
485
+ };
486
+ }).filter(item => item.title.length >= 3);
487
+ }
488
+
489
+ function canonicalUrlKey(rawUrl) {
490
+ if (!rawUrl) return null;
491
+ try {
492
+ const u = new URL(String(rawUrl));
493
+ return `${u.hostname.toLowerCase()}${u.pathname.replace(/\/+$/, '').toLowerCase()}`;
494
+ } catch {
495
+ return String(rawUrl).trim().toLowerCase();
496
+ }
497
+ }
498
+
499
+ export function loadExistingDedupKeys(root, { home = os.homedir() } = {}) {
500
+ const resolvedRoot = path.resolve(root);
501
+ const urlKeys = new Set();
502
+ const fpKeys = new Set();
503
+
504
+ for (const rel of ['logs/applications-log.json', 'logs/skipped-jobs.json']) {
505
+ const abs = path.join(resolvedRoot, rel);
506
+ if (!fs.existsSync(abs)) continue;
507
+ try {
508
+ refuseSymlink(abs, resolvedRoot, home);
509
+ const parsed = JSON.parse(fs.readFileSync(abs, 'utf8'));
510
+ const list = Array.isArray(parsed)
511
+ ? parsed
512
+ : (Array.isArray(parsed.applications) ? parsed.applications
513
+ : Array.isArray(parsed.skipped) ? parsed.skipped : []);
514
+ for (const row of list) {
515
+ if (!isObj(row)) continue;
516
+ const uk = canonicalUrlKey(row.url || row.job_url);
517
+ if (uk) urlKeys.add(uk);
518
+ if (row.company && row.role) {
519
+ fpKeys.add(`${String(row.company).trim().toLowerCase()}::${String(row.role).trim().toLowerCase()}`);
520
+ } else if (row.company && row.title) {
521
+ fpKeys.add(`${String(row.company).trim().toLowerCase()}::${String(row.title).trim().toLowerCase()}`);
522
+ }
523
+ }
524
+ } catch { /* ignore malformed historical logs */ }
525
+ }
526
+
527
+ const trackerPath = path.join(resolvedRoot, 'tracker', 'freelance-proposals.md');
528
+ if (fs.existsSync(trackerPath)) {
529
+ try {
530
+ refuseSymlink(trackerPath, resolvedRoot, home);
531
+ const text = fs.readFileSync(trackerPath, 'utf8');
532
+ const urls = text.match(/https?:\/\/[^\s|)]+/g) || [];
533
+ for (const u of urls) {
534
+ const uk = canonicalUrlKey(u);
535
+ if (uk) urlKeys.add(uk);
536
+ }
537
+ } catch { /* ignore */ }
538
+ }
539
+
540
+ return { urlKeys, fpKeys };
541
+ }
542
+
543
+ function scoreFeedItem(item, brief) {
544
+ const stack = (brief?.core_stack || []).map(s => s.toLowerCase());
545
+ const forbidden = (brief?.forbidden_unverified_claims || []).map(s => s.toLowerCase());
546
+ const haystack = `${item.title} ${item.snippet} ${(item.tags || []).join(' ')}`.toLowerCase();
547
+
548
+ let matchedSkills = [];
549
+ for (const sk of stack) {
550
+ if (sk.length >= 2 && haystack.includes(sk)) matchedSkills.push(sk);
551
+ }
552
+ const missingForbidden = forbidden.filter(f => f.length >= 2 && haystack.includes(f));
553
+
554
+ // Score 0-100 deterministic rubric:
555
+ // Stack overlap up to 65 pts + budget stated/above floor 20 pts + freshness 15 pts - penalties
556
+ let score = stack.length > 0
557
+ ? Math.min(65, Math.round((matchedSkills.length / Math.min(stack.length, 4)) * 65))
558
+ : 45;
559
+ if (item.budget_num !== null) score += 20;
560
+ else score += 8;
561
+
562
+ if (item.posted_at) {
563
+ const ts = Date.parse(item.posted_at);
564
+ if (Number.isFinite(ts)) {
565
+ const ageDays = (Date.now() - ts) / (1000 * 60 * 60 * 24);
566
+ if (ageDays <= 3) score += 15;
567
+ else if (ageDays <= 14) score += 10;
568
+ else if (ageDays > 45) score -= 20;
569
+ } else if (/just now|today|\bh\b|\bmin|منذ\s+ساع/i.test(String(item.posted_at))) {
570
+ score += 15;
571
+ }
572
+ }
573
+ score -= missingForbidden.length * 15;
574
+ score -= (item.injection_flags?.length || 0) * 25;
575
+ score = Math.max(0, Math.min(100, score));
576
+
577
+ return { score, matched_skills: matchedSkills.slice(0, 6), unverified_required: missingForbidden };
578
+ }
579
+
580
+ export async function scanPublicFeeds(root, {
581
+ url = null,
582
+ file = null,
583
+ top = 10,
584
+ minBudget = null,
585
+ fetchImpl = null,
586
+ lookupImpl = undefined,
587
+ home = os.homedir(),
588
+ cwd = null,
589
+ } = {}) {
590
+ const resolvedRoot = path.resolve(root);
591
+ if ((!url && !file) || (url && file)) {
592
+ throw new Error('`veycraft feed-scan` requires exactly one of `--url <https-url>` or `--file <workspace-path>`.');
593
+ }
594
+ const topN = Number.isInteger(top) && top > 0 ? Math.min(top, 50) : 10;
595
+
596
+ let rawText = '';
597
+ let sourceLabel = '';
598
+ if (file) {
599
+ const baseDir = cwd ? path.resolve(cwd) : resolvedRoot;
600
+ const candidate = path.isAbsolute(file) ? path.resolve(file) : path.resolve(baseDir, file);
601
+ if (!isWithinDir(candidate, resolvedRoot)) {
602
+ throw new Error(`Refusing feed file outside workspace boundary: ${file}`);
603
+ }
604
+ refuseSymlink(candidate, resolvedRoot, home);
605
+ if (!fs.existsSync(candidate)) {
606
+ throw new Error(`Feed input file not found: ${candidate}`);
607
+ }
608
+ rawText = readFileBoundedSync(candidate, MAX_LOCAL_FEED_BYTES, 'feed file').toString('utf8');
609
+ sourceLabel = path.relative(resolvedRoot, candidate).replace(/\\/g, '/');
610
+ } else {
611
+ const res = await fetchTextWithSafeRedirects(url, { fetchImpl, lookupImpl });
612
+ if (res.status < 200 || res.status >= 300) {
613
+ throw new Error(`Feed request returned HTTP ${res.status} for ${res.finalUrl}`);
614
+ }
615
+ rawText = res.text;
616
+ sourceLabel = res.finalUrl;
617
+ }
618
+
619
+ const parsedItems = parseFeedText(rawText, { sourceUrl: url || '' });
620
+ const briefResult = compileCandidateBrief(resolvedRoot, { write: false, home });
621
+ const brief = briefResult.brief || null;
622
+ const { urlKeys, fpKeys } = loadExistingDedupKeys(resolvedRoot, { home });
623
+ const blacklist = (brief?.constraints?.blacklist || []).map(b => b.toLowerCase());
624
+ const effMinBudget = Number.isFinite(minBudget) ? minBudget : (brief?.rate_floor?.min_budget ?? null);
625
+
626
+ let filteredDuplicates = 0;
627
+ let filteredBlacklist = 0;
628
+ let filteredBudget = 0;
629
+ const scored = [];
630
+ const seenLocal = new Set();
631
+
632
+ for (const item of parsedItems) {
633
+ const uKey = canonicalUrlKey(item.url);
634
+ const fp = item.company ? `${item.company.toLowerCase()}::${item.title.toLowerCase()}` : null;
635
+ if ((uKey && (urlKeys.has(uKey) || seenLocal.has(uKey))) || (fp && fpKeys.has(fp))) {
636
+ filteredDuplicates++;
637
+ continue;
638
+ }
639
+ if (uKey) seenLocal.add(uKey);
640
+
641
+ const hay = `${item.company || ''} ${item.url || ''} ${item.title}`.toLowerCase();
642
+ if (blacklist.some(b => b && hay.includes(b))) {
643
+ filteredBlacklist++;
644
+ continue;
645
+ }
646
+
647
+ if (effMinBudget !== null && item.budget_num !== null && item.budget_num < effMinBudget) {
648
+ filteredBudget++;
649
+ continue;
650
+ }
651
+
652
+ const fit = scoreFeedItem(item, brief);
653
+ scored.push({
654
+ title: item.title,
655
+ url: item.url,
656
+ company: item.company,
657
+ budget: item.budget_raw,
658
+ posted_at: item.posted_at,
659
+ fit_score: fit.score,
660
+ matched_skills: fit.matched_skills,
661
+ ...(fit.unverified_required.length ? { unverified_required: fit.unverified_required } : {}),
662
+ ...(item.injection_flags.length ? { injection_flags: item.injection_flags } : {}),
663
+ snippet: item.snippet.slice(0, 160),
664
+ });
665
+ }
666
+
667
+ scored.sort((a, b) => b.fit_score - a.fit_score);
668
+ const topItems = scored.slice(0, topN).map((item, idx) => ({ rank: idx + 1, ...item }));
669
+
670
+ return {
671
+ ok: true,
672
+ source: sourceLabel,
673
+ untrusted_external_data: true,
674
+ brief_used: Boolean(brief),
675
+ total_scanned: parsedItems.length,
676
+ filtered_duplicates: filteredDuplicates,
677
+ filtered_blacklist: filteredBlacklist,
678
+ filtered_budget: filteredBudget,
679
+ returned_count: topItems.length,
680
+ items: topItems,
681
+ };
682
+ }
683
+
684
+ // ---------------- Multi-Feed Radar (`context/feeds.yaml` + `feed-scan --all`) ----------------
685
+
686
+ export function parseFeedsConfigYaml(yamlText) {
687
+ const lines = String(yamlText || '').split(/\r?\n/);
688
+ const feeds = [];
689
+ let current = null;
690
+ let inFeeds = false;
691
+
692
+ for (const raw of lines) {
693
+ const clean = raw.replace(/\s+#.*$/, '');
694
+ const trimmed = clean.trim();
695
+ if (!trimmed || trimmed.startsWith('#')) continue;
696
+
697
+ if (/^feeds\s*:\s*$/i.test(trimmed)) {
698
+ inFeeds = true;
699
+ continue;
700
+ }
701
+ if (!inFeeds) continue;
702
+
703
+ if (/^-\s+/.test(trimmed)) {
704
+ if (current && (current.url || current.file)) feeds.push(current);
705
+ current = { name: 'Unnamed Feed', enabled: true, url: null, file: null, min_budget: null };
706
+ const rest = trimmed.replace(/^-\s+/, '');
707
+ const kv = rest.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
708
+ if (kv) applyFeedField(current, kv[1], kv[2]);
709
+ continue;
710
+ }
711
+
712
+ if (current) {
713
+ const kv = trimmed.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
714
+ if (kv) applyFeedField(current, kv[1], kv[2]);
715
+ }
716
+ }
717
+ if (current && (current.url || current.file)) feeds.push(current);
718
+ return feeds;
719
+ }
720
+
721
+ function applyFeedField(target, key, rawVal) {
722
+ const val = String(rawVal || '').trim().replace(/^["']|["']$/g, '');
723
+ if (key === 'name' && val) target.name = val;
724
+ else if (key === 'enabled') target.enabled = val.toLowerCase() === 'true';
725
+ else if (key === 'url' && val) target.url = val;
726
+ else if (key === 'file' && val) target.file = val;
727
+ else if (key === 'min_budget' && val && Number.isFinite(Number(val))) target.min_budget = Number(val);
728
+ }
729
+
730
+ function escapeMdCell(val) {
731
+ return String(val ?? '').replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').trim();
732
+ }
733
+
734
+ export async function scanAllConfiguredFeeds(root, {
735
+ configPath = null,
736
+ top = 15,
737
+ minBudget = null,
738
+ concurrency = 4,
739
+ write = true,
740
+ fetchImpl = null,
741
+ lookupImpl = undefined,
742
+ home = os.homedir(),
743
+ cwd = null,
744
+ } = {}) {
745
+ const resolvedRoot = path.resolve(root);
746
+ const baseDir = cwd ? path.resolve(cwd) : resolvedRoot;
747
+ const cfgAbs = configPath
748
+ ? (path.isAbsolute(configPath) ? path.resolve(configPath) : path.resolve(baseDir, configPath))
749
+ : path.join(resolvedRoot, 'context', 'feeds.yaml');
750
+
751
+ if (!isWithinDir(cfgAbs, resolvedRoot)) {
752
+ throw new Error(`Refusing feeds config outside workspace boundary: ${configPath}`);
753
+ }
754
+ refuseSymlink(cfgAbs, resolvedRoot, home);
755
+ if (!fs.existsSync(cfgAbs)) {
756
+ throw new Error(`Feeds config not found at ${cfgAbs}. Copy context/feeds.yaml.example to context/feeds.yaml and enable at least one feed.`);
757
+ }
758
+
759
+ const allConfigured = parseFeedsConfigYaml(readFileBoundedSync(cfgAbs, 256 * 1024, 'feeds.yaml').toString('utf8'));
760
+ const enabledFeeds = allConfigured.filter(f => f.enabled);
761
+ const maxWorkers = Math.max(1, Math.min(4, Number.isInteger(concurrency) ? concurrency : 4));
762
+ const topN = Number.isInteger(top) && top > 0 ? Math.min(top, 50) : 15;
763
+
764
+ const briefResult = compileCandidateBrief(resolvedRoot, { write: false, home });
765
+ const brief = briefResult.brief || null;
766
+ const { urlKeys, fpKeys } = loadExistingDedupKeys(resolvedRoot, { home });
767
+ const blacklist = (brief?.constraints?.blacklist || []).map(b => b.toLowerCase());
768
+ const globalMinBudget = Number.isFinite(minBudget) ? minBudget : (brief?.rate_floor?.min_budget ?? null);
769
+
770
+ // Bounded concurrency worker pool (max 4 concurrent sources) with per-source fault isolation
771
+ let nextIdx = 0;
772
+ let activeCount = 0;
773
+ let peakConcurrency = 0;
774
+ const perSourceResults = new Array(enabledFeeds.length);
775
+
776
+ const worker = async () => {
777
+ while (true) {
778
+ const idx = nextIdx++;
779
+ if (idx >= enabledFeeds.length) return;
780
+ const feed = enabledFeeds[idx];
781
+ activeCount++;
782
+ if (activeCount > peakConcurrency) peakConcurrency = activeCount;
783
+ try {
784
+ let rawText = '';
785
+ let sourceLabel = feed.url || feed.file || feed.name;
786
+ if (feed.file) {
787
+ const fAbs = path.isAbsolute(feed.file) ? path.resolve(feed.file) : path.resolve(resolvedRoot, feed.file);
788
+ if (!isWithinDir(fAbs, resolvedRoot)) throw new Error(`Feed file outside workspace: ${feed.file}`);
789
+ refuseSymlink(fAbs, resolvedRoot, home);
790
+ rawText = readFileBoundedSync(fAbs, MAX_LOCAL_FEED_BYTES, feed.name).toString('utf8');
791
+ sourceLabel = path.relative(resolvedRoot, fAbs).replace(/\\/g, '/');
792
+ } else {
793
+ const res = await fetchTextWithSafeRedirects(feed.url, { fetchImpl, lookupImpl });
794
+ if (res.status < 200 || res.status >= 300) {
795
+ throw new Error(`HTTP ${res.status}`);
796
+ }
797
+ rawText = res.text;
798
+ sourceLabel = res.finalUrl;
799
+ }
800
+ const parsed = parseFeedText(rawText, { sourceUrl: feed.url || '' });
801
+ perSourceResults[idx] = {
802
+ status: 'fulfilled',
803
+ feed,
804
+ sourceLabel,
805
+ items: parsed,
806
+ };
807
+ } catch (err) {
808
+ perSourceResults[idx] = {
809
+ status: 'rejected',
810
+ feed,
811
+ error: err instanceof Error ? err.message : String(err),
812
+ };
813
+ } finally {
814
+ activeCount--;
815
+ }
816
+ }
817
+ };
818
+
819
+ await Promise.allSettled(Array.from({ length: Math.min(maxWorkers, enabledFeeds.length) }, () => worker()));
820
+
821
+ const sourceStatuses = [];
822
+ const scored = [];
823
+ const seenCrossFeedUrls = new Set();
824
+ const seenCrossFeedFps = new Set();
825
+ let totalScanned = 0;
826
+ let filteredDuplicates = 0;
827
+ let filteredBlacklist = 0;
828
+ let filteredBudget = 0;
829
+
830
+ for (const outcome of perSourceResults) {
831
+ if (!outcome) continue;
832
+ if (outcome.status === 'rejected') {
833
+ sourceStatuses.push({
834
+ name: outcome.feed.name,
835
+ ok: false,
836
+ scanned: 0,
837
+ kept: 0,
838
+ error: outcome.error,
839
+ });
840
+ continue;
841
+ }
842
+
843
+ const effMin = globalMinBudget !== null ? globalMinBudget : outcome.feed.min_budget;
844
+ let keptFromSource = 0;
845
+ totalScanned += outcome.items.length;
846
+
847
+ for (const item of outcome.items) {
848
+ const uKey = canonicalUrlKey(item.url);
849
+ const fp = item.company ? `${item.company.toLowerCase()}::${item.title.toLowerCase()}` : null;
850
+ if (
851
+ (uKey && (urlKeys.has(uKey) || seenCrossFeedUrls.has(uKey))) ||
852
+ (fp && (fpKeys.has(fp) || seenCrossFeedFps.has(fp)))
853
+ ) {
854
+ filteredDuplicates++;
855
+ continue;
856
+ }
857
+ if (uKey) seenCrossFeedUrls.add(uKey);
858
+ if (fp) seenCrossFeedFps.add(fp);
859
+
860
+ const hay = `${item.company || ''} ${item.url || ''} ${item.title}`.toLowerCase();
861
+ if (blacklist.some(b => b && hay.includes(b))) {
862
+ filteredBlacklist++;
863
+ continue;
864
+ }
865
+ if (effMin !== null && effMin > 0 && item.budget_num !== null && item.budget_num < effMin) {
866
+ filteredBudget++;
867
+ continue;
868
+ }
869
+
870
+ const fit = scoreFeedItem(item, brief);
871
+ keptFromSource++;
872
+ scored.push({
873
+ source_name: outcome.feed.name,
874
+ title: item.title,
875
+ url: item.url,
876
+ company: item.company,
877
+ budget: item.budget_raw,
878
+ posted_at: item.posted_at,
879
+ fit_score: fit.score,
880
+ matched_skills: fit.matched_skills,
881
+ ...(fit.unverified_required.length ? { unverified_required: fit.unverified_required } : {}),
882
+ ...(item.injection_flags.length ? { injection_flags: item.injection_flags } : {}),
883
+ snippet: item.snippet.slice(0, 160),
884
+ });
885
+ }
886
+
887
+ sourceStatuses.push({
888
+ name: outcome.feed.name,
889
+ ok: true,
890
+ scanned: outcome.items.length,
891
+ kept: keptFromSource,
892
+ error: null,
893
+ });
894
+ }
895
+
896
+ scored.sort((a, b) => b.fit_score - a.fit_score);
897
+ const topItems = scored.slice(0, topN).map((it, i) => ({ rank: i + 1, ...it }));
898
+
899
+ const today = new Date().toISOString().slice(0, 10);
900
+ const digestPath = path.join(resolvedRoot, 'logs', 'radar', `${today}.md`);
901
+ if (write) {
902
+ const mdLines = [
903
+ `# Veycraft Daily Opportunity Radar — ${today}`,
904
+ '',
905
+ '> `UNTRUSTED_EXTERNAL_DATA`: Review every listing manually before drafting or approving any bid or application. Zero automatic submissions occur.',
906
+ '',
907
+ `- **Enabled Sources:** ${enabledFeeds.length} (OK: ${sourceStatuses.filter(s => s.ok).length}, Failed: ${sourceStatuses.filter(s => !s.ok).length}, Peak Concurrency: ${peakConcurrency})`,
908
+ `- **Scanned:** ${totalScanned} | **Duplicates Filtered:** ${filteredDuplicates} | **Blacklist Filtered:** ${filteredBlacklist} | **Below Budget:** ${filteredBudget} | **Top Shortlist:** ${topItems.length}`,
909
+ '',
910
+ '## Source Health',
911
+ '',
912
+ '| Source | Status | Scanned | Kept | Notes |',
913
+ '|---|---|---|---|---|',
914
+ ...sourceStatuses.map(s => `| ${escapeMdCell(s.name)} | ${s.ok ? 'OK' : 'FAILED'} | ${s.scanned} | ${s.kept} | ${escapeMdCell(s.error || '—')} |`),
915
+ '',
916
+ '## Ranked Shortlist',
917
+ '',
918
+ '| # | Fit | Source | Title | Budget | Matched Skills | URL | Flags |',
919
+ '|---|---|---|---|---|---|---|---|',
920
+ ...(topItems.length > 0
921
+ ? topItems.map(it =>
922
+ `| ${it.rank} | ${it.fit_score}% | ${escapeMdCell(it.source_name)} | ${escapeMdCell(it.title)} | ${escapeMdCell(it.budget || 'Unstated')} | ${escapeMdCell((it.matched_skills || []).join(', ') || '—')} | ${escapeMdCell(it.url || '—')} | ${escapeMdCell((it.injection_flags || []).join(', ') || 'clean')} |`
923
+ )
924
+ : ['| — | — | — | No new matching items found | — | — | — | — |']),
925
+ '',
926
+ ];
927
+ writeAtomic(digestPath, mdLines.join('\n'), { boundary: resolvedRoot, home });
928
+ }
929
+
930
+ return {
931
+ ok: true,
932
+ mode: 'multi_feed_radar',
933
+ untrusted_external_data: true,
934
+ config_path: path.relative(resolvedRoot, cfgAbs).replace(/\\/g, '/'),
935
+ digest_path: write ? path.relative(resolvedRoot, digestPath).replace(/\\/g, '/') : null,
936
+ enabled_sources: enabledFeeds.length,
937
+ succeeded_sources: sourceStatuses.filter(s => s.ok).length,
938
+ failed_sources: sourceStatuses.filter(s => !s.ok).length,
939
+ peak_concurrency: peakConcurrency,
940
+ total_scanned: totalScanned,
941
+ filtered_duplicates: filteredDuplicates,
942
+ filtered_blacklist: filteredBlacklist,
943
+ filtered_budget: filteredBudget,
944
+ returned_count: topItems.length,
945
+ source_statuses: sourceStatuses,
946
+ items: topItems,
947
+ };
948
+ }
949
+
950
+ // ---------------- 60-Second Interactive / Non-Interactive Onboarding (`veycraft onboard`) ----------------
951
+
952
+ function normalizeGithubUrl(raw) {
953
+ const s = String(raw || '').trim();
954
+ if (!s) return null;
955
+ if (/^https:\/\/github\.com\/[A-Za-z0-9_.-]+/i.test(s)) return s;
956
+ const handle = s.replace(/^@/, '').replace(/^github\.com\//i, '').split('/')[0];
957
+ if (/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(handle)) return `https://github.com/${handle}`;
958
+ return null;
959
+ }
960
+
961
+ async function promptLineList(questions, { input = process.stdin, output = process.stdout } = {}) {
962
+ const answers = [];
963
+ if (!input) return answers;
964
+
965
+ // For non-TTY piped stdin, read all lines upfront cleanly so EOF never hangs on any OS
966
+ if (!input.isTTY) {
967
+ const chunks = [];
968
+ for await (const chunk of input) {
969
+ chunks.push(typeof chunk === 'string' ? chunk : chunk.toString('utf8'));
970
+ }
971
+ const rawLines = chunks.join('').split(/\r?\n/);
972
+ for (let i = 0; i < questions.length; i++) {
973
+ answers.push((rawLines[i] || '').trim());
974
+ }
975
+ return answers;
976
+ }
977
+
978
+ const rl = readline.createInterface({ input, output });
979
+ try {
980
+ for (const q of questions) {
981
+ try {
982
+ const ans = await rl.question(q);
983
+ answers.push(String(ans || '').trim());
984
+ } catch {
985
+ answers.push('');
986
+ }
987
+ }
988
+ } finally {
989
+ rl.close();
990
+ }
991
+ return answers;
992
+ }
993
+
994
+ export async function runOnboardingWizard(root, {
995
+ cvPath = null,
996
+ role = null,
997
+ stack = null,
998
+ minBudget = null,
999
+ minHourly = null,
1000
+ currency = null,
1001
+ workMode = null,
1002
+ github = null,
1003
+ portfolio = null,
1004
+ force = false,
1005
+ nonInteractive = false,
1006
+ useStdin = false,
1007
+ input = process.stdin,
1008
+ output = process.stdout,
1009
+ home = os.homedir(),
1010
+ cwd = null,
1011
+ } = {}) {
1012
+ const resolvedRoot = path.resolve(root);
1013
+ const baseDir = cwd ? path.resolve(cwd) : resolvedRoot;
1014
+
1015
+ let effCv = cvPath;
1016
+ let effRole = role;
1017
+ let effStack = stack;
1018
+ let effMinBudget = minBudget;
1019
+ let effWorkMode = workMode;
1020
+ let effGithub = github;
1021
+ let effPortfolio = portfolio;
1022
+ const effCurrency = String(currency || 'USD').toUpperCase();
1023
+
1024
+ const hasExplicitFlags = Boolean(effCv || effRole || effStack || effMinBudget !== null || effGithub || effWorkMode);
1025
+ const shouldPrompt = !nonInteractive && (useStdin || (!hasExplicitFlags && Boolean(input?.isTTY)));
1026
+
1027
+ if (shouldPrompt) {
1028
+ const [aRole, aStack, aBudget, aMode, aGithub, aCv] = await promptLineList([
1029
+ '1/6 Target role / headline (e.g., Senior Full-Stack TypeScript Engineer): ',
1030
+ '2/6 Core skills comma-separated (e.g., TypeScript, Next.js, Node.js, PostgreSQL): ',
1031
+ '3/6 Minimum project budget / monthly floor in USD (optional, e.g., 400): ',
1032
+ '4/6 Work mode (remote / hybrid / onsite) [remote]: ',
1033
+ '5/6 GitHub handle or URL (optional): ',
1034
+ '6/6 Path to existing CV (.md/.txt/.html inside workspace, optional): ',
1035
+ ], { input, output });
1036
+ if (!effRole && aRole) effRole = aRole;
1037
+ if (!effStack && aStack) effStack = aStack;
1038
+ if (effMinBudget === null && aBudget && /^\d+(?:\.\d+)?$/.test(aBudget)) effMinBudget = Number(aBudget);
1039
+ if (!effWorkMode && aMode) effWorkMode = aMode;
1040
+ if (!effGithub && aGithub) effGithub = aGithub;
1041
+ if (!effCv && aCv) effCv = aCv;
1042
+ }
1043
+
1044
+ const finalRole = String(effRole || '').trim() || 'Software Engineer';
1045
+ const finalSkills = String(effStack || '')
1046
+ .split(',')
1047
+ .map(s => s.trim())
1048
+ .filter(Boolean)
1049
+ .slice(0, 15);
1050
+ const finalWorkMode = /^(remote|hybrid|onsite)$/i.test(String(effWorkMode || '').trim())
1051
+ ? String(effWorkMode).trim().toLowerCase()
1052
+ : 'remote';
1053
+ const finalGithubUrl = normalizeGithubUrl(effGithub);
1054
+ const finalPortfolioUrl = portfolio && /^https:\/\//i.test(String(portfolio).trim()) ? String(portfolio).trim() : null;
1055
+
1056
+ const writtenFiles = [];
1057
+ const skippedExisting = [];
1058
+
1059
+ const canWriteContextFile = (absPath) => {
1060
+ if (!fs.existsSync(absPath)) return true;
1061
+ if (force) return true;
1062
+ try {
1063
+ refuseSymlink(absPath, resolvedRoot, home);
1064
+ const txt = fs.readFileSync(absPath, 'utf8');
1065
+ return TEMPLATE_PLACEHOLDER_RE.test(txt);
1066
+ } catch {
1067
+ return false;
1068
+ }
1069
+ };
1070
+
1071
+ // 1. context/cv.md (from --cv if provided, else grounded starter summary)
1072
+ const cvDest = path.join(resolvedRoot, 'context', 'cv.md');
1073
+ if (effCv) {
1074
+ const srcAbs = path.isAbsolute(effCv) ? path.resolve(effCv) : path.resolve(baseDir, effCv);
1075
+ if (!isWithinDir(srcAbs, resolvedRoot)) {
1076
+ throw new Error(`Refusing CV source outside workspace boundary: ${effCv}`);
1077
+ }
1078
+ refuseSymlink(srcAbs, resolvedRoot, home);
1079
+ if (!fs.existsSync(srcAbs)) throw new Error(`CV file not found: ${srcAbs}`);
1080
+ const rawCv = readFileBoundedSync(srcAbs, 512 * 1024, 'CV source').toString('utf8');
1081
+ const cleanCv = /\.html?$/i.test(srcAbs) ? decodeXmlHtmlEntities(stripMarkupTags(rawCv, '\n')) : rawCv;
1082
+ if (canWriteContextFile(cvDest)) {
1083
+ writeAtomic(cvDest, cleanCv, { boundary: resolvedRoot, home });
1084
+ writtenFiles.push('context/cv.md');
1085
+ } else {
1086
+ skippedExisting.push('context/cv.md');
1087
+ }
1088
+ } else if (canWriteContextFile(cvDest)) {
1089
+ const starterCv = [
1090
+ `# ${finalRole}`,
1091
+ '',
1092
+ `Skills: ${finalSkills.length ? finalSkills.join(', ') : 'TypeScript, Node.js'}`,
1093
+ '',
1094
+ '## Experience',
1095
+ `- Add verified project outcomes and metrics for ${finalRole}.`,
1096
+ '',
1097
+ ].join('\n');
1098
+ writeAtomic(cvDest, starterCv, { boundary: resolvedRoot, home });
1099
+ writtenFiles.push('context/cv.md');
1100
+ } else {
1101
+ skippedExisting.push('context/cv.md');
1102
+ }
1103
+
1104
+ // 2. context/profile.md
1105
+ const profileDest = path.join(resolvedRoot, 'context', 'profile.md');
1106
+ if (canWriteContextFile(profileDest)) {
1107
+ const profileLines = [
1108
+ '# Candidate Profile',
1109
+ '',
1110
+ `Headline: ${finalRole}`,
1111
+ `Work Mode: ${finalWorkMode}`,
1112
+ ...(finalGithubUrl ? [`GitHub: ${finalGithubUrl}`] : []),
1113
+ ...(finalPortfolioUrl ? [`Portfolio: ${finalPortfolioUrl}`] : []),
1114
+ '',
1115
+ ];
1116
+ writeAtomic(profileDest, profileLines.join('\n'), { boundary: resolvedRoot, home });
1117
+ writtenFiles.push('context/profile.md');
1118
+ } else {
1119
+ skippedExisting.push('context/profile.md');
1120
+ }
1121
+
1122
+ // 3. context/preferences.yaml
1123
+ const prefDest = path.join(resolvedRoot, 'context', 'preferences.yaml');
1124
+ if (canWriteContextFile(prefDest)) {
1125
+ const prefLines = [
1126
+ `work_mode: ${finalWorkMode}`,
1127
+ `currency: ${effCurrency}`,
1128
+ ...(effMinBudget !== null && Number.isFinite(Number(effMinBudget)) ? [`min_budget: ${Number(effMinBudget)}`] : []),
1129
+ ...(minHourly !== null && Number.isFinite(Number(minHourly)) ? [`min_hourly: ${Number(minHourly)}`] : []),
1130
+ 'languages:',
1131
+ ' - en',
1132
+ ...(finalSkills.length
1133
+ ? ['skills:', ...finalSkills.map(s => ` - ${s}`)]
1134
+ : []),
1135
+ 'blacklisted_companies: []',
1136
+ '',
1137
+ ];
1138
+ writeAtomic(prefDest, prefLines.join('\n'), { boundary: resolvedRoot, home });
1139
+ writtenFiles.push('context/preferences.yaml');
1140
+ } else {
1141
+ skippedExisting.push('context/preferences.yaml');
1142
+ }
1143
+
1144
+ // 4. Immediately compile compact context/brief.json (< 400 tokens)
1145
+ const briefRes = compileCandidateBrief(resolvedRoot, { refresh: true, write: true, home });
1146
+ if (briefRes.brief_ready) writtenFiles.push('context/brief.json');
1147
+
1148
+ return {
1149
+ ok: true,
1150
+ onboarded: true,
1151
+ written_files: writtenFiles,
1152
+ skipped_existing: skippedExisting,
1153
+ brief: {
1154
+ ready: briefRes.brief_ready,
1155
+ bytes: briefRes.bytes || 0,
1156
+ est_tokens: briefRes.est_tokens || 0,
1157
+ path: briefRes.brief_ready ? 'context/brief.json' : null,
1158
+ },
1159
+ };
1160
+ }
1161
+
1162
+ // ---------------- Scoped CLI Runner for `brief`, `feed-scan`, `browser-script`, `onboard` ----------------
1163
+
1164
+ export async function runFastOpsCli(root, command, rawArgs = [], { home = os.homedir(), cwd = process.cwd() } = {}) {
1165
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
1166
+ let json = false;
1167
+ let help = false;
1168
+
1169
+ if (command === 'brief') {
1170
+ let refresh = false;
1171
+ let write = true;
1172
+ for (let i = 0; i < args.length; i++) {
1173
+ const a = args[i];
1174
+ if (a === '--json') json = true;
1175
+ else if (a === '--refresh') refresh = true;
1176
+ else if (a === '--no-write') write = false;
1177
+ else if (a === '--help' || a === '-h') help = true;
1178
+ else throw new Error(`Unknown option for \`veycraft brief\`: "${a}".`);
1179
+ }
1180
+ if (help) {
1181
+ return {
1182
+ json: false,
1183
+ exitCode: 0,
1184
+ lines: [
1185
+ 'Usage: veycraft brief [--refresh] [--no-write] [--json]',
1186
+ 'Compiles or reads cached context/brief.json (< 400 tokens, zero PII) with mtime+sha256 invalidation.',
1187
+ ],
1188
+ };
1189
+ }
1190
+ const res = compileCandidateBrief(root, { refresh, write, home });
1191
+ return {
1192
+ json,
1193
+ exitCode: 0,
1194
+ data: res,
1195
+ lines: res.brief_ready
1196
+ ? [
1197
+ `Candidate brief ready (${res.cached ? 'cache hit' : 'compiled'}): ${res.path}`,
1198
+ `Size: ${res.bytes} bytes (~${res.est_tokens} tokens) · Headline: ${res.brief.headline}`,
1199
+ `Core stack (${res.brief.core_stack.length}): ${res.brief.core_stack.join(', ') || 'none'}`,
1200
+ ]
1201
+ : [`Brief not ready: ${res.reason}`],
1202
+ };
1203
+ }
1204
+
1205
+ if (command === 'onboard') {
1206
+ let cvPath = null;
1207
+ let role = null;
1208
+ let stack = null;
1209
+ let minBudget = null;
1210
+ let minHourly = null;
1211
+ let currency = null;
1212
+ let workMode = null;
1213
+ let github = null;
1214
+ let portfolio = null;
1215
+ let force = false;
1216
+ let nonInteractive = false;
1217
+ let useStdin = false;
1218
+
1219
+ for (let i = 0; i < args.length; i++) {
1220
+ const a = args[i];
1221
+ if (a === '--json') json = true;
1222
+ else if (a === '--help' || a === '-h') help = true;
1223
+ else if (a === '--force') force = true;
1224
+ else if (a === '--non-interactive') nonInteractive = true;
1225
+ else if (a === '--stdin') useStdin = true;
1226
+ else if (a === '--cv') { cvPath = args[++i]; if (!cvPath) throw new Error('Option --cv requires a file path.'); }
1227
+ else if (a === '--role') { role = args[++i]; if (!role) throw new Error('Option --role requires a role title.'); }
1228
+ else if (a === '--stack') { stack = args[++i]; if (!stack) throw new Error('Option --stack requires comma-separated skills.'); }
1229
+ else if (a === '--currency') { currency = args[++i]; if (!currency) throw new Error('Option --currency requires a currency code.'); }
1230
+ else if (a === '--work-mode') { workMode = args[++i]; if (!workMode) throw new Error('Option --work-mode requires remote|hybrid|onsite.'); }
1231
+ else if (a === '--github') { github = args[++i]; if (!github) throw new Error('Option --github requires a handle or URL.'); }
1232
+ else if (a === '--portfolio') { portfolio = args[++i]; if (!portfolio) throw new Error('Option --portfolio requires an HTTPS URL.'); }
1233
+ else if (a === '--min-budget') {
1234
+ const rawVal = args[++i];
1235
+ if (!rawVal || !/^\d+(?:\.\d+)?$/.test(rawVal)) throw new Error(`Invalid --min-budget value: "${rawVal}".`);
1236
+ minBudget = Number(rawVal);
1237
+ } else if (a === '--min-hourly') {
1238
+ const rawVal = args[++i];
1239
+ if (!rawVal || !/^\d+(?:\.\d+)?$/.test(rawVal)) throw new Error(`Invalid --min-hourly value: "${rawVal}".`);
1240
+ minHourly = Number(rawVal);
1241
+ } else {
1242
+ throw new Error(`Unknown option for \`veycraft onboard\`: "${a}".`);
1243
+ }
1244
+ }
1245
+ if (help) {
1246
+ return {
1247
+ json: false,
1248
+ exitCode: 0,
1249
+ lines: [
1250
+ 'Usage: veycraft onboard [--cv <path>] [--role <title>] [--stack <a,b,c>] [--min-budget <n>] [--min-hourly <n>] [--currency <USD>] [--work-mode <remote|hybrid|onsite>] [--github <handle>] [--portfolio <https-url>] [--force] [--non-interactive | --stdin] [--json]',
1251
+ '60-second zero-dependency onboarding wizard: populates context/ files (preserving existing verified files unless --force) and compiles context/brief.json (< 400 tokens).',
1252
+ ],
1253
+ };
1254
+ }
1255
+ const res = await runOnboardingWizard(root, {
1256
+ cvPath, role, stack, minBudget, minHourly, currency, workMode, github, portfolio,
1257
+ force, nonInteractive, useStdin, home, cwd,
1258
+ });
1259
+ return {
1260
+ json,
1261
+ exitCode: 0,
1262
+ data: res,
1263
+ lines: [
1264
+ `Onboarding complete. Written: ${res.written_files.join(', ') || 'none'}${res.skipped_existing.length ? ` | Preserved existing: ${res.skipped_existing.join(', ')}` : ''}`,
1265
+ res.brief.ready
1266
+ ? `Candidate brief ready: ${res.brief.path} (${res.brief.bytes} bytes, ~${res.brief.est_tokens} tokens)`
1267
+ : 'Candidate brief pending real CV/profile details.',
1268
+ ],
1269
+ };
1270
+ }
1271
+
1272
+ if (command === 'feed-scan') {
1273
+ let url = null;
1274
+ let file = null;
1275
+ let all = false;
1276
+ let configPath = null;
1277
+ let top = 10;
1278
+ let topExplicit = false;
1279
+ let minBudget = null;
1280
+ let concurrency = 4;
1281
+ let write = true;
1282
+ for (let i = 0; i < args.length; i++) {
1283
+ const a = args[i];
1284
+ if (a === '--json') json = true;
1285
+ else if (a === '--help' || a === '-h') help = true;
1286
+ else if (a === '--all') all = true;
1287
+ else if (a === '--no-write') write = false;
1288
+ else if (a === '--config') {
1289
+ configPath = args[++i];
1290
+ if (!configPath || configPath.startsWith('-')) throw new Error('Option --config requires a workspace path to feeds.yaml.');
1291
+ } else if (a === '--url') {
1292
+ url = args[++i];
1293
+ if (!url || url.startsWith('-')) throw new Error('Option --url requires an HTTPS URL.');
1294
+ } else if (a === '--file') {
1295
+ file = args[++i];
1296
+ if (!file || file.startsWith('-')) throw new Error('Option --file requires a workspace file path.');
1297
+ } else if (a === '--top') {
1298
+ const rawTop = args[++i];
1299
+ if (!rawTop || !/^\d+$/.test(rawTop) || Number(rawTop) < 1) throw new Error(`Invalid --top value: "${rawTop}".`);
1300
+ top = Number(rawTop);
1301
+ topExplicit = true;
1302
+ } else if (a === '--min-budget') {
1303
+ const rawMin = args[++i];
1304
+ if (!rawMin || !/^\d+(?:\.\d+)?$/.test(rawMin)) throw new Error(`Invalid --min-budget value: "${rawMin}".`);
1305
+ minBudget = Number(rawMin);
1306
+ } else if (a === '--concurrency') {
1307
+ const rawConc = args[++i];
1308
+ if (!rawConc || !/^[1-4]$/.test(rawConc)) throw new Error(`Invalid --concurrency value (must be 1..4): "${rawConc}".`);
1309
+ concurrency = Number(rawConc);
1310
+ } else {
1311
+ throw new Error(`Unknown option for \`veycraft feed-scan\`: "${a}".`);
1312
+ }
1313
+ }
1314
+ if (help) {
1315
+ return {
1316
+ json: false,
1317
+ exitCode: 0,
1318
+ lines: [
1319
+ 'Usage: veycraft feed-scan (--all [--config <feeds.yaml>] [--concurrency 1..4] [--no-write] | --url <https-url> | --file <path>) [--top <n>] [--min-budget <n>] [--json]',
1320
+ 'Zero-token local RSS/Atom/JSON feed scanner with SEC-01 SSRF protection, bounded concurrency (max 4), deduplication, daily logs/radar/YYYY-MM-DD.md digest, and local Fit Score (0-100) ranking.',
1321
+ ],
1322
+ };
1323
+ }
1324
+ if (all) {
1325
+ if (url || file) throw new Error('Cannot combine --all with --url or --file.');
1326
+ const res = await scanAllConfiguredFeeds(root, {
1327
+ configPath,
1328
+ top: topExplicit ? top : 15,
1329
+ minBudget,
1330
+ concurrency,
1331
+ write,
1332
+ home,
1333
+ cwd,
1334
+ });
1335
+ return {
1336
+ json,
1337
+ exitCode: 0,
1338
+ data: res,
1339
+ lines: [
1340
+ `Radar scanned ${res.enabled_sources} source(s) (ok: ${res.succeeded_sources}, failed: ${res.failed_sources}, peak concurrency: ${res.peak_concurrency}) -> ${res.returned_count} top item(s) from ${res.total_scanned} scanned`,
1341
+ ...(res.digest_path ? [`Saved daily digest -> ${res.digest_path}`] : []),
1342
+ ...res.items.map(it => `#${it.rank} [${it.fit_score}%] (${it.source_name}) ${it.title}${it.budget ? ` (${it.budget})` : ''}`),
1343
+ ],
1344
+ };
1345
+ }
1346
+ const res = await scanPublicFeeds(root, { url, file, top, minBudget, home, cwd });
1347
+ return {
1348
+ json,
1349
+ exitCode: 0,
1350
+ data: res,
1351
+ lines: [
1352
+ `Scanned ${res.total_scanned} item(s) from ${res.source} -> returning top ${res.returned_count} (deduped: ${res.filtered_duplicates}, blacklist: ${res.filtered_blacklist}, below budget: ${res.filtered_budget})`,
1353
+ ...res.items.map(it => `#${it.rank} [${it.fit_score}%] ${it.title}${it.budget ? ` (${it.budget})` : ''}${it.url ? ` — ${it.url}` : ''}`),
1354
+ ],
1355
+ };
1356
+ }
1357
+
1358
+ if (command === 'browser-script') {
1359
+ let targetName = null;
1360
+ for (let i = 0; i < args.length; i++) {
1361
+ const a = args[i];
1362
+ if (a === '--json') json = true;
1363
+ else if (a === '--help' || a === '-h') help = true;
1364
+ else if (a.startsWith('-')) throw new Error(`Unknown option for \`veycraft browser-script\`: "${a}".`);
1365
+ else if (!targetName) targetName = a;
1366
+ else throw new Error(`Unexpected extra argument for \`veycraft browser-script\`: "${a}".`);
1367
+ }
1368
+ if (help || !targetName) {
1369
+ return {
1370
+ json: false,
1371
+ exitCode: help ? 0 : 1,
1372
+ lines: [
1373
+ `Usage: veycraft browser-script <${PAYLOAD_NAMES.join('|')}> [--json]`,
1374
+ 'Prints read-only DOM distiller or single-shot non-submitting batch-fill JS payload (never clicks Submit/Publish).',
1375
+ ],
1376
+ };
1377
+ }
1378
+ const payload = getBrowserPayload(targetName);
1379
+ return {
1380
+ json,
1381
+ exitCode: 0,
1382
+ data: payload,
1383
+ lines: [
1384
+ `Payload: ${payload.name} (read_only=${payload.read_only}, never_submits=${payload.never_submits})`,
1385
+ payload.usage,
1386
+ payload.fn_source,
1387
+ ],
1388
+ };
1389
+ }
1390
+
1391
+ throw new Error(`Unknown fast-ops command: "${command}".`);
1392
+ }