cvprism 1.5.0__py3-none-any.whl

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 (94) hide show
  1. cvprism/__init__.py +3 -0
  2. cvprism/__main__.py +3 -0
  3. cvprism/app/__init__.py +0 -0
  4. cvprism/app/pages.py +206 -0
  5. cvprism/app/server.py +382 -0
  6. cvprism/capture/__init__.py +0 -0
  7. cvprism/capture/hookentry.py +61 -0
  8. cvprism/capture/importers.py +228 -0
  9. cvprism/capture/manual.py +133 -0
  10. cvprism/capture/pipeline.py +144 -0
  11. cvprism/capture/projects.py +24 -0
  12. cvprism/capture/prompts.py +92 -0
  13. cvprism/capture/queue.py +93 -0
  14. cvprism/capture/redact.py +141 -0
  15. cvprism/capture/reduce.py +250 -0
  16. cvprism/capture/watcher.py +250 -0
  17. cvprism/capture/worker.py +123 -0
  18. cvprism/cli.py +918 -0
  19. cvprism/compile/__init__.py +0 -0
  20. cvprism/compile/ats.py +125 -0
  21. cvprism/compile/bibtex.py +72 -0
  22. cvprism/compile/build.py +382 -0
  23. cvprism/compile/context.py +216 -0
  24. cvprism/compile/draft.py +273 -0
  25. cvprism/compile/evidence.py +161 -0
  26. cvprism/compile/export.py +79 -0
  27. cvprism/compile/gate.py +117 -0
  28. cvprism/compile/jd.py +180 -0
  29. cvprism/compile/market.py +98 -0
  30. cvprism/compile/orcid.py +79 -0
  31. cvprism/compile/quality.py +135 -0
  32. cvprism/compile/render.py +398 -0
  33. cvprism/compile/roles.py +59 -0
  34. cvprism/compile/select.py +68 -0
  35. cvprism/compile/sign.py +75 -0
  36. cvprism/compile/verify.py +158 -0
  37. cvprism/config.py +68 -0
  38. cvprism/data/__init__.py +0 -0
  39. cvprism/data/demo/cards.jsonl +10 -0
  40. cvprism/data/demo/profile.yaml +26 -0
  41. cvprism/data/demo/pubs.bib +14 -0
  42. cvprism/data/demo/sample_jd.txt +17 -0
  43. cvprism/data/roles/academic.yaml +12 -0
  44. cvprism/data/roles/applied-ai.yaml +13 -0
  45. cvprism/data/roles/geospatial.yaml +12 -0
  46. cvprism/data/roles/hydrodynamics.yaml +12 -0
  47. cvprism/data/roles/industry-ds.yaml +13 -0
  48. cvprism/data/seed_skills.json +624 -0
  49. cvprism/data/skills/cv-build/SKILL.md +12 -0
  50. cvprism/data/skills/cv-log/SKILL.md +22 -0
  51. cvprism/data/vault_template/README.md +14 -0
  52. cvprism/data/vault_template/profile.yaml +20 -0
  53. cvprism/data/vault_template/roles/README.md +3 -0
  54. cvprism/demo.py +41 -0
  55. cvprism/hub/__init__.py +0 -0
  56. cvprism/hub/merge.py +200 -0
  57. cvprism/hub/registry.py +110 -0
  58. cvprism/install/__init__.py +0 -0
  59. cvprism/install/claude.py +122 -0
  60. cvprism/install/githooks.py +120 -0
  61. cvprism/install/service.py +116 -0
  62. cvprism/llm.py +210 -0
  63. cvprism/lock.py +36 -0
  64. cvprism/mcp_server.py +154 -0
  65. cvprism/novelty/__init__.py +0 -0
  66. cvprism/novelty/counters.py +42 -0
  67. cvprism/novelty/filter.py +70 -0
  68. cvprism/novelty/ids.py +77 -0
  69. cvprism/paths.py +36 -0
  70. cvprism/schemas/__init__.py +33 -0
  71. cvprism/schemas/card.schema.json +246 -0
  72. cvprism/schemas/device.schema.json +242 -0
  73. cvprism/schemas/manifest.schema.json +107 -0
  74. cvprism/schemas/profile.schema.json +275 -0
  75. cvprism/schemas/registry.schema.json +149 -0
  76. cvprism/schemas/role.schema.json +170 -0
  77. cvprism/setup/__init__.py +0 -0
  78. cvprism/setup/web.py +180 -0
  79. cvprism/setup/wizard.py +121 -0
  80. cvprism/sync/__init__.py +0 -0
  81. cvprism/sync/adapters/__init__.py +48 -0
  82. cvprism/sync/adapters/base.py +257 -0
  83. cvprism/sync/adapters/folders.py +103 -0
  84. cvprism/sync/adapters/git.py +84 -0
  85. cvprism/sync/engine.py +186 -0
  86. cvprism/sync/outbox.py +75 -0
  87. cvprism/vault.py +82 -0
  88. cvprism/yamlio.py +38 -0
  89. cvprism-1.5.0.dist-info/METADATA +301 -0
  90. cvprism-1.5.0.dist-info/RECORD +94 -0
  91. cvprism-1.5.0.dist-info/WHEEL +5 -0
  92. cvprism-1.5.0.dist-info/entry_points.txt +3 -0
  93. cvprism-1.5.0.dist-info/licenses/LICENSE +201 -0
  94. cvprism-1.5.0.dist-info/top_level.txt +1 -0
cvprism/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """cvprism: evidence-backed, role-specific CVs from everyday work."""
2
+
3
+ __version__ = "1.5.0"
cvprism/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import app
2
+
3
+ app(prog_name="cvprism")
File without changes
cvprism/app/pages.py ADDED
@@ -0,0 +1,206 @@
1
+ """Server-rendered pages for `cvprism app` (no JavaScript). Every value is escaped with h()."""
2
+ from __future__ import annotations
3
+
4
+ import html
5
+ from urllib.parse import quote
6
+
7
+ CSS = """
8
+ :root{--paper:#EEF1F5;--ink:#1A2230;--muted:#5A6577;--line:#CDD3DC;--act:#3346C8;--ok:#1E7A6E;--err:#B3261E;--field:#FFF;--link:#0052CC}
9
+ *{box-sizing:border-box}
10
+ body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
11
+ .spectrum{height:6px;background:linear-gradient(90deg,#3346C8 0 20%,#2A9D8F 20% 40%,#E9C46A 40% 60%,#F4A261 60% 80%,#E5533D 80%)}
12
+ header{background:#fff;border-bottom:1px solid var(--line)}
13
+ .bar{max-width:980px;margin:0 auto;padding:10px 24px;display:flex;gap:22px;align-items:center;flex-wrap:wrap}
14
+ .brand{font-weight:700;font-size:18px;margin-right:12px;color:var(--ink);text-decoration:none}
15
+ nav a{color:var(--muted);text-decoration:none;padding:6px 2px;border-bottom:2px solid transparent}
16
+ nav a[aria-current=page]{color:var(--ink);border-bottom-color:var(--act)}
17
+ nav{display:flex;gap:18px;flex-wrap:wrap}
18
+ main{max-width:980px;margin:0 auto;padding:32px 24px 72px}
19
+ h1{font-size:26px;line-height:1.25;margin:0 0 6px;font-weight:650}
20
+ h2{font-size:18px;margin:28px 0 10px}
21
+ .lede{color:var(--muted);margin:0 0 26px;max-width:68ch}
22
+ a{color:var(--link)}
23
+ .actions{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin:8px 0 28px}
24
+ .action{display:block;background:#fff;border:1px solid var(--line);border-radius:10px;padding:16px 18px;color:var(--ink);text-decoration:none}
25
+ .action b{display:block;font-size:16px;margin-bottom:4px}
26
+ .action span{color:var(--muted);font-size:14px}
27
+ .action:hover{border-color:var(--act)}
28
+ .facts{display:flex;gap:28px;flex-wrap:wrap;margin:0 0 8px;color:var(--muted)}
29
+ .facts strong{color:var(--ink);font-size:20px;display:block}
30
+ form.card,.panel{background:#fff;border:1px solid var(--line);border-radius:10px;padding:20px 22px;max-width:720px}
31
+ label{display:block;font-weight:550;margin:14px 0 4px}
32
+ .hint{display:block;color:var(--muted);font-weight:400;font-size:13.5px}
33
+ input[type=text],input[type=url],select,textarea{width:100%;padding:9px 11px;border:1px solid var(--line);border-radius:6px;background:var(--field);font:inherit;color:inherit}
34
+ textarea{min-height:170px}
35
+ .row{display:grid;grid-template-columns:2fr 1fr 1fr;gap:10px}
36
+ .check{display:flex;gap:8px;align-items:flex-start;font-weight:400}
37
+ button{margin-top:20px;background:var(--act);color:#fff;border:0;border-radius:6px;padding:10px 18px;font:inherit;font-weight:600;cursor:pointer}
38
+ button.small{margin:0;padding:6px 12px;font-size:14px}
39
+ :focus-visible{outline:3px solid #9AA8F0;outline-offset:2px}
40
+ .msg{border-left:4px solid var(--ok);background:#E7F4F1;padding:10px 14px;margin:0 0 22px;border-radius:0 6px 6px 0;max-width:720px}
41
+ .msg.err{border-left-color:var(--err);background:#FBEAE9}
42
+ table{width:100%;border-collapse:collapse;background:#fff;border:1px solid var(--line);border-radius:8px}
43
+ th,td{text-align:left;padding:9px 12px;border-bottom:1px solid #E3E7ED;vertical-align:top}
44
+ th{font-weight:600;background:#F6F8FB}
45
+ td form{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
46
+ td select,td input[type=url]{width:auto;min-width:130px}
47
+ .lvl-public{color:var(--ok);font-weight:600}
48
+ .muted{color:var(--muted)}
49
+ .downloads{display:flex;gap:12px;flex-wrap:wrap;margin:6px 0 24px}
50
+ .downloads a{background:var(--act);color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-weight:600}
51
+ pre{background:#fff;border:1px solid var(--line);border-radius:8px;padding:14px 16px;white-space:pre-wrap;font-size:13.5px;max-width:900px}
52
+ @media (max-width:640px){.row{grid-template-columns:1fr}}
53
+ """
54
+
55
+ NAV = [("/", "Home"), ("/add", "Add evidence"), ("/import", "Bring in what you have"), ("/projects", "Projects"),
56
+ ("/cards", "My evidence"), ("/build", "Build a CV")]
57
+ DEPTHS = [("1", "I used it"), ("2", "I applied it in real work"), ("3", "I built something with it"),
58
+ ("4", "I led it / it's in production"), ("5", "I published or taught it")]
59
+ LEVEL_TEXT = {"public": "Public proof", "confirmed": "Third-party confirmed", "captured": "Captured",
60
+ "self-reported": "Self-reported"}
61
+
62
+
63
+ def h(v) -> str:
64
+ return html.escape("" if v is None else str(v), quote=True)
65
+
66
+
67
+ def layout(title: str, active: str, body: str) -> bytes:
68
+ nav = "".join(f'<a href="{p}"{" aria-current=page" if p == active else ""}>{h(t)}</a>' for p, t in NAV)
69
+ return (f"<!doctype html><html lang='en'><head><meta charset='utf-8'>"
70
+ f"<meta name='viewport' content='width=device-width,initial-scale=1'><title>{h(title)} · cvprism</title>"
71
+ f"<style>{CSS}</style></head><body><div class='spectrum' aria-hidden='true'></div>"
72
+ f"<header><div class='bar'><a class='brand' href='/'>cvprism</a><nav aria-label='Main'>{nav}</nav></div>"
73
+ f"</header><main>{body}</main></body></html>").encode("utf-8")
74
+
75
+
76
+ def message(text: str | None, error: bool = False) -> str:
77
+ if not text:
78
+ return ""
79
+ return f"<p class='msg{' err' if error else ''}' role='{'alert' if error else 'status'}'>{h(text)}</p>"
80
+
81
+
82
+ def home(name: str, role: str, counts: dict, projects: int, last_build: str | None) -> str:
83
+ total = sum(counts.values())
84
+ facts = (f"<div class='facts'><div><strong>{total}</strong>evidence cards</div>"
85
+ f"<div><strong>{counts.get('public', 0)}</strong>with public proof</div>"
86
+ f"<div><strong>{projects}</strong>projects</div>"
87
+ f"<div><strong>{h(last_build or 'none yet')}</strong>last CV</div></div>")
88
+ who = h(name) if name and name != "Your Name" else "Welcome"
89
+ where = ("This is your main computer: your CVs are built here." if role == "hub" else
90
+ "This computer sends your evidence to your main computer, where CVs are built.")
91
+ return f"""<h1>{who}</h1><p class="lede">{where} Everything stays on your computers.</p>{facts}
92
+ <h2>What would you like to do?</h2>
93
+ <div class="actions">
94
+ <a class="action" href="/add"><b>Add evidence</b><span>A paper, a talk, field work, a result, a skill you used.</span></a>
95
+ <a class="action" href="/import"><b>Bring in what you have</b><span>Your LinkedIn export or an old CV.</span></a>
96
+ <a class="action" href="/projects"><b>Projects</b><span>Choose which work gets public proof links.</span></a>
97
+ <a class="action" href="/build"><b>Build a CV</b><span>For a role, or tailored to a job posting.</span></a>
98
+ </div>"""
99
+
100
+
101
+ def add_form(projects: list[dict], values: dict | None = None, msg: str = "", error: bool = False) -> str:
102
+ v = values or {}
103
+ opts = "<option value=''>No project</option>" + "".join(
104
+ f"<option value='{h(p['ctx'])}'{' selected' if v.get('project') == p['ctx'] else ''}>{h(p.get('display') or p['ctx'])}</option>"
105
+ for p in projects)
106
+ depth = "".join(f"<option value='{k}'{' selected' if str(v.get('depth', '2')) == k else ''}>{h(t)}</option>"
107
+ for k, t in DEPTHS)
108
+ return f"""<h1>Add evidence</h1><p class="lede">One achievement at a time. Only write what you can stand behind:
109
+ numbers are kept only if you type them.</p>{message(msg, error)}
110
+ <form class="card" method="post" action="/add"><input type="hidden" name="csrf" value="{{csrf}}">
111
+ <label for="what">What did you do?<span class="hint">One sentence, e.g. "Calibrated a 2D flood model for the Hooghly estuary".</span></label>
112
+ <input type="text" id="what" name="what" required value="{h(v.get('what'))}">
113
+ <label for="skill">Skills<span class="hint">Comma-separated, e.g. "HEC-RAS, model calibration".</span></label>
114
+ <input type="text" id="skill" name="skill" value="{h(v.get('skill'))}">
115
+ <label for="depth">How deep did you go?</label><select id="depth" name="depth">{depth}</select>
116
+ <label>Result, if you measured one<span class="hint">e.g. metric "setup time", value "15", unit "min". Leave empty if there isn't one.</span></label>
117
+ <div class="row"><input type="text" name="result_metric" aria-label="Metric" placeholder="metric" value="{h(v.get('result_metric'))}">
118
+ <input type="text" name="result_value" aria-label="Value" placeholder="value" value="{h(v.get('result_value'))}">
119
+ <input type="text" name="result_unit" aria-label="Unit" placeholder="unit" value="{h(v.get('result_unit'))}"></div>
120
+ <label for="link">Proof link<span class="hint">Optional public https:// link: a DOI, repository, video, certificate page.</span></label>
121
+ <input type="url" id="link" name="link" value="{h(v.get('link'))}">
122
+ <label for="project">Project</label><select id="project" name="project">{opts}</select>
123
+ <label class="check"><input type="checkbox" name="work"{' checked' if v.get('work') else ''}> This isn't code (paper, talk, field work, award, teaching)</label>
124
+ <label class="check"><input type="checkbox" name="use_ai"{' checked' if v.get('use_ai') else ''}> Let Claude polish the wording (it can't add claims or numbers)</label>
125
+ <button type="submit">Save evidence</button></form>"""
126
+
127
+
128
+ def import_form(msg: str = "", error: bool = False) -> str:
129
+ return f"""<h1>Bring in what you have</h1><p class="lede">Start from your LinkedIn data or an old CV. Imported
130
+ lines are marked for review, because they're self-reported.</p>{message(msg, error)}
131
+ <form class="card" method="post" action="/import" enctype="multipart/form-data"><input type="hidden" name="csrf" value="{{csrf}}">
132
+ <label for="kind">What are you uploading?</label>
133
+ <select id="kind" name="kind"><option value="linkedin">LinkedIn data export (.zip)</option>
134
+ <option value="cv">An old CV (.docx, .md, .txt or .pdf)</option></select>
135
+ <label for="file">File<span class="hint">LinkedIn: Settings → Data privacy → Get a copy of your data.</span></label>
136
+ <input type="file" id="file" name="file" required>
137
+ <label class="check"><input type="checkbox" name="use_ai"> Let Claude read it more carefully (slower)</label>
138
+ <button type="submit">Import</button></form>"""
139
+
140
+
141
+ def projects_page(projects: list[dict], is_hub: bool, msg: str = "", error: bool = False) -> str:
142
+ if not is_hub:
143
+ return "<h1>Projects</h1><p class='lede'>Project settings live on your main computer.</p>"
144
+ rows = []
145
+ for p in projects:
146
+ vis = p.get("visibility", "local")
147
+ sel = "".join(f"<option value='{k}'{' selected' if vis == k else ''}>{t}</option>"
148
+ for k, t in (("public", "Public: show links"), ("private", "Private repository"),
149
+ ("local", "Local only")))
150
+ rows.append(f"<tr><td><b>{h(p.get('display') or p['ctx'])}</b><br><span class='muted'>{h(p['ctx'])}</span></td>"
151
+ f"<td><form method='post' action='/projects'><input type='hidden' name='csrf' value='{{csrf}}'>"
152
+ f"<input type='hidden' name='ctx' value='{h(p['ctx'])}'>"
153
+ f"<select name='visibility' aria-label='Visibility'>{sel}</select>"
154
+ f"<input type='url' name='url' aria-label='Repository or project link' placeholder='https://…' value='{h(p.get('url'))}'>"
155
+ f"<button class='small' type='submit'>Save</button></form></td></tr>")
156
+ table = ("<table><thead><tr><th>Project</th><th>How it appears on your CV</th></tr></thead><tbody>"
157
+ + "".join(rows) + "</tbody></table>") if rows else "<p class='muted'>No projects yet.</p>"
158
+ return f"""<h1>Projects</h1><p class="lede">Public projects get blue proof links to the exact work. Private ones
159
+ keep every skill and show "(private repository)". Local work shows no label.</p>{message(msg, error)}{table}
160
+ <h2>Add a project</h2>
161
+ <form class="card" method="post" action="/projects"><input type="hidden" name="csrf" value="{{csrf}}">
162
+ <label for="ctx">Short name<span class="hint">e.g. flood-copilot</span></label><input type="text" id="ctx" name="ctx" required>
163
+ <label for="display">Name shown on your CV</label><input type="text" id="display" name="display">
164
+ <label for="visibility">Visibility</label><select id="visibility" name="visibility">
165
+ <option value="private">Private repository</option><option value="public">Public: show links</option><option value="local">Local only</option></select>
166
+ <label for="url">Link (public projects)</label><input type="url" id="url" name="url" placeholder="https://github.com/you/project">
167
+ <button type="submit">Add project</button></form>"""
168
+
169
+
170
+ def cards_page(rows: list[dict]) -> str:
171
+ if not rows:
172
+ return "<h1>My evidence</h1><p class='lede'>Nothing yet. <a href='/add'>Add your first piece of evidence</a>.</p>"
173
+ body = "".join(
174
+ f"<tr><td>{h(r['txt'])}</td><td>{h(', '.join(r['s']))}</td>"
175
+ f"<td class='lvl-{h(r['level'])}'>{h(LEVEL_TEXT.get(r['level'], r['level']))}</td>"
176
+ f"<td class='muted'>{h(r['t'][:10])}</td></tr>" for r in rows)
177
+ return (f"<h1>My evidence</h1><p class='lede'>The {len(rows)} most recent cards. Each line on a CV points back to "
178
+ f"one of these.</p><table><thead><tr><th>What you did</th><th>Skills</th><th>Proof</th><th>Date</th></tr>"
179
+ f"</thead><tbody>{body}</tbody></table>")
180
+
181
+
182
+ def build_form(roles: list[tuple[str, str]], is_hub: bool, msg: str = "", error: bool = False) -> str:
183
+ if not is_hub:
184
+ return ("<h1>Build a CV</h1><p class='lede'>CVs are built on your main computer (the hub). Your evidence from "
185
+ "this computer is sent there automatically.</p>")
186
+ opts = "<option value=''>Choose a role…</option>" + "".join(
187
+ f"<option value='{h(rid)}'>{h(title)}</option>" for rid, title in roles)
188
+ fmts = "".join(f"<label class='check'><input type='checkbox' name='formats' value='{k}' checked> {t}</label>"
189
+ for k, t in (("pdf", "PDF"), ("docx", "Word"), ("md", "Markdown")))
190
+ return f"""<h1>Build a CV</h1><p class="lede">Pick a role, or paste a job posting to tailor the CV to it. Every line
191
+ will point to its proof, and anything the evidence can't support is left out.</p>{message(msg, error)}
192
+ <form class="card" method="post" action="/build"><input type="hidden" name="csrf" value="{{csrf}}">
193
+ <label for="role">Role</label><select id="role" name="role">{opts}</select>
194
+ <label for="jd">…or paste a job posting<span class="hint">If you paste one, the CV is tailored to it and you get a gap report.</span></label>
195
+ <textarea id="jd" name="jd"></textarea>
196
+ <label>Formats</label>{fmts}
197
+ <label class="check"><input type="checkbox" name="use_ai" checked> Let Claude write the lines (honesty checks still apply)</label>
198
+ <button type="submit">Build my CV</button></form>"""
199
+
200
+
201
+ def build_result(rel_dir: str, files: list[str], log: list[str], reports: dict[str, str]) -> str:
202
+ names = {"cv.pdf": "Download PDF", "cv.docx": "Download Word", "cv.md": "Download Markdown"}
203
+ dl = "".join(f'<a href="/download/{quote(rel_dir + "/" + f)}">{names[f]}</a>' for f in files if f in names)
204
+ rep = "".join(f"<h2>{h(title)}</h2><pre>{h(text)}</pre>" for title, text in reports.items() if text)
205
+ return (f"<h1>Your CV is ready</h1><p class='lede'>{h(' · '.join(log[-3:]))}</p>"
206
+ f"<div class='downloads'>{dl}</div>{rep}")
cvprism/app/server.py ADDED
@@ -0,0 +1,382 @@
1
+ """`cvprism app`: a local browser app for people who don't use a terminal (ADR-018).
2
+
3
+ Security: binds 127.0.0.1 only; a one-time key in the URL becomes an HttpOnly, SameSite=Strict cookie;
4
+ every POST carries a CSRF token; the Host header must be localhost (DNS-rebinding defence); strict CSP; all
5
+ output escaped; downloads limited to the vault's build folder.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import email.parser
10
+ import email.policy
11
+ import secrets
12
+ import tempfile
13
+ import threading
14
+ import urllib.parse
15
+ from datetime import datetime
16
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
17
+ from pathlib import Path
18
+
19
+ from .. import config, paths, yamlio
20
+ from . import pages
21
+
22
+ MAX_BODY = 25 * 1024 * 1024
23
+ COOKIE = "cvprism_app"
24
+
25
+
26
+ def _cfg() -> dict:
27
+ return config.load_device()
28
+
29
+
30
+ def _vault(cfg: dict) -> Path | None:
31
+ return Path(cfg["vault_path"]) if cfg.get("role") == "hub" and cfg.get("vault_path") else None
32
+
33
+
34
+ def _profile(cfg: dict) -> dict:
35
+ v = _vault(cfg)
36
+ if v and (v / "profile.yaml").is_file():
37
+ return yamlio.load(v / "profile.yaml") or {}
38
+ return {}
39
+
40
+
41
+ def _cards(cfg: dict) -> list[dict]:
42
+ from ..hub.merge import read_cards
43
+ from ..sync.outbox import Outbox
44
+
45
+ v = _vault(cfg)
46
+ own = list(Outbox(paths.outbox_dir(), cfg["device_id"]).iter_cards())
47
+ if v is None:
48
+ return own
49
+ ids = {c["id"] for c in read_cards(v)}
50
+ return read_cards(v) + [c for c in own if c["id"] not in ids]
51
+
52
+
53
+ def _with_levels(cards: list[dict], cfg: dict) -> list[dict]:
54
+ from ..compile.evidence import LinkIndex, card_proof
55
+
56
+ prof = _profile(cfg)
57
+ v = _vault(cfg)
58
+ idx = LinkIndex.load(v) if v else LinkIndex()
59
+ return [dict(c, level=card_proof(c, prof, idx).level) for c in cards]
60
+
61
+
62
+ def _last_build(cfg: dict) -> str | None:
63
+ v = _vault(cfg)
64
+ if not v or not (v / "build").is_dir():
65
+ return None
66
+ dirs = sorted((d for d in (v / "build").glob("*/*") if d.is_dir() and (d / "build.json").exists()),
67
+ key=lambda d: d.stat().st_mtime)
68
+ if not dirs:
69
+ return None
70
+ return datetime.fromtimestamp(dirs[-1].stat().st_mtime).strftime("%d %b %Y")
71
+
72
+
73
+ def _roles(cfg: dict) -> list[tuple[str, str]]:
74
+ from ..compile.roles import load_role, starter_roles
75
+
76
+ v = _vault(cfg)
77
+ ids = list(starter_roles())
78
+ if v and (v / "roles").is_dir():
79
+ ids += [p.stem for p in (v / "roles").glob("*.yaml") if p.stem not in ids]
80
+ out = []
81
+ for rid in ids:
82
+ try:
83
+ out.append((rid, load_role(rid, v)["title"]))
84
+ except Exception: # noqa: BLE001 - a broken role file shouldn't take the page down
85
+ continue
86
+ return out
87
+
88
+
89
+ def _set_project(cfg: dict, ctx: str, visibility: str, url: str, display: str) -> str:
90
+ from ..compile.evidence import is_https, normalise_repo_url
91
+ from ..novelty.ids import slugify
92
+ from ..schemas import errors
93
+
94
+ v = _vault(cfg)
95
+ if v is None:
96
+ raise ValueError("Project settings live on your main computer.")
97
+ slug = slugify(ctx)
98
+ if not slug:
99
+ raise ValueError("Give the project a short name.")
100
+ if visibility not in ("public", "private", "local"):
101
+ raise ValueError("Choose public, private or local.")
102
+ url = normalise_repo_url(url) if url else ""
103
+ if url and not is_https(url):
104
+ raise ValueError("The link must start with https://")
105
+ if visibility == "public" and not url:
106
+ raise ValueError("A public project needs a link to its repository or page.")
107
+ pf = v / "profile.yaml"
108
+ prof = yamlio.load(pf) or {"v": 1, "person": {"name": "Your Name"}}
109
+ projs = prof.setdefault("projects", [])
110
+ p = next((x for x in projs if x.get("ctx") == slug), None)
111
+ if p is None:
112
+ p = {"ctx": slug, "display": display or slug.replace("-", " ").capitalize()}
113
+ projs.append(p)
114
+ if display:
115
+ p["display"] = display
116
+ p["visibility"] = visibility
117
+ if url:
118
+ p["url"] = url
119
+ errs = errors("profile", prof)
120
+ if errs:
121
+ raise ValueError("; ".join(errs[:2]))
122
+ yamlio.dump(prof, pf)
123
+ return f"Saved: {p.get('display') or slug} is now {visibility}."
124
+
125
+
126
+ class AppServer:
127
+ def __init__(self, port: int = 0):
128
+ self.token = secrets.token_urlsafe(24)
129
+ outer = self
130
+
131
+ class Handler(BaseHTTPRequestHandler):
132
+ def log_message(self, *a):
133
+ pass
134
+
135
+ # ---- plumbing ----------------------------------------------------------------------------
136
+ def _host_ok(self) -> bool:
137
+ return (self.headers.get("Host") or "").split(":")[0] in ("127.0.0.1", "localhost")
138
+
139
+ def _authed(self) -> bool:
140
+ raw = self.headers.get("Cookie") or ""
141
+ parts = dict(p.strip().split("=", 1) for p in raw.split(";") if "=" in p)
142
+ return secrets.compare_digest(parts.get(COOKIE, ""), outer.token)
143
+
144
+ def _send(self, code: int, body: bytes, ctype="text/html; charset=utf-8", extra=None):
145
+ self.send_response(code)
146
+ self.send_header("Content-Type", ctype)
147
+ self.send_header("Cache-Control", "no-store")
148
+ self.send_header("X-Frame-Options", "DENY")
149
+ self.send_header("X-Content-Type-Options", "nosniff")
150
+ self.send_header("Referrer-Policy", "no-referrer")
151
+ self.send_header("Content-Security-Policy",
152
+ "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'")
153
+ for k, v in (extra or {}).items():
154
+ self.send_header(k, v)
155
+ self.end_headers()
156
+ self.wfile.write(body)
157
+
158
+ def _page(self, code: int, title: str, active: str, body: str):
159
+ body = body.replace("{csrf}", outer.token)
160
+ self._send(code, pages.layout(title, active, body))
161
+
162
+ def _deny(self):
163
+ self._send(403, pages.layout("Locked", "", "<h1>Open cvprism from the link in your terminal</h1>"
164
+ "<p class='lede'>Run <code>cvprism app</code> again if you closed it.</p>"))
165
+
166
+ def _form(self) -> tuple[dict, dict]:
167
+ n = int(self.headers.get("Content-Length") or 0)
168
+ if n > MAX_BODY:
169
+ raise ValueError("That file is too large (25 MB maximum).")
170
+ raw = self.rfile.read(n)
171
+ ctype = self.headers.get("Content-Type") or ""
172
+ if ctype.startswith("multipart/form-data"):
173
+ msg = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes(
174
+ f"Content-Type: {ctype}\r\n\r\n".encode() + raw)
175
+ fields, files = {}, {}
176
+ for part in msg.iter_parts():
177
+ name = part.get_param("name", header="content-disposition")
178
+ if part.get_filename():
179
+ files[name] = (part.get_filename(), part.get_payload(decode=True) or b"")
180
+ else:
181
+ fields.setdefault(name, []).append((part.get_payload(decode=True) or b"").decode("utf-8", "replace"))
182
+ return fields, files
183
+ return urllib.parse.parse_qs(raw.decode("utf-8", "replace"), keep_blank_values=True), {}
184
+
185
+ # ---- GET ---------------------------------------------------------------------------------
186
+ def do_GET(self): # noqa: N802
187
+ if not self._host_ok():
188
+ return self._deny()
189
+ path = urllib.parse.urlparse(self.path).path
190
+ if path.startswith("/k/"):
191
+ if secrets.compare_digest(path[3:], outer.token):
192
+ return self._send(303, b"", extra={
193
+ "Location": "/", "Set-Cookie": f"{COOKIE}={outer.token}; HttpOnly; SameSite=Strict; Path=/"})
194
+ return self._deny()
195
+ if not self._authed():
196
+ return self._deny()
197
+ try:
198
+ cfg = _cfg()
199
+ except config.NotInitialised:
200
+ return self._page(200, "Set up", "/", "<h1>Set up cvprism first</h1>"
201
+ "<p class='lede'>Run <code>cvprism init --web</code>, then open the app again.</p>")
202
+ if path.startswith("/download/"):
203
+ return self._download(cfg, path[len("/download/"):])
204
+ prof = _profile(cfg)
205
+ if path == "/":
206
+ cards = _with_levels(_cards(cfg), cfg)
207
+ counts: dict = {}
208
+ for c in cards:
209
+ counts[c["level"]] = counts.get(c["level"], 0) + 1
210
+ return self._page(200, "Home", "/", pages.home((prof.get("person") or {}).get("name", ""),
211
+ cfg["role"], counts, len(prof.get("projects") or []),
212
+ _last_build(cfg)))
213
+ if path == "/add":
214
+ return self._page(200, "Add evidence", "/add", pages.add_form(prof.get("projects") or []))
215
+ if path == "/import":
216
+ return self._page(200, "Import", "/import", pages.import_form())
217
+ if path == "/projects":
218
+ return self._page(200, "Projects", "/projects",
219
+ pages.projects_page(prof.get("projects") or [], _vault(cfg) is not None))
220
+ if path == "/cards":
221
+ rows = sorted(_with_levels(_cards(cfg), cfg), key=lambda c: c["t"], reverse=True)[:50]
222
+ return self._page(200, "My evidence", "/cards", pages.cards_page(rows))
223
+ if path == "/build":
224
+ return self._page(200, "Build a CV", "/build",
225
+ pages.build_form(_roles(cfg) if _vault(cfg) else [], _vault(cfg) is not None))
226
+ return self._page(404, "Not found", "", "<h1>Page not found</h1>")
227
+
228
+ def _download(self, cfg: dict, rel: str):
229
+ v = _vault(cfg)
230
+ rel = urllib.parse.unquote(rel)
231
+ if v is None or not rel or "\\" in rel or rel.startswith("/") or ".." in Path(rel).parts:
232
+ return self._send(400, b"bad path", "text/plain")
233
+ root = (v / "build").resolve()
234
+ target = (root / rel).resolve()
235
+ if not target.is_relative_to(root) or not target.is_file():
236
+ return self._send(404, b"not found", "text/plain")
237
+ ctypes = {".pdf": "application/pdf", ".md": "text/markdown; charset=utf-8",
238
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}
239
+ self._send(200, target.read_bytes(), ctypes.get(target.suffix, "application/octet-stream"),
240
+ {"Content-Disposition": f'attachment; filename="{target.name}"'})
241
+
242
+ # ---- POST --------------------------------------------------------------------------------
243
+ def do_POST(self): # noqa: N802
244
+ if not self._host_ok() or not self._authed():
245
+ return self._deny()
246
+ try:
247
+ fields, files = self._form()
248
+ except ValueError as e:
249
+ return self._page(413, "Too large", "", pages.message(str(e), True))
250
+ one = lambda k: (fields.get(k) or [""])[0].strip() # noqa: E731
251
+ if not secrets.compare_digest(one("csrf"), outer.token):
252
+ return self._deny()
253
+ cfg = _cfg()
254
+ path = urllib.parse.urlparse(self.path).path
255
+ if path == "/add":
256
+ return self._post_add(cfg, fields, one)
257
+ if path == "/projects":
258
+ try:
259
+ msg = _set_project(cfg, one("ctx"), one("visibility") or "private", one("url"), one("display"))
260
+ err = False
261
+ except ValueError as e:
262
+ msg, err = str(e), True
263
+ prof = _profile(cfg)
264
+ return self._page(400 if err else 200, "Projects", "/projects",
265
+ pages.projects_page(prof.get("projects") or [], True, msg, err))
266
+ if path == "/import":
267
+ return self._post_import(cfg, files, one)
268
+ if path == "/build":
269
+ return self._post_build(cfg, fields, one)
270
+ return self._page(404, "Not found", "", "<h1>Page not found</h1>")
271
+
272
+ def _post_add(self, cfg, fields, one):
273
+ from ..capture.manual import LogError, log_entry
274
+
275
+ prof = _profile(cfg)
276
+ values = {k: one(k) for k in ("what", "skill", "depth", "result_metric", "result_value",
277
+ "result_unit", "link", "project", "work", "use_ai")}
278
+ skills = [s.strip() for s in values["skill"].split(",") if s.strip()]
279
+ use_ai = bool(values["use_ai"])
280
+ result = None
281
+ if values["result_value"]:
282
+ result = f"{values['result_metric'] or 'result'}:{values['result_value']}:{values['result_unit']}"
283
+ try:
284
+ if not use_ai and not skills:
285
+ raise LogError("Name at least one skill, or tick 'Let Claude polish the wording'.")
286
+ res = log_entry(values["what"], cfg=cfg, skills=skills, depth=int(values["depth"] or 2),
287
+ result=result, work=bool(values["work"]), ctx=values["project"] or None,
288
+ raw=not use_ai, links=[values["link"]] if values["link"] else None)
289
+ except (LogError, ValueError) as e:
290
+ return self._page(400, "Add evidence", "/add",
291
+ pages.add_form(prof.get("projects") or [], values, str(e), True))
292
+ msg = "Saved. " + " ".join(m for m in res.messages if not m.startswith("cvprism:"))
293
+ return self._page(200, "Add evidence", "/add", pages.add_form(prof.get("projects") or [], None, msg))
294
+
295
+ def _post_import(self, cfg, files, one):
296
+ from ..capture.importers import import_cv, import_linkedin
297
+
298
+ kind = one("kind")
299
+ name, data = files.get("file", ("", b""))
300
+ if not data:
301
+ return self._page(400, "Import", "/import", pages.import_form("Choose a file to upload.", True))
302
+ suffix = Path(name).suffix.lower()
303
+ allowed = {".zip"} if kind == "linkedin" else {".docx", ".md", ".txt", ".pdf"}
304
+ if suffix not in allowed:
305
+ return self._page(400, "Import", "/import",
306
+ pages.import_form(f"Expected a {' or '.join(sorted(allowed))} file.", True))
307
+ with tempfile.TemporaryDirectory() as td:
308
+ f = Path(td) / f"upload{suffix}"
309
+ f.write_bytes(data)
310
+ try:
311
+ fn = import_linkedin if kind == "linkedin" else import_cv
312
+ rep = fn(f, cfg, use_llm=bool(one("use_ai")))
313
+ except Exception as e: # noqa: BLE001
314
+ return self._page(400, "Import", "/import", pages.import_form(f"Couldn't import: {e}", True))
315
+ msg = (f"Imported: {rep.cards} new card(s), {rep.known} already known. "
316
+ f"Profile: +{rep.positions} position(s), +{rep.education} education, +{rep.certifications} "
317
+ f"certification(s). Imported lines are marked for review.")
318
+ return self._page(200, "Import", "/import", pages.import_form(msg))
319
+
320
+ def _post_build(self, cfg, fields, one):
321
+ from ..compile.build import BuildError, build_cv
322
+ from ..compile.jd import build_for_jd
323
+ from ..compile.roles import RoleError
324
+
325
+ v = _vault(cfg)
326
+ if v is None:
327
+ return self._page(200, "Build a CV", "/build", pages.build_form([], False))
328
+ formats = [f for f in fields.get("formats", []) if f in ("pdf", "docx", "md")] or ["pdf", "docx", "md"]
329
+ role, jd = one("role"), (fields.get("jd") or [""])[0]
330
+ try:
331
+ if jd.strip():
332
+ jd_dir = v / "build" / "_postings"
333
+ jd_dir.mkdir(parents=True, exist_ok=True)
334
+ jd_file = jd_dir / f"{datetime.now():%Y%m%d-%H%M%S}.txt"
335
+ jd_file.write_text(jd, encoding="utf-8")
336
+ res = build_for_jd(cfg, str(jd_file), use_llm=bool(one("use_ai")), formats=formats,
337
+ base_role=role or None)
338
+ elif role:
339
+ res = build_cv(cfg, role, use_llm=bool(one("use_ai")), formats=formats)
340
+ else:
341
+ raise BuildError("Choose a role or paste a job posting.")
342
+ except (BuildError, RoleError) as e:
343
+ return self._page(400, "Build a CV", "/build", pages.build_form(_roles(cfg), True, str(e), True))
344
+ rel = res.out_dir.resolve().relative_to((v / "build").resolve()).as_posix()
345
+ files = [f for f in ("cv.pdf", "cv.docx", "cv.md") if (res.out_dir / f).exists()]
346
+ reports = {}
347
+ for title, f in (("ATS read-back", "ats.md"), ("Gap report", "gaps.md"), ("Writing quality", "quality.md"),
348
+ ("Removed claims", "rejected.md")):
349
+ p = res.out_dir / f
350
+ if p.exists():
351
+ reports[title] = p.read_text(encoding="utf-8")
352
+ return self._page(200, "Your CV", "/build", pages.build_result(rel, files, res.log, reports))
353
+
354
+ self.httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler)
355
+ self.port = self.httpd.server_address[1]
356
+ self.url = f"http://127.0.0.1:{self.port}/k/{self.token}"
357
+ self._thread: threading.Thread | None = None
358
+
359
+ def start(self) -> None:
360
+ self._thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
361
+ self._thread.start()
362
+
363
+ def stop(self) -> None:
364
+ self.httpd.shutdown()
365
+ self.httpd.server_close()
366
+
367
+
368
+ def run(open_browser: bool = True, port: int = 0) -> None:
369
+ import webbrowser
370
+
371
+ s = AppServer(port=port)
372
+ s.start()
373
+ print(f"cvprism app is running. Open: {s.url}")
374
+ print("Keep this window open while you use it; press Ctrl+C to stop.")
375
+ if open_browser:
376
+ webbrowser.open(s.url)
377
+ try:
378
+ threading.Event().wait()
379
+ except KeyboardInterrupt:
380
+ pass
381
+ finally:
382
+ s.stop()
File without changes