devcoach 2.5.0 → 2.6.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.
package/dist/bin.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var t=process.argv[2]??"",r=new Set(["stop-hook","prompt-hook","gemini-stop-hook","gemini-prompt-hook","codex-stop-hook","codex-prompt-hook","onboard-hook","lesson-ready"]);try{if(r.has(t)){let{runHook:o}=await import('./hooks-WFR6QCFN.js');o(t);}else {let{runCli:o}=await import('./commands-NVMZMCN3.js');await o();}}catch(o){console.error(o),process.exit(1);}
2
+ var r=process.argv[2]??"",e=new Set(["stop-hook","prompt-hook","gemini-stop-hook","gemini-prompt-hook","codex-stop-hook","codex-prompt-hook","onboard-hook","lesson-ready"]);try{if(e.has(r)){let{runHook:o}=await import('./hooks-TOKSEH4Z.js');o(r);}else {let{runCli:o}=await import('./commands-WM7JZ3SG.js');await o();}}catch(o){o?.name==="SchemaTooNewError"&&(console.error(o.message),process.exit(3)),console.error(o),process.exit(1);}
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import {z as z$1}from'zod';import {existsSync,readFileSync,lstatSync,mkdirSync,writeFileSync}from'fs';import {createRequire}from'module';import {homedir}from'os';import {join,dirname}from'path';import {strToU8,zipSync,unzipSync,deflateSync,strFromU8,Inflate}from'fflate';var de={version:"2.6.0"};var b=de.version;var X=z$1.enum(["junior","mid","senior"]),H=z$1.enum(["github","gitlab","bitbucket","local"]),Ve=z$1.enum(["know","understood","dont_know"]),Nn=z$1.number().int().min(0).max(10);function j(e){return e.toISOString().replace(/\.\d{3}Z$/,"Z")}function Je(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new TypeError("Invalid Date");return e}let t=e.trim();/[zZ]$|[+-]\d{2}:?\d{2}$/.test(t)||(t=t.includes("T")||t.includes(" ")?`${t.replace(" ","T")}Z`:`${t}T00:00:00Z`);let s=new Date(t);if(Number.isNaN(s.getTime()))throw new TypeError(`Cannot parse timestamp ${JSON.stringify(e)} \u2014 expected ISO 8601`);return s}function Ze(e){let t=Je(e),n=new Date;return t.getTime()>n.getTime()&&(t=n),j(t)}var Qe=z$1.union([z$1.string(),z$1.date()]).transform((e,t)=>{try{return Ze(e)}catch(n){return t.addIssue({code:"custom",message:n.message}),z$1.NEVER}}),S=z$1.string().nullish().transform(e=>e??null),et=z$1.object({id:z$1.string(),timestamp:Qe,topic_id:z$1.string(),categories:z$1.array(z$1.string()),title:z$1.string(),level:X,summary:z$1.string(),body:S,task_context:S,project:S,repository:S,branch:S,commit_hash:S,folder:S,repository_platform:H.nullish().transform(e=>e??null),starred:z$1.boolean().default(false),feedback:Ve.nullish().transform(e=>e??null),imported:z$1.boolean().default(false),shared_by:S}),tt=z$1.object({topic:z$1.string(),confidence:z$1.number().int()}),nt=z$1.object({name:z$1.string(),topics:z$1.array(z$1.string())});z$1.object({knowledge:z$1.array(tt),groups:z$1.array(nt)});var st=z$1.enum(["system","dark","light"]),ot=z$1.enum(["auto","lessons","knowledge"]),rt=z$1.enum(["session","global"]);z$1.object({max_per_day:z$1.number().int().default(2),min_gap_minutes:z$1.number().int().default(240),ui_theme:st.default("system"),ui_home:ot.default("auto"),nudge_every:z$1.number().int().min(0).default(10),nudge_scope:rt.default("session"),share_name:z$1.string().nullable().default(null)});var it=z$1.enum(["active","completed","abandoned"]),at=z$1.enum(["concept","example","practice","check"]),ct=z$1.enum(["todo","done","skipped"]),ut=z$1.object({concept:z$1.string().min(1),known:z$1.boolean()}),B=z$1.object({course_id:z$1.string(),position:z$1.number().int().min(1),title:z$1.string().min(1),kind:at,anchor:z$1.string().regex(/^[a-z0-9][a-z0-9-]*$/),status:ct.default("todo"),done_at:S}),W=z$1.object({id:z$1.string().regex(/^[a-z0-9-]+$/),lesson_id:S,topic_id:z$1.string().min(1),title:z$1.string().min(1),goal:S,prerequisites:z$1.array(ut).default([]),status:it.default("active"),created_at:z$1.string(),updated_at:z$1.string(),completed_at:S});function R(e){return et.parse(e)}var {DatabaseSync:ft}=createRequire(import.meta.url)("node:sqlite"),Q=process.env.DEVCOACH_DIR??join(homedir(),".devcoach"),ee=join(Q,"coaching.db"),k=join(Q,"learning-state.md"),ye=join(Q,"courses"),K="settings.json",G="lessons.json",Y="knowledge.json",z="learning-state.md",q="courses.json",v="index.html",Et=new RegExp(`^courses/([a-z0-9-]+)/${v.replace(".","\\.")}$`),Mn={engineering:8,architecture:8,patterns:7,debugging:8,node:7,javascript:7,typescript:6,python:4,django:3,fastapi:4,docker:8,traefik:7,coolify:7,postgresql:6,redis:6,git:7,ci_cd:6,security:5,performance:6,testing:5,linux:7,networking:6,react:5,frontend:5},_t=80;function ht(e){return e.trim().slice(0,_t)}var St={max_per_day:"2",min_gap_minutes:"240",ui_theme:"system",ui_home:"auto",nudge_every:"10",nudge_scope:"session",share_name:""},yt=50;function f(e,t,...n){return e.prepare(t).all(...n)}function E(e,t,...n){return e.prepare(t).get(...n)}function l(e,t,...n){return Number(e.prepare(t).run(...n).changes)}function ge(e=ee,t=false){e!==":memory:"&&mkdirSync(dirname(e),{recursive:true});let n=new ft(e,{readOnly:t});return n.exec("PRAGMA busy_timeout = 3000"),n}var I=6,Tt="2.6.0",V="schema_app_version",J="schema_min_app_version";function bt(e){let t=e.upgradedBy?`devcoach ${e.upgradedBy}`:"a newer devcoach",n=e.minApp?`devcoach \u2265 ${e.minApp}`:"a newer devcoach";return `The coaching database was upgraded by ${t} (schema v${e.dbSchema}); this is devcoach ${b} (schema v${e.appSchema}). Reads work; writes need ${n} \u2014 update this install, or use the newer channel.`}var N=class extends Error{constructor(n){super(bt(n));this.compat=n;this.name="SchemaTooNewError";}compat},Te=new WeakMap;function be(e){return Te.get(e)??null}function Rt(e){try{let t=f(e,"SELECT key, value FROM settings WHERE key IN (?, ?)",V,J),n=s=>t.find(o=>o.key===s)?.value??null;return {upgradedBy:n(V),minApp:n(J)}}catch{return {upgradedBy:null,minApp:null}}}function Lt(e){let t=e.prepare("PRAGMA user_version").get();return Number(t?.user_version??0)}function Nt(e=ee){let t=ge(e),n=Lt(t);return n>I?(t.close(),t=ge(e,true),t.exec("PRAGMA query_only = 1"),Te.set(t,{readOnly:true,dbSchema:n,appSchema:I,...Rt(t)}),t):(n<I&&(xt(t,n),t.exec(`PRAGMA user_version = ${I}`)),t)}function Re(e,t){let n=be(e);if(n)throw new N(n);e.exec("BEGIN IMMEDIATE");try{let s=t();return e.exec("COMMIT"),s}catch(s){try{e.exec("ROLLBACK");}catch{}throw s}}function Fn(e,t=ee){let n=Nt(t);try{return e(n)}catch(s){let o=be(n);throw o&&!(s instanceof N)&&/readonly database/i.test(String(s))?new N(o):s}finally{n.close();}}function Ot(e,t){try{return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}catch{return false}}function xt(e,t=0){let n=Ot(e,"courses");e.exec(`
3
+ CREATE TABLE IF NOT EXISTS lessons (
4
+ id TEXT PRIMARY KEY,
5
+ timestamp TEXT NOT NULL,
6
+ topic_id TEXT NOT NULL,
7
+ categories TEXT NOT NULL,
8
+ title TEXT NOT NULL,
9
+ level TEXT NOT NULL,
10
+ summary TEXT NOT NULL,
11
+ body TEXT,
12
+ task_context TEXT,
13
+ project TEXT,
14
+ repository TEXT,
15
+ branch TEXT,
16
+ commit_hash TEXT,
17
+ folder TEXT,
18
+ feedback TEXT,
19
+ repository_platform TEXT,
20
+ starred INTEGER NOT NULL DEFAULT 0,
21
+ imported INTEGER NOT NULL DEFAULT 0,
22
+ shared_by TEXT
23
+ );
24
+
25
+ CREATE TABLE IF NOT EXISTS knowledge (
26
+ topic TEXT PRIMARY KEY,
27
+ confidence INTEGER NOT NULL DEFAULT 5,
28
+ updated_at TEXT NOT NULL
29
+ );
30
+
31
+ CREATE TABLE IF NOT EXISTS settings (
32
+ key TEXT PRIMARY KEY,
33
+ value TEXT NOT NULL
34
+ );
35
+
36
+ CREATE TABLE IF NOT EXISTS knowledge_group_names (
37
+ group_name TEXT PRIMARY KEY
38
+ );
39
+
40
+ CREATE TABLE IF NOT EXISTS knowledge_groups (
41
+ group_name TEXT NOT NULL,
42
+ topic TEXT NOT NULL,
43
+ PRIMARY KEY (group_name, topic)
44
+ );
45
+
46
+ -- Courses (v5): the index of ~/.devcoach/courses/<id>/index.html \u2014 one rich document per
47
+ -- course, steps are its sections. prerequisites = JSON [{concept, known}] from the Q&A.
48
+ CREATE TABLE IF NOT EXISTS courses (
49
+ id TEXT PRIMARY KEY,
50
+ lesson_id TEXT,
51
+ topic_id TEXT NOT NULL,
52
+ title TEXT NOT NULL,
53
+ goal TEXT,
54
+ prerequisites TEXT NOT NULL DEFAULT '[]',
55
+ status TEXT NOT NULL DEFAULT 'active',
56
+ created_at TEXT NOT NULL,
57
+ updated_at TEXT NOT NULL,
58
+ completed_at TEXT
59
+ );
60
+
61
+ CREATE TABLE IF NOT EXISTS course_steps (
62
+ course_id TEXT NOT NULL,
63
+ position INTEGER NOT NULL,
64
+ title TEXT NOT NULL,
65
+ kind TEXT NOT NULL,
66
+ anchor TEXT NOT NULL,
67
+ status TEXT NOT NULL DEFAULT 'todo',
68
+ done_at TEXT,
69
+ PRIMARY KEY (course_id, position)
70
+ );
71
+
72
+ -- One-shot data migrations, by name: a stamp downgraded by an older build must never
73
+ -- make a newer one repeat them (v6; runtime metadata, not backed up).
74
+ CREATE TABLE IF NOT EXISTS schema_migrations (
75
+ name TEXT PRIMARY KEY,
76
+ applied_at TEXT NOT NULL
77
+ );
78
+
79
+ CREATE INDEX IF NOT EXISTS idx_courses_lesson_id ON courses (lesson_id);
80
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_course_steps_anchor ON course_steps (course_id, anchor);
81
+
82
+ -- Runtime-only: per-session interaction counter for lesson-cue pacing.
83
+ -- Never exported/imported (backup carries config, not this state).
84
+ CREATE TABLE IF NOT EXISTS nudge_state (
85
+ session_id TEXT PRIMARY KEY,
86
+ interactions INTEGER NOT NULL DEFAULT 0,
87
+ updated_at TEXT NOT NULL
88
+ );
89
+
90
+ -- Runtime-only, single row: cue lifecycle. pending=1 between an emitted cue and
91
+ -- its resolution (log_lesson or skip_lesson), arming a shorter retry threshold.
92
+ CREATE TABLE IF NOT EXISTS cue_state (
93
+ id INTEGER PRIMARY KEY CHECK (id = 1),
94
+ pending INTEGER NOT NULL DEFAULT 0,
95
+ last_cue_at TEXT,
96
+ last_skip_reason TEXT
97
+ );
98
+
99
+ CREATE INDEX IF NOT EXISTS idx_lessons_timestamp ON lessons (timestamp);
100
+ CREATE INDEX IF NOT EXISTS idx_lessons_starred_ts ON lessons (starred, timestamp);
101
+ CREATE INDEX IF NOT EXISTS idx_lessons_feedback ON lessons (feedback);
102
+ CREATE INDEX IF NOT EXISTS idx_lessons_topic_id ON lessons (topic_id);
103
+ `),Ct(e,t,n),At(e),y(e,V,b),y(e,J,Tt);}var fe="v4-feedback-understood";function wt(e,t){return e.prepare("SELECT 1 FROM schema_migrations WHERE name = ?").get(t)!==void 0}function Dt(e,t){l(e,"INSERT OR IGNORE INTO schema_migrations (name, applied_at) VALUES (?, ?)",t,new Date().toISOString());}function Ct(e,t,n){for(let s of ["ALTER TABLE lessons ADD COLUMN body TEXT","ALTER TABLE lessons ADD COLUMN imported INTEGER NOT NULL DEFAULT 0","ALTER TABLE lessons ADD COLUMN shared_by TEXT"])try{e.exec(s);}catch{}wt(e,fe)||(t<4&&!n&&e.exec("UPDATE lessons SET feedback = 'understood' WHERE feedback = 'dont_know'"),Dt(e,fe));}function At(e){for(let[t,n]of Object.entries(St))l(e,"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",t,n);}var Le="(id, timestamp, topic_id, categories, title, level, summary, body, task_context, project, repository, branch, commit_hash, folder, repository_platform, starred, feedback, imported, shared_by)",Ne="(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";function Oe(e){return [e.id,e.timestamp,e.topic_id,JSON.stringify(e.categories),e.title,e.level,e.summary,e.body,e.task_context,e.project,e.repository,e.branch,e.commit_hash,e.folder,e.repository_platform,e.starred?1:0,e.feedback,e.imported?1:0,e.shared_by]}function $n(e,t){l(e,`INSERT OR REPLACE INTO lessons ${Le} VALUES ${Ne}`,...Oe(t));}function te(e,t){return l(e,`INSERT OR IGNORE INTO lessons ${Le} VALUES ${Ne}`,...Oe(t))>0}var It=[["project","project"],["repository","repository"],["branch","branch"],["commit","commit_hash"]];function kt(e,t){if(e.date_from==null&&e.date_to==null){let n=qt(e.period??null);n!=null&&t("timestamp >= ?",n);return}if(e.date_from!=null&&t("timestamp >= ?",e.date_from),e.date_to!=null){let n=e.date_to.includes("T")||e.date_to.includes(" ");t("timestamp <= ?",n?e.date_to:`${e.date_to}T23:59:59`);}}function xe(e){let t=[],n=[],s=(r,...i)=>{t.push(r),n.push(...i);};kt(e,s),e.category!=null&&s("categories LIKE ?",`%"${e.category}"%`),e.level!=null&&s("level = ?",e.level);for(let[r,i]of It){let a=e[r];a!=null&&s(`${i} LIKE ?`,`%${a}%`);}if(e.starred!=null&&s("starred = ?",e.starred?1:0),e.imported!=null&&s("imported = ?",e.imported?1:0),e.shared_by!=null&&s("imported = 1 AND shared_by = ?",e.shared_by),e.search!=null)for(let r of e.search.split(/\s+/).filter(Boolean)){let i=`%${r}%`;s("(title LIKE ? OR topic_id LIKE ? OR summary LIKE ? OR body LIKE ? OR shared_by LIKE ?)",i,i,i,i,i);}return e.feedback==="none"?s("feedback IS NULL"):e.feedback!=null&&s("feedback = ?",e.feedback),{where:t.length?`WHERE ${t.join(" AND ")}`:"",params:n}}function ne(e,t={}){let{where:n,params:s}=xe(t),o=E(e,`SELECT COUNT(*) AS n FROM lessons ${n}`,...s);return Number(o?.n??0)}var vt=new Set(["timestamp","level","topic_id","title","feedback"]),Ut=new Set(["project","repository","branch","commit_hash","repository_platform"]);function Pn(e,t={}){let{where:n,params:s}=xe(t),o=t.sort&&vt.has(t.sort)?t.sort:"timestamp",r=(t.order??"desc").toLowerCase()==="asc"?"ASC":"DESC",i=`SELECT * FROM lessons ${n} ORDER BY ${o} ${r}`,a=[...s];if(t.page!=null){let u=t.per_page??25;i+=" LIMIT ? OFFSET ?",a.push(u,(t.page-1)*u);}return f(e,i,...a).map(le)}function Xn(e,t){return l(e,"DELETE FROM lessons WHERE id = ?",t)>0}function Hn(e,t){if(t.length===0)return 0;let n=t.map(()=>"?").join(", ");return l(e,`DELETE FROM lessons WHERE id IN (${n})`,...t)}function jn(e,t,n){return l(e,"UPDATE lessons SET starred = ? WHERE id = ?",n?1:0,t)>0}function we(e,t,n){l(e,"UPDATE lessons SET feedback = ? WHERE id = ?",n||null,t);let s=E(e,"SELECT topic_id FROM lessons WHERE id = ?",t);return s?s.topic_id:null}function Mt(e){return f(e,"SELECT * FROM lessons ORDER BY timestamp DESC").map(le)}function se(e,t){let n=0,s=0,o=0;for(let r of t){let i;try{i=R(r);}catch{o+=1;continue}te(e,i)?n+=1:s+=1;}return {inserted:n,duplicated:s,invalid:o}}function Bn(e,t){if(!Ut.has(t))throw new Error(`Column not allowed: ${JSON.stringify(t)}`);return f(e,`SELECT DISTINCT ${t} FROM lessons WHERE ${t} IS NOT NULL ORDER BY ${t}`).map(s=>s[t])}function Wn(e){return f(e,"SELECT DISTINCT shared_by FROM lessons WHERE imported = 1 AND shared_by IS NOT NULL ORDER BY shared_by").map(t=>t.shared_by)}function De(e,t){let n=E(e,"SELECT * FROM lessons WHERE id = ?",t);return n?le(n):null}function Kn(e){return f(e,"SELECT DISTINCT value FROM lessons, json_each(lessons.categories) ORDER BY value").map(n=>n.value)}function Ce(e){return f(e,"SELECT DISTINCT topic_id FROM lessons").map(t=>t.topic_id)}function M(e,t){let n=E(e,"SELECT COUNT(*) AS n FROM lessons WHERE timestamp >= ? AND imported = 0",t);return Number(n?.n??0)}function Ae(e){let t=E(e,"SELECT timestamp FROM lessons WHERE imported = 0 ORDER BY timestamp DESC LIMIT 1");return t?t.timestamp:null}function x(e){let t={};for(let n of f(e,"SELECT topic, confidence FROM knowledge"))t[n.topic]=Number(n.confidence);return t}function oe(e){return f(e,"SELECT topic, confidence FROM knowledge ORDER BY topic").map(t=>({topic:t.topic,confidence:Number(t.confidence)}))}function re(e){let t=f(e,"SELECT group_name FROM knowledge_group_names ORDER BY group_name").map(s=>s.group_name),n=new Map;for(let s of f(e,"SELECT group_name, topic FROM knowledge_groups ORDER BY group_name, topic")){let o=s.group_name,r=n.get(o)??[];r.push(s.topic),n.set(o,r);}return t.map(s=>({name:s,topics:n.get(s)??[]}))}function U(e,t,n){let s=Math.max(0,Math.min(10,n)),o=new Date().toISOString();l(e,`INSERT INTO knowledge (topic, confidence, updated_at) VALUES (?, ?, ?)
104
+ ON CONFLICT(topic) DO UPDATE SET confidence = excluded.confidence, updated_at = excluded.updated_at`,t,s,o);}function Gn(e,t){let n=l(e,"DELETE FROM knowledge WHERE topic = ?",t);return l(e,"DELETE FROM knowledge_groups WHERE topic = ?",t),n>0}function Ee(e,t){let n=t.trim();if(!n)throw new Error("Group name must not be empty");return l(e,"INSERT OR IGNORE INTO knowledge_group_names (group_name) VALUES (?)",n)>0}function Yn(e,t){return l(e,"DELETE FROM knowledge_groups WHERE group_name = ?",t),l(e,"DELETE FROM knowledge_group_names WHERE group_name = ?",t)>0}function Ft(e,t,n){l(e,"INSERT OR IGNORE INTO knowledge_group_names (group_name) VALUES (?)",n),l(e,"DELETE FROM knowledge_groups WHERE topic = ?",t),l(e,"INSERT OR IGNORE INTO knowledge_groups (group_name, topic) VALUES (?, ?)",n,t);}function zn(e,t){l(e,"DELETE FROM knowledge_groups WHERE topic = ?",t);}function w(e){let t={};for(let A of f(e,"SELECT key, value FROM settings"))t[A.key]=A.value;let n=t.min_gap_minutes,s=t.min_hours_between,o;n!==void 0?o=Number.parseInt(n,10):s!==void 0?o=Number.parseInt(s,10)*60:o=240;let r=t.max_per_day,i=t.ui_theme??"system",a=i==="dark"||i==="light"||i==="system"?i:"system",u=t.ui_home??"auto",p=u==="lessons"||u==="knowledge"||u==="auto"?u:"auto",_=t.nudge_every,g=_!==void 0?Number.parseInt(_,10):10,h=t.nudge_scope==="global"?"global":"session";return {max_per_day:r!==void 0?Number.parseInt(r,10):2,min_gap_minutes:o,ui_theme:a,ui_home:p,nudge_every:Number.isFinite(g)&&g>=0?g:10,nudge_scope:h,share_name:t.share_name?.trim()||null}}function y(e,t,n){l(e,"INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",t,n);}function Ie(e,t,n){let s=E(e,"INSERT INTO nudge_state (session_id, interactions, updated_at) VALUES (?, 1, ?) ON CONFLICT(session_id) DO UPDATE SET interactions = interactions + 1, updated_at = excluded.updated_at RETURNING interactions",t,new Date().toISOString()),o=Number(s?.interactions??0);return o===1&&l(e,"DELETE FROM nudge_state WHERE session_id NOT IN (SELECT session_id FROM nudge_state ORDER BY updated_at DESC LIMIT ?)",yt),n==="global"?ie(e,t,n):o}function qn(e){return f(e,"SELECT session_id, interactions, updated_at FROM nudge_state ORDER BY updated_at DESC").map(t=>({session_id:String(t.session_id),interactions:Number(t.interactions),updated_at:String(t.updated_at)}))}function ie(e,t,n){let s=n==="global"?E(e,"SELECT COALESCE(SUM(interactions), 0) AS n FROM nudge_state"):E(e,"SELECT interactions AS n FROM nudge_state WHERE session_id = ?",t);return Number(s?.n??0)}function Vn(e){l(e,"DELETE FROM nudge_state"),l(e,"UPDATE cue_state SET pending = 0 WHERE id = 1");}var ae=3;function ce(e){let t=E(e,"SELECT pending, last_cue_at, last_skip_reason FROM cue_state WHERE id = 1");return {pending:Number(t?.pending??0)===1,last_cue_at:t?.last_cue_at??null,last_skip_reason:t?.last_skip_reason??null}}function ke(e){l(e,"INSERT INTO cue_state (id, pending, last_cue_at) VALUES (1, 1, ?) ON CONFLICT(id) DO UPDATE SET pending = 1, last_cue_at = excluded.last_cue_at",new Date().toISOString()),l(e,"DELETE FROM nudge_state");}function Jn(e,t){l(e,"INSERT INTO cue_state (id, pending, last_skip_reason) VALUES (1, 0, ?) ON CONFLICT(id) DO UPDATE SET pending = 0, last_skip_reason = excluded.last_skip_reason",t??null),l(e,"DELETE FROM nudge_state");}function ue(e){let t=E(e,"SELECT COUNT(*) AS n FROM knowledge");return {knowledge_ready:Number(t?.n??0)>0}}function Zn(e){let t={};for(let n of ["project","repository","branch","repository_platform"]){let s=E(e,`SELECT ${n} AS v, COUNT(*) AS c FROM lessons WHERE ${n} IS NOT NULL AND imported = 0 GROUP BY ${n} ORDER BY c DESC LIMIT 1`);t[n]=s?s.v:null;}return t}function ve(e){return W.parse({...e,prerequisites:JSON.parse(String(e.prerequisites??"[]"))})}function $t(e){return B.parse(e)}function Pt(e,t){l(e,"INSERT INTO courses (id, lesson_id, topic_id, title, goal, prerequisites, status, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",t.id,t.lesson_id,t.topic_id,t.title,t.goal,JSON.stringify(t.prerequisites),t.status,t.created_at,t.updated_at,t.completed_at);}function Xt(e,t){let n=E(e,"SELECT * FROM courses WHERE id = ?",t);return n?ve(n):null}function Ht(e,t={}){let n=[],s=[];t.status!=null&&(n.push("status = ?"),s.push(t.status)),t.lesson_id!=null&&(n.push("lesson_id = ?"),s.push(t.lesson_id));let o=`SELECT * FROM courses ${n.length?`WHERE ${n.join(" AND ")}`:""} ORDER BY updated_at DESC`;return f(e,o,...s).map(ve)}function jt(e,t){return f(e,"SELECT * FROM course_steps WHERE course_id = ? ORDER BY position",t).map($t)}function Qn(e,t,n){l(e,"UPDATE course_steps SET position = position + ? WHERE course_id = ? AND position >= ?",1e5,t,n),l(e,"UPDATE course_steps SET position = position - ? WHERE course_id = ? AND position >= ?",99999,t,1e5);}function Bt(e,t){l(e,"INSERT INTO course_steps (course_id, position, title, kind, anchor, status, done_at) VALUES (?, ?, ?, ?, ?, ?, ?)",t.course_id,t.position,t.title,t.kind,t.anchor,t.status,t.done_at);}function es(e,t,n,s,o){return l(e,"UPDATE course_steps SET status = ?, done_at = ? WHERE course_id = ? AND position = ?",s,o,t,n)>0}function ts(e,t,n,s){return l(e,"UPDATE courses SET status = ?, updated_at = ?, completed_at = CASE WHEN ? = 'completed' THEN ? ELSE NULL END WHERE id = ?",n,s,n,s,t)>0}function ns(e,t,n){l(e,"UPDATE courses SET updated_at = ? WHERE id = ?",n,t);}function ss(e,t){return l(e,"DELETE FROM course_steps WHERE course_id = ?",t),l(e,"DELETE FROM courses WHERE id = ?",t)>0}function os(e){return E(e,"SELECT 1 AS one FROM courses WHERE status = 'active' LIMIT 1")!==void 0}function rs(e){let t=w(e),n=Mt(e),s=oe(e),o=re(e),r=new Map;for(let p of o)for(let _ of p.topics)r.set(_,p.name);let i={groups:o.map(p=>p.name),topics:s.map(p=>({topic:p.topic,confidence:p.confidence,group:r.get(p.topic)??null}))},a={[K]:strToU8(JSON.stringify(t,null,2)),[G]:strToU8(JSON.stringify(n,null,2)),[Y]:strToU8(JSON.stringify(i,null,2))};existsSync(k)&&(a[z]=strToU8(readFileSync(k,"utf8")));let u=Ht(e);if(u.length){let p=u.flatMap(_=>jt(e,_.id));a[q]=strToU8(JSON.stringify({courses:u,steps:p},null,2));for(let _ of u){let g=join(ye,_.id,v);try{let h=lstatSync(g);h.isFile()&&h.size<=Ue&&(a[`courses/${_.id}/${v}`]=new Uint8Array(readFileSync(g)));}catch{}}}return zipSync(a)}var Ue=2*1024*1024;function Wt(e,t,n){if(!(K in t))return;let s=JSON.parse(strFromU8(t[K]));"max_per_day"in s&&y(e,"max_per_day",String(s.max_per_day)),"min_gap_minutes"in s&&y(e,"min_gap_minutes",String(s.min_gap_minutes)),(s.ui_theme==="system"||s.ui_theme==="dark"||s.ui_theme==="light")&&y(e,"ui_theme",s.ui_theme),(s.ui_home==="auto"||s.ui_home==="lessons"||s.ui_home==="knowledge")&&y(e,"ui_home",s.ui_home),"nudge_every"in s&&y(e,"nudge_every",String(s.nudge_every)),(s.nudge_scope==="session"||s.nudge_scope==="global")&&y(e,"nudge_scope",s.nudge_scope),typeof s.share_name=="string"&&y(e,"share_name",ht(s.share_name)),n.settings=1;}function Kt(e,t,n){if(!(Y in t))return;let s=JSON.parse(strFromU8(t[Y]));if(!(s&&typeof s=="object"&&Array.isArray(s.topics))){for(let[r,i]of Object.entries(s))U(e,r,i);n.topics=Object.keys(s).length;return}let o=0;for(let r of s.groups??[])Ee(e,r)&&(o+=1);for(let r of s.topics){U(e,r.topic,r.confidence);let i=r.group;i&&i!=="Other"&&(Ee(e,i)&&(o+=1),Ft(e,r.topic,i));}n.topics=s.topics.length,n.groups=o;}function Gt(e,t,n){if(!(G in t))return;let s=JSON.parse(strFromU8(t[G])),{inserted:o,duplicated:r,invalid:i}=se(e,s);n.lessons=o,n.skipped=r,n.invalid=i;}function Yt(e,t){z in e&&(mkdirSync(dirname(k),{recursive:true}),writeFileSync(k,strFromU8(e[z]),"utf8"),t.learning_state=1);}function zt(e,t,n){if(!(q in t))return;let s=JSON.parse(strFromU8(t[q])),o=new Set;for(let r of s.courses??[])try{let i=W.parse(r);Xt(e,i.id)||(Pt(e,i),n.courses+=1),o.add(i.id);}catch{n.invalid+=1;}for(let r of s.steps??[])try{let i=B.parse(r);if(!o.has(i.course_id))continue;E(e,"SELECT 1 AS one FROM course_steps WHERE course_id = ? AND position = ?",i.course_id,i.position)||Bt(e,i);}catch{n.invalid+=1;}for(let[r,i]of Object.entries(t)){let a=Et.exec(r)?.[1];if(!a||!o.has(a)||i.length>Ue)continue;let u=join(ye,a),p=join(u,v);existsSync(p)||(mkdirSync(u,{recursive:true}),writeFileSync(p,i));}}function is(e,t){let n={settings:0,topics:0,groups:0,lessons:0,skipped:0,invalid:0,learning_state:0,courses:0},s=unzipSync(t);return Wt(e,s,n),Kt(e,s,n),Gt(e,s,n),Yt(s,n),zt(e,s,n),n}function qt(e){let t=new Date,n;if(e==="today")n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,0,0));else if(e==="week")n=new Date(t.getTime()-7*864e5);else if(e==="month")n=new Date(t.getTime()-30*864e5);else if(e==="year")n=new Date(t.getTime()-365*864e5);else return null;return n.toISOString()}function le(e){let t=[];try{let n=JSON.parse(e.categories);Array.isArray(n)&&(t=n);}catch{t=[];}return R({...e,categories:t,starred:!!e.starred,imported:!!e.imported})}function Me(e){let t=[...e].length,n=Math.max(34-t-2,2),s=Math.floor(n/2);return `### ${"\u2500".repeat(s)} ${e} ${"\u2500".repeat(n-s)}`}function Fe(e){let t=e.level.charAt(0).toUpperCase()+e.level.slice(1),n=e.categories.join(" \xB7 ");return [Me("\u{1F393} devcoach"),`**${e.title}** \xB7 ${n} \xB7 ${t}`,"",e.body?.trim()||e.summary,"",Me(`${e.topic_id} \xB7 ${e.level}`)].join(`
105
+ `)}var P="devcoach.lesson",C=1,en=`devcoach:lesson:${C}:`,tn="https://ultimaphoenix.github.io/dev-coach/lesson",nn=".devcoach.md",sn=256*1024,m=class extends Error{},D=z$1.string().nullish(),on=["task_context","project","branch","commit_hash"],rn=new Set(["github","gitlab","bitbucket"]),Pe=z$1.object({format:z$1.literal(P),version:z$1.literal(C),lesson:z$1.object({title:z$1.string().min(1),summary:z$1.string(),body:z$1.string().nullable(),topic_id:z$1.string().min(1),categories:z$1.array(z$1.string()),level:X,task_context:D,project:D,repository:D,branch:D,commit_hash:D,repository_platform:H.nullish()}),origin:z$1.object({id:z$1.string().min(1),timestamp:z$1.string()}),shared_by:z$1.string().nullable(),shared_at:z$1.string(),app_version:z$1.string()});function gs(e,t){let n={title:e.title,summary:e.summary,body:e.body,topic_id:e.topic_id,categories:e.categories,level:e.level};if(t.includeContext){for(let s of on)e[s]!=null&&(n[s]=e[s]);e.repository_platform&&rn.has(e.repository_platform)&&(e.repository!=null&&(n.repository=e.repository),n.repository_platform=e.repository_platform);}return {format:P,version:C,lesson:n,origin:{id:e.id,timestamp:e.timestamp},shared_by:t.sharedBy,shared_at:j(t.now??new Date),app_version:b}}function fs(e){return e.anonymous?null:e.explicit!=null?e.explicit.trim()||null:e.setting?.trim()||e.gitUserName?.trim()||null}function Xe(e){let t=deflateSync(strToU8(JSON.stringify(e)),{level:9});return en+Buffer.from(t).toString("base64url")}var He=/devcoach:lesson:(\d+):([A-Za-z0-9_-]+)/,an=64e3,pe=512,$=class extends Error{};function cn(e,t){let n=[],s=0,o=new Inflate(a=>{if(s+=a.length,s>t)throw new $("too large");n.push(a);});for(let a=0;a<e.length;a+=pe)o.push(e.subarray(a,a+pe),a+pe>=e.length);let r=new Uint8Array(s),i=0;for(let a of n)r.set(a,i),i+=a.length;return r}function un(e){let t=new RegExp(`^${He.source}$`).exec(e.trim());if(!t)throw new m("That is not a devcoach lesson code.");if(Number(t[1])!==C)throw new m(`This lesson was shared by a newer devcoach (format ${t[1]}) \u2014 upgrade to import it.`);let n=t[2]??"";if(n.length>an)throw new m("This lesson code is too large to be a lesson.");let s;try{let o=cn(new Uint8Array(Buffer.from(n,"base64url")),sn);s=strFromU8(o);}catch(o){throw o instanceof $?new m("This lesson code is too large to be a lesson."):new m("This lesson code is damaged or incomplete \u2014 copy it again.")}return je(s)}function je(e){let t;try{t=JSON.parse(e);}catch{throw new m("This lesson code is damaged or incomplete \u2014 copy it again.")}let n=Pe.safeParse(t);if(!n.success)throw new m("This is not a valid devcoach lesson.");return n.data}function Es(e,t=Xe(e)){let n=e.shared_by?`Shared by ${e.shared_by} with devcoach`:"Shared with devcoach";return [Fe(e.lesson),"",`${n} \u2014 paste it to your agent or run: devcoach import`,t].join(`
106
+ `)}function _s(e,t=Xe(e)){return `${tn}#${t}`}function ln(e,t="lesson"){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||t}function hs(e){return `${ln(e.origin.id)}${nn}`}var pn=/^[A-Za-z0-9_.+:@/-]+$/,F=e=>pn.test(e)?e:JSON.stringify(e),dn=e=>`[${e.map(F).join(", ")}]`;function Ss(e){let t=e.lesson,n=["---",`format: ${P}`,`version: ${C}`,`title: ${JSON.stringify(t.title)}`,`topic_id: ${F(t.topic_id)}`,`level: ${t.level}`,`categories: ${dn(t.categories)}`,`summary: ${JSON.stringify(t.summary)}`,`origin_id: ${F(e.origin.id)}`,`origin_timestamp: ${e.origin.timestamp}`,`shared_by: ${e.shared_by==null?"null":JSON.stringify(e.shared_by)}`,`shared_at: ${e.shared_at}`,`app_version: ${F(e.app_version)}`];for(let s of ["task_context","project","repository","branch","commit_hash","repository_platform"]){let o=t[s];o!=null&&n.push(`${s}: ${JSON.stringify(o)}`);}return n.push("---","",t.body??t.summary,""),n.join(`
107
+ `)}function mn(e){let t=[],n="",s=false;for(let o=0;o<e.length;o++){let r=e[o]??"";s?(n+=r,r==="\\"?n+=e[++o]??"":r==='"'&&(s=false)):r==='"'?(s=true,n+=r):r===","?(t.push(n),n=""):n+=r;}return t.push(n),t}function Be(e){let t=e.trim();if(t==="null"||t==="")return null;if(t.startsWith('"'))return JSON.parse(t);if(t.startsWith("[")&&t.endsWith("]")){let n=t.slice(1,-1).trim();return n?mn(n).map(s=>Be(s)):[]}return t}function gn(e){let t=e.replace(/\r\n?/g,`
108
+ `).split(`
109
+ `);if(t[0]?.trim()!=="---")throw new m("Missing frontmatter (--- \u2026 ---).");let n=t.findIndex((a,u)=>u>0&&a.trim()==="---");if(n===-1)throw new m("Frontmatter never closes (missing ---).");let s={};for(let a of t.slice(1,n)){if(!a.trim()||a.trimStart().startsWith("#"))continue;let u=a.indexOf(":");if(u===-1)throw new m(`Cannot read frontmatter line: ${a.trim()}`);try{s[a.slice(0,u).trim()]=Be(a.slice(u+1));}catch{throw new m(`Cannot read frontmatter line: ${a.trim()}`)}}let o=t.slice(n+1).join(`
110
+ `).trim(),r={format:s.format,version:typeof s.version=="string"?Number(s.version):s.version,lesson:{title:s.title,summary:s.summary,body:o||null,topic_id:s.topic_id,categories:s.categories,level:s.level,task_context:s.task_context??void 0,project:s.project??void 0,repository:s.repository??void 0,branch:s.branch??void 0,commit_hash:s.commit_hash??void 0,repository_platform:s.repository_platform??void 0},origin:{id:s.origin_id,timestamp:s.origin_timestamp},shared_by:s.shared_by??null,shared_at:s.shared_at,app_version:s.app_version},i=Pe.safeParse(r);if(!i.success)throw new m("This file is not a valid devcoach lesson.");return i.data}function We(e){let t=e.trim();if(!t)throw new m("Nothing to import \u2014 paste a lesson code, link or file.");if(t.startsWith("[")){let o=$e(t);if(Array.isArray(o))return {kind:"lessons",records:o}}else if(t.startsWith("{")){let o=$e(t);if(o&&typeof o=="object")return o.format===P?{kind:"shared",source:"json",payload:je(t)}:{kind:"lessons",records:[o]}}else if(t.startsWith("---"))return {kind:"shared",source:"markdown",payload:gn(t)};let n=[...t.matchAll(new RegExp(He.source,"g"))];if(n.length===0)throw new m("Not a devcoach lesson: expected a devcoach:lesson code, a share link, a .devcoach.md file or a lessons JSON export.");let s;for(let o of n.reverse()){let r=[o[0]],i=fn(t.slice(o.index??0));i!==o[0]&&r.push(i);for(let a of r)try{return {kind:"shared",source:"code",payload:un(a)}}catch(u){s=u;}}throw s}function fn(e){let t=e.split(`
111
+ `).map(s=>s.trim()),n=t[0]??"";for(let s of t.slice(1)){if(!/^[A-Za-z0-9_-]+$/.test(s))break;n+=s;}return n}function $e(e){try{return JSON.parse(e)}catch{throw new m("This looks like JSON but does not parse \u2014 copy it again.")}}function Ke(e,t,n=new Date){let s=e.lesson;return R({id:t,timestamp:n,topic_id:s.topic_id,categories:s.categories,title:s.title,level:s.level,summary:s.summary,body:s.body,task_context:s.task_context??null,project:s.project??null,repository:s.repository??null,branch:s.branch??null,commit_hash:s.commit_hash??null,folder:null,repository_platform:s.repository_platform??null,starred:false,feedback:null,imported:true,shared_by:e.shared_by})}var En=50;function Ge(e,t=En){let n=e.origin.id,s=[n];for(let o=1;s.length<t;o++)s.push(o===1?`${n}-shared`:`${n}-shared-${o}`);return s}function Ye(e,t){return e.imported&&e.title===t.lesson.title&&e.topic_id===t.lesson.topic_id&&(e.shared_by??null)===(t.shared_by??null)}function ze(e){try{let t=w(e),n=new Date,s=new Date(n.getTime()-24*36e5).toISOString(),o=M(e,s);if(o>=t.max_per_day)return {allowed:!1,reason:`Daily limit reached (${o}/${t.max_per_day} lessons in the last 24h)`};let r=Ae(e);if(r!=null){let i=new Date(r),a=(n.getTime()-i.getTime())/6e4;if(a<t.min_gap_minutes){let u=t.min_gap_minutes-a,p=Math.floor(t.min_gap_minutes/60),_=t.min_gap_minutes%60,g=Math.trunc(u),h=Math.floor(g/60),A=g%60;return {allowed:!1,reason:`Too soon: last lesson ${a<0?`in ${Math.round(-a)}m (future timestamp)`:`${Math.round(a)}m ago`}, minimum interval is ${p}h ${_}m (${h}h ${A}m remaining)`}}}return {allowed:!0}}catch(t){return {allowed:true,reason:`Rate limit check failed: ${t}`}}}function Rs(e){try{return {knowledge:oe(e),groups:re(e)}}catch{return {knowledge:[],groups:[]}}}function _n(e,t,n){let s=x(e)[t]??5,o=Math.max(0,Math.min(10,s+n));return U(e,t,o),o}function Ls(e,t,n){return Re(e,()=>{let s=e.prepare("SELECT feedback, topic_id FROM lessons WHERE id = ?").get(t);if(!s)return null;let o=s.feedback??null,r=x(e);if(o===n)return {topic_id:s.topic_id,previous:o,delta:0,confidence:r[s.topic_id]??null};we(e,t,n);let i=(n==="know"?1:0)-(o==="know"?1:0),a=i!==0?_n(e,s.topic_id,i):r[s.topic_id]??null;return {topic_id:s.topic_id,previous:o,delta:i,confidence:a}})}function hn(e){try{let t=new Date,n=ne(e),s=new Date(t.getTime()-24*36e5).toISOString(),o=new Date(t.getTime()-7*864e5).toISOString(),r=M(e,s),i=M(e,o),a=x(e),u=Object.entries(a).sort((g,h)=>g[1]-h[1]),p=u.slice(0,5).map(([g,h])=>({topic:g,confidence:h})),_=u.slice(-5).reverse().map(([g,h])=>({topic:g,confidence:h}));return {total_lessons:n,lessons_today:r,lessons_this_week:i,imported_lessons:ne(e,{imported:!0}),weakest_topics:p,strongest_topics:_}}catch(t){return {error:String(t)}}}function Sn(e,t){let n=Object.hasOwn(x(e),t.lesson.topic_id);for(let s of Ge(t)){let o=De(e,s);if(o){if(Ye(o,t))return {kind:"shared",inserted:0,duplicated:1,invalid:0,lesson:o,topic_tracked:n};continue}let r=Ke(t,s);if(te(e,r))return {kind:"shared",inserted:1,duplicated:0,invalid:0,lesson:r,topic_tracked:n}}return {kind:"shared",inserted:0,duplicated:0,invalid:1,lesson:null,topic_tracked:n}}function Ns(e,t){let n=We(t);return n.kind==="lessons"?{kind:"lessons",...se(e,n.records),lesson:null,topic_tracked:null}:Sn(e,n.payload)}function Os(e){try{return Ce(e)}catch{return []}}function xs(e,t,n){let s=a=>({cue:false,reason:a,nextLessonNumber:0});if(n.planMode)return s("plan mode (not counted)");if(!ue(e).knowledge_ready)return s("onboarding not complete");let o=w(e),r="pacing disabled (nudge_every=0)";if(o.nudge_every>0){let a=Ie(e,t??"__nosession__",o.nudge_scope),{pending:u}=ce(e),p=u?Math.min(ae,o.nudge_every):o.nudge_every;if(r=`${a}/${p}${u?" (retry window)":""}`,a<p)return s(`paced (${r})`)}let i=ze(e);return i.allowed?(ke(e),{cue:true,reason:`cue (${r})`,nextLessonNumber:Number(hn(e).total_lessons??0)+1}):s(`rate limited: ${i.reason??"denied"}`)}function ws(e,t){try{let n=[],s=!0;if(!ue(e).knowledge_ready)return {wouldCue:!1,reasons:["onboarding not complete \u2014 no knowledge topics yet"]};let o=w(e);if(o.nudge_every>0){let i=ie(e,t??"__nosession__",o.nudge_scope)+1,{pending:a}=ce(e),u=a?Math.min(ae,o.nudge_every):o.nudge_every;i<u?(s=!1,n.push(`pacing: next stop would be ${i}/${u}${a?" (retry window)":""}`)):n.push(`pacing: next stop reaches the threshold (${i}/${u})`);}else n.push("pacing disabled (nudge_every=0) \u2014 every eligible stop cues");let r=ze(e);return r.allowed?n.push("rate limit: allowed"):(s=!1,n.push(`rate limited: ${r.reason??"denied"}`)),{wouldCue:s,reasons:n}}catch(n){return {wouldCue:false,reasons:[`check failed: ${n}`]}}}export{Pt as $,Fn as A,Ls as Aa,$n as B,hn as Ba,ne as C,Ns as Ca,Pn as D,Os as Da,Xn as E,xs as Ea,Hn as F,ws as Fa,jn as G,Mt as H,Bn as I,Wn as J,De as K,Kn as L,oe as M,U as N,Gn as O,Ee as P,Yn as Q,Ft as R,zn as S,w as T,y as U,qn as V,Vn as W,ce as X,Jn as Y,ue as Z,Zn as _,b as a,Xt as aa,X as b,Ht as ba,H as c,jt as ca,Ve as d,Qn as da,Nn as e,Bt as ea,st as f,es as fa,ot as g,ts as ga,rt as h,ns as ha,it as i,ss as ia,at as j,os as ja,ct as k,rs as ka,R as l,Ue as la,Q as m,is as ma,ee as n,m as na,k as o,gs as oa,ye as p,fs as pa,v as q,Xe as qa,Mn as r,un as ra,_t as s,Es as sa,ht as t,_s as ta,I as u,ln as ua,bt as v,hs as va,N as w,Ss as wa,be as x,ze as xa,Rt as y,Rs as ya,Re as z,_n as za};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import {p,q,la,$ as $$1,aa,ca,ba,z,da,ea,ha,fa,ga,ia,na,ua,a}from'./chunk-C3PYOEBP.js';import {lstatSync,mkdirSync,readFileSync,rmSync,existsSync}from'fs';import {join,sep,basename}from'path';import {execFileSync}from'child_process';import nt from'dns';import rt from'http';import ot from'https';import {isIP}from'net';var w=/^[a-z0-9-]+$/,X=q,h=class extends Error{};function Y(e){if(!w.test(e))throw new h(`Invalid course id '${e}'`)}function C(e){return Y(e),join(p,e)}function M(e){return join(C(e),X)}function J(e){let t=M(e);if(!t.startsWith(C(e)+sep))return null;try{let n=lstatSync(t);return !n.isFile()||n.size>la?null:t}catch{return null}}function Q(e,t){let n=ua(t,"course"),r=n;for(let o=2;aa(e,r)!==null||existsSync(join(p,r));o++)r=`${n}-${o}`;return r}function dt(e,t){let n=new Date().toISOString(),r={id:Q(e,t.title),lesson_id:t.lesson_id??null,topic_id:t.topic_id,title:t.title,goal:t.goal??null,prerequisites:t.prerequisites??[],status:"active",created_at:n,updated_at:n,completed_at:null};return $$1(e,r),mkdirSync(C(r.id),{recursive:true}),{...r,steps:[]}}function $(e,t){if(!w.test(t))return null;let n=aa(e,t);return n?{...n,steps:ca(e,t)}:null}function St(e,t={}){return ba(e,t).map(n=>({...n,steps:ca(e,n.id)}))}function wt(e,t,n){return z(e,()=>{let r=$(e,t);if(!r)throw new h(`Course '${t}' not found`);let o=r.steps.length,i=n.after??o;if(!Number.isInteger(i)||i<0||i>o)throw new h(`'after' must be between 0 and ${o} (the course has ${o} steps)`);let a=J(t);if(!a)throw new h(`Course '${t}' has no document yet \u2014 write ${M(t)} first`);let f=readFileSync(a,"utf8");if(!new RegExp(`\\sid=["']${n.anchor}["']`).test(f))throw new h(`No element with id="${n.anchor}" in ${a}`);if(r.steps.some(s=>s.anchor===n.anchor))throw new h(`Step anchor '${n.anchor}' is already registered`);let l={course_id:t,position:i+1,title:n.title,kind:n.kind,anchor:n.anchor,status:"todo",done_at:null};return i<o&&da(e,t,i+1),ea(e,l),ha(e,t,new Date().toISOString()),l})}function Ct(e,t,n,r){let o=new Date().toISOString();return z(e,()=>{if(!fa(e,t,n,r,r==="done"?o:null))return null;let a=ca(e,t),f=a.length>0&&a.every(s=>s.status!=="todo"),l=aa(e,t);return l&&f&&l.status==="active"?ga(e,t,"completed",o):l&&!f&&l.status==="completed"?ga(e,t,"active",o):ha(e,t,o),$(e,t)})}function yt(e,t,n){return w.test(t)&&ga(e,t,n,new Date().toISOString())?$(e,t):null}function bt(e,t){if(!w.test(t))return false;let n=ia(e,t);return rmSync(C(t),{recursive:true,force:true}),n}function xt(e){return {done:e.steps.filter(t=>t.status!=="todo").length,total:e.steps.length}}function y(...e){try{return execFileSync("git",e,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}var F={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function et(e){if(!e)return [null,null];let t=/^git@([^:]+):(.+?)(?:\.git)?$/.exec(e);if(t){let r=(t[1]??"").toLowerCase();return [t[2]??e,F[r]??"local"]}let n=/^https?:\/\/([^/]+)\/(.+?)(?:\.git)?$/.exec(e);if(n){let r=(n[1]??"").toLowerCase();return [n[2]??e,F[r]??"local"]}return [e,"local"]}function Dt(){return y("config","user.name")}function $t(){let e=process.cwd(),t=y("rev-parse","--abbrev-ref","HEAD"),n=y("rev-parse","HEAD"),r=y("remote","get-url","origin"),[o,i]=et(r),a;return o?a=o.replace(/\/+$/,"").split("/").pop()??null:a=basename(e)||null,t==="HEAD"&&(t=null),{project:a,repository:o,branch:t,commit_hash:n,folder:e,repository_platform:i}}var W="That URL is too large to be a lesson.",b="Only public http(s) URLs can be imported.",st=new Set([301,302,303,307,308]);function it(e){return /^https?:\/\/\S+$/i.test(e.trim())}function B(e){let[t=0,n=0]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===168||t===100&&n>=64&&n<=127||t>=224}function G(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"").toLowerCase();if(isIP(t)===4)return B(t);if(isIP(t)!==6)return true;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(t);if(n?.[1])return B(n[1]);if(t==="::"||t==="::1")return true;let r=t.split(":")[0]??"";return !!(/^f[cd]/.test(r)||/^fe[89ab]/.test(r))}async function at(e){return (await nt.promises.lookup(e,{all:true})).map(n=>n.address)}async function ut(e,t){let n=e.hostname.replace(/^\[|\]$/g,"").toLowerCase();if(n==="localhost"||n.endsWith(".localhost"))throw new na(b);if(isIP(n)){if(G(n))throw new na(b);return n}let r;try{r=await t(n);}catch{throw new na("The URL could not be reached \u2014 copy the lesson text instead.")}let o=r[0];if(!o||r.some(i=>G(i)))throw new na(b);return o}var lt=(e,t,n)=>new Promise((r,o)=>{let i=isIP(t)===6?6:4,a$1=(s,c,m)=>{c.all?m(null,[{address:t,family:i}]):m(null,t,i);},l=(e.protocol==="https:"?ot:rt).request(e,{method:"GET",lookup:a$1,signal:n,headers:{accept:"text/plain, text/markdown, application/json;q=0.9, */*;q=0.5","user-agent":`devcoach/${a}`}},s=>{let c=s.headers["content-length"];r({status:s.statusCode??0,location:s.headers.location??null,contentLength:c===void 0?null:Number(c),body:s,abort:()=>s.destroy()});});l.on("error",o),l.end();});async function ct(e,t){if(e.contentLength!==null&&e.contentLength>t)throw e.abort(),new na(W);let n=[],r=0;for await(let o of e.body){if(r+=o.byteLength,r>t)throw e.abort(),new na(W);n.push(o);}return Buffer.concat(n).toString("utf8")}async function kt(e,t={}){let n=t.timeoutMs??5e3,r=t.maxBytes??256*1024,o=t.maxRedirects??3,i=t.lookup??at,a=t.transport??lt;if(!it(e))throw new na("Only http(s) URLs can be imported.");let f=new AbortController,l=setTimeout(()=>f.abort(),n);try{let s=new URL(e.trim());for(let c=0;;c++){let m=await ut(s,i),p=await a(s,m,f.signal);if(st.has(p.status)){if(p.abort(),!p.location||c>=o)throw new na("The URL redirects too many times \u2014 copy the lesson text instead.");if(s=new URL(p.location,s),!/^https?:$/.test(s.protocol))throw new na(b);continue}if(p.status<200||p.status>=300)throw p.abort(),new na(`The URL answered ${p.status} \u2014 nothing to import there.`);return await ct(p,r)}}catch(s){if(s instanceof na)throw s;let c=s?.name==="AbortError"?"timed out":"could not be reached";throw new na(`The URL ${c} \u2014 copy the lesson text instead.`)}finally{clearTimeout(l);}}export{w as a,h as b,C as c,M as d,J as e,dt as f,$ as g,St as h,wt as i,Ct as j,yt as k,bt as l,xt as m,Dt as n,$t as o,it as p,kt as q};
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import {n,A,x,Z,ja,Fa,m,z,Ea}from'./chunk-C3PYOEBP.js';import {existsSync,mkdirSync,statSync,writeFileSync,appendFileSync,fstatSync,readFileSync}from'fs';import {join}from'path';function N(e){try{let o=JSON.parse(e);return {stop_hook_active:o?.stop_hook_active===!0,permission_mode:typeof o?.permission_mode=="string"?o.permission_mode:null,session_id:typeof o?.session_id=="string"?o.session_id:null}}catch{return {stop_hook_active:false,permission_mode:null,session_id:null}}}function l(){let e={stop_hook_active:false,permission_mode:null,session_id:null};try{let o=fstatSync(0);return !o.isFIFO()&&!o.isFile()&&!o.isSocket()?e:N(readFileSync(0,"utf8"))}catch{return e}}function $(e){return e.stop_hook_active||e.permission_mode==="plan"}function s(e,o,t){if(process.env.DEVCOACH_HOOK_DEBUG==="1")try{mkdirSync(m,{recursive:!0});let n=join(m,"hook.log");existsSync(n)&&statSync(n).size>256*1024&&writeFileSync(n,""),appendFileSync(n,`${new Date().toISOString()} ${e} ${(o??"-").slice(0,8)} ${t}
3
+ `);}catch{}}var E={claude:"block",gemini:"deny",codex:"block"};function u(e,o,t){let n={decision:E[e],reason:o};t&&(n.systemMessage=t),process.stdout.write(`${JSON.stringify(n)}
4
+ `),process.exit(0);}var g="devcoach: the user has no coaching profile yet. Ask them how they want to set it up and STRONGLY recommend Automatic \u2014 devcoach scans their full Claude Code history across all their projects (call get_onboarding for the detected stack and per-project evidence) so the profile reflects what they actually build. Also offer Guided (a short conversation to map topics and confidence levels) and Import (restore from a backup), but lead with Automatic; do not pick for them. After they choose, build the profile and save it by calling the devcoach `complete_onboarding` MCP tool (not a shell command) before ending your turn.";function I(e=l()){if($(e)&&process.exit(0),existsSync(n)){let o;try{o=A(t=>x(t)!==null||Z(t).knowledge_ready);}catch(t){s("onboard-hook",e.session_id,`error: ${t}`),process.exit(0);}o&&process.exit(0);}s("onboard-hook",e.session_id,"onboarding cue"),u("claude",g);}var a=10,w={claude:{cue:"Invoke the `devcoach` skill (Skill tool)",prime:"invoke the `devcoach` skill (Skill tool)"},gemini:{cue:"Activate the `devcoach` skill (activate_skill tool)",prime:"activate the `devcoach` skill (activate_skill tool)"},codex:{cue:"Activate the `devcoach` skill",prime:"activate the `devcoach` skill"}};function T(e,o="claude"){let t=e%a===0,n=Math.ceil(e/a)*a,i=t?`This is lesson #${e} \u2014 a notebook checkpoint (every ${a} lessons): after log_lesson returns the feedback, also read references/calibration.md in the devcoach skill and run its notebook-update step (a direct file write), recording "(updated after ${e} lessons)".`:`Skip the notebook update this time \u2014 it is refreshed only every ${a} lessons (next checkpoint at lesson #${n}).`;return `devcoach: a lesson is due for the technical work just completed. Do it now \u2014 do not acknowledge this message and do not explain what you are about to do.
5
+
6
+ ${w[o].cue} NOW and follow it exactly \u2014 the skill is the single source of truth for the entire flow, including the explicit no-op when the completed work does not warrant a lesson.
7
+ ${i}
8
+
9
+ If the devcoach skill is not available, fall back to: call get_briefing (one call: profile, taught topics, notebook); pick ONE untaught profile topic at or above the user's confidence band; call log_lesson silently (body = 3\u20136 short paragraphs tied to the task plus a \`\u{1F4A1} *Senior tip:*\` line, clean markdown without bands or a title line); THEN write the card as the FINAL message of the turn: plain markdown (no '>' blockquote) between two band headings \`### \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u{1F393} devcoach \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\` and \`### \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [topic] \xB7 [level] \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\`, with \`**[Title]** \xB7 [Category] \xB7 [Level]\`, the body you passed, and the tip \u2014 saving is not showing; the card in the final message is the only thing the user sees. If instead the work does not warrant a lesson (pure questions, chat, nothing technical), call the devcoach \`skip_lesson\` tool with a one-line reason.
10
+
11
+ The rate-limit check is already done by this hook \u2014 skip it. Work in silence: never narrate devcoach tool calls or resource reads ('checking your profile\u2026'). Output only the lesson card (or nothing). No preamble, no meta-commentary.`}function R(e,o,t){let n=o.permission_mode==="plan";if(o.stop_hook_active)return {kind:"silent",note:"hook-forced continuation"};if(x(e))return {kind:"silent",note:"read-only: database newer than this build"};if(!Z(e).knowledge_ready)return !t.onboardCue||n?{kind:"silent",note:"onboarding not complete"}:{kind:"onboard",note:"onboarding cue (empty knowledge)"};if(ja(e))return {kind:"silent",note:"course in progress \u2014 cues paused"};let i=Ea(e,o.session_id,{planMode:n});return i.cue?{kind:"cue",nextLessonNumber:i.nextLessonNumber,note:i.reason}:{kind:"silent",note:i.reason}}function C(e,o,t){let n;try{n=A(i=>z(i,()=>R(i,o,t)));}catch(i){s(e,o.session_id,`error: ${i}`),process.exit(0);}switch(s(e,o.session_id,n.note),n.kind){case "onboard":u(t.client,g);break;case "cue":u(t.client,T(n.nextLessonNumber,t.client),"\u{1F393} devcoach: checking whether a lesson is due\u2026");break;}process.exit(0);}function B(e=l()){existsSync(n)||process.exit(0),C("lesson-ready",e,{onboardCue:false,client:"claude"});}function f(e=l(),o="claude"){let t=o==="claude"?"stop-hook":`${o}-stop-hook`;existsSync(n)||((e.stop_hook_active||e.permission_mode==="plan")&&process.exit(0),s(t,e.session_id,"onboarding cue (no DB)"),u(o,g)),C(t,e,{onboardCue:true,client:o});}function L(e="claude"){return `devcoach: the lesson pacing threshold will be reached at the end of this turn. Resolve it before finishing:
12
+ - If this task is technical: ${w[e].prime} and follow it exactly to close your reply \u2014 the skill is the single source of truth for the entire lesson flow.
13
+ - If it is not technical: silently call the devcoach \`skip_lesson\` tool with a one-line reason and output nothing about it.
14
+ - Either way, work in silence: never narrate devcoach tool calls or resource reads ('checking your profile\u2026').`}var F={claude:"UserPromptSubmit",gemini:"BeforeAgent",codex:"UserPromptSubmit"};function b(e=l(),o="claude"){let t=o==="claude"?"prompt-hook":`${o}-prompt-hook`;e.permission_mode==="plan"&&process.exit(0),existsSync(n)||process.exit(0);let n$1;try{n$1=A(i=>x(i)===null&&!ja(i)&&Fa(i,e.session_id).wouldCue);}catch(i){s(t,e.session_id,`error: ${i}`),process.exit(0);}s(t,e.session_id,n$1?"priming":"no prime"),n$1||process.exit(0),process.stdout.write(`${JSON.stringify({hookSpecificOutput:{hookEventName:F[o],additionalContext:L(o)}})}
15
+ `),process.exit(0);}function K(e,o){let t=()=>o??l();switch(e){case "stop-hook":f(t());break;case "gemini-stop-hook":f(t(),"gemini");break;case "codex-stop-hook":f(t(),"codex");break;case "prompt-hook":b(t());break;case "gemini-prompt-hook":b(t(),"gemini");break;case "codex-prompt-hook":b(t(),"codex");break;case "onboard-hook":I(t());break;case "lesson-ready":B(t());break;default:process.exit(0);}}export{N as a,I as b,T as c,B as d,f as e,L as f,b as g,K as h};
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import {e,g,b,d as d$1}from'./chunk-RGZN7AZO.js';export{c as buildLessonCue,d as cmdLessonReady,b as cmdOnboardHook,g as cmdPromptHook,e as cmdStopHook,a as parseHookPayload}from'./chunk-RGZN7AZO.js';import {a as a$1,d as d$2,e as e$1,g as g$2,b as b$2,f}from'./chunk-QU6UQJWC.js';import {c,b as b$1,a as a$2,e as e$3,f as f$1}from'./chunk-MRABMPXO.js';import {h,m,g as g$1,e as e$2,d as d$3,n,o as o$1,p,q as q$1}from'./chunk-MKH6XAM4.js';import {a,A,x as x$1,ya,D,K,G,E,Aa,T as T$1,pa,U,t,oa,va,wa,ta,sa,qa,Ca,na,xa,Ba,s,N as N$1,R,O,P,Q as Q$1,S as S$1,ka,M,H as H$1,o,ma,m as m$1,n as n$1,v,y,u,Z as Z$1,V,X as X$1,Fa}from'./chunk-C3PYOEBP.js';import {spawn,spawnSync,execFileSync}from'child_process';import {writeFileSync,existsSync,readFileSync,rmSync,mkdirSync,accessSync,constants}from'fs';import {createInterface}from'readline/promises';import {text}from'stream/consumers';import {Command}from'commander';import {homedir,platform}from'os';import {join,dirname}from'path';var d=(e="")=>{console.log(e);};function _o(){let e=platform();if(e==="darwin")return join(homedir(),"Library","Application Support","Claude","claude_desktop_config.json");if(e==="win32"){let t=process.env.APPDATA??join(homedir(),"AppData","Roaming");return join(t,"Claude","claude_desktop_config.json")}let o=process.env.XDG_CONFIG_HOME??join(homedir(),".config");return join(o,"Claude","claude_desktop_config.json")}var I=join(homedir(),".claude","settings.json"),q=join(homedir(),".claude","skills","devcoach"),ke=join(homedir(),".gemini"),x=join(ke,"settings.json"),Jo=join(ke,"extensions","devcoach","gemini-extension.json"),$e=join(homedir(),".codex"),H=join($e,"hooks.json"),X=join($e,"config.toml"),N=join(homedir(),".agents","skills","devcoach");function xo(e){for(let o of (process.env.PATH??"").split(":"))if(o)try{return accessSync(join(o,e),constants.X_OK),join(o,e)}catch{}return null}var Z=e=>xo(e)!==null;function Io(){return Z("devcoach")?{command:"devcoach",args:["mcp"]}:{command:"npx",args:["-y","devcoach","mcp"]}}function ye(){let e=xo("devcoach");return e?e.includes("fnm_multishells")?"devcoach":e:"npx -y devcoach"}function vo(e,o,t){if(!Z(e))return "";t&&spawnSync(e,t,{encoding:"utf8"});let s=spawnSync(e,o,{encoding:"utf8"});return s.status===0?`${a$1.green("\u2713")} Registered via \`${e} mcp add\``:`${s.stderr??""}${s.stdout??""}`.toLowerCase().includes("already")?`${a$1.yellow("Already registered")} in ${e} (use --force to overwrite)`:`${a$1.red(`${e} mcp add failed:`)} ${(s.stderr||s.stdout||"").trim()}`}function Wo(e,o){if(!Z("claude"))return "";o&&spawnSync("claude",["mcp","remove","--scope",e,"devcoach"],{encoding:"utf8"});let t=Io(),s=spawnSync("claude",["mcp","add","--scope",e,"devcoach",t.command,"--",...t.args],{encoding:"utf8"});return s.status===0?`${a$1.green("\u2713")} Registered via \`claude mcp add\` (scope: ${e})`:`${s.stderr??""}${s.stdout??""}`.toLowerCase().includes("already")?`${a$1.yellow("Already registered")} in Claude Code (use --force to overwrite)`:`${a$1.red("claude mcp add failed:")} ${(s.stderr||s.stdout||"").trim()}`}function C(e){if(!existsSync(e))return {ok:true,data:{}};try{return {ok:!0,data:JSON.parse(readFileSync(e,"utf8"))??{}}}catch{return {ok:false,error:`${a$1.red("\u2717")} ${e} is not valid JSON \u2014 fix it and re-run (left unchanged)`}}}function ue(e,o,t){let s=C(e);if(!s.ok)return s.error;let r=s.data;r.mcpServers??={};let a=r.mcpServers;return a.devcoach&&!t?`${a$1.yellow("Already registered")} in ${e} (use --force to overwrite)`:(a.devcoach=o,mkdirSync(dirname(e),{recursive:true}),writeFileSync(e,`${JSON.stringify(r,null,2)}
3
+ `),`${a$1.green("\u2713")} Installed into ${e}`)}function Yo(){let e=ye();return {Stop:{hooks:[{type:"command",command:`${e} stop-hook`,timeout:60}]},UserPromptSubmit:{hooks:[{type:"command",command:`${e} prompt-hook`,timeout:30}]}}}function Xo(){let e=ye();return {AfterAgent:{hooks:[{type:"command",command:`${e} gemini-stop-hook`,timeout:6e4}]},BeforeAgent:{hooks:[{type:"command",command:`${e} gemini-prompt-hook`,timeout:3e4}]}}}function qo(){let e=ye();return {Stop:{hooks:[{type:"command",command:`${e} codex-stop-hook`,timeout:60}]},UserPromptSubmit:{hooks:[{type:"command",command:`${e} codex-prompt-hook`,timeout:30}]}}}function Lo(e){return Object.entries(e.enabledPlugins??{}).filter(([o,t])=>t&&o.startsWith("devcoach@")).map(([o])=>o)}function ve(e){return Lo(e).length>0}function Q(){return existsSync(Jo)}function ee(e){return /dev-?coach/i.test(e)&&/\b(?:stop-hook|prompt-hook|onboard-hook|lesson-ready)\b/.test(e)}function we(e,o){let t=C(e);if(!t.ok)return t.error;let s=t.data;s.hooks??={};let r=s.hooks,a=false;for(let[c,l]of Object.entries(o)){r[c]??=[];let u=r[c],f=u.map((m,p)=>[m,p]).filter(([m])=>(m.hooks??[]).some(p=>ee(p.command??""))).map(([,m])=>m),[g]=f;if(!(f.length===1&&g!==void 0&&JSON.stringify(u[g])===JSON.stringify(l))){for(let m of f.toReversed())u.splice(m,1);u.push(l),a=true;}}return a?(mkdirSync(dirname(e),{recursive:true}),writeFileSync(e,`${JSON.stringify(s,null,2)}
4
+ `),`${a$1.green("\u2713")} Hooks installed into ${e} (${Object.keys(o).join(" + ")})`):`${a$1.yellow("Already installed")} in ${e} (current layout)`}function Zo(){let e=C(I);return e.ok?ve(e.data)?`${a$1.yellow("Skipped")} \u2014 the devcoach plugin already provides the hooks (installing both would double-count interactions)`:we(I,Yo()):e.error}function Qo(){return Q()?`${a$1.yellow("Skipped")} \u2014 the devcoach Gemini extension already provides the hooks (installing both would double-count interactions)`:we(x,Xo())}function B(e){if(!existsSync(join(e,"SKILL.md")))return "missing";try{if(readFileSync(join(e,".devcoach-version"),"utf8").trim()===a)return "current"}catch{}return "outdated"}function he(e,o){if(!o&&B(e)==="current")return `${a$1.yellow("Already installed")} in ${e} (current version)`;mkdirSync(e,{recursive:true}),writeFileSync(join(e,"SKILL.md"),e$3());let t=f$1();if(t.length){let s=join(e,"references");mkdirSync(s,{recursive:true});for(let r of t)writeFileSync(join(s,r.name),r.content);}return writeFileSync(join(e,".devcoach-version"),`${a}
5
+ `),`${a$1.green("\u2713")} Installed into ${e}`}function en(e){return Q()?`${a$1.yellow("Skipped")} \u2014 bundled with the devcoach Gemini extension`:he(N,e)}function T(e,o){let t=C(e);return t.ok&&(t.data.hooks?.[o]??[]).some(s=>(s.hooks??[]).some(r=>ee(r.command??"")))}function Ce(){let e=[{name:"Claude Code",dir:q,cmd:"devcoach install",hooked:()=>T(I,"Stop")},{name:"Gemini/Codex",dir:N,cmd:"devcoach install --gemini (or --codex)",hooked:()=>T(x,"AfterAgent")||T(H,"Stop")}];for(let o of e){let t=B(o.dir);if(t==="outdated")return `${a$1.yellow("\u2192")} The devcoach ${o.name} skill is out of date \u2014 run ${a$1.bold(o.cmd)} to refresh it.`;if(t==="missing"&&o.hooked())return `${a$1.yellow("\u2192")} The devcoach ${o.name} skill is not installed \u2014 run ${a$1.bold(o.cmd)} to add it.`}return ""}function Do(e){let o=e.claudeCode||e.claudeDesktop||e.gemini||e.codex,t=e.claudeCode||!o,s=e.claudeDesktop||!o,r=Io(),a=false;if(d(a$1.bold("Setting up devcoach")+a$1.dim(` (${r.command} ${r.args.join(" ")})`)),d(),t){d(a$1.bold("Claude Code"));let c=Wo("user",e.force);if(!c){let l=join(homedir(),".claude.json");c=ue(l,{type:"stdio",env:{},...r},e.force),a=true;}d(` MCP server\u2026 ${c}`),e.skipHook||d(` Hooks\u2026 ${Zo()}`),d(` Skill\u2026 ${he(q,e.force)}`),d();}if(s&&(d(a$1.bold("Claude Desktop")),d(` MCP server\u2026 ${ue(_o(),r,e.force)}`),a=true,d()),e.gemini){d(a$1.bold("Gemini CLI (beta)"));let c=vo("gemini",["mcp","add","-s","user","devcoach",r.command,...r.args],e.force?["mcp","remove","-s","user","devcoach"]:null);c||(c=ue(x,r,e.force)),d(` MCP server\u2026 ${c}`),e.skipHook||d(` Hooks\u2026 ${Qo()}`),d(` Skill\u2026 ${en(e.force)}`),d();}if(e.codex){d(a$1.bold("Codex CLI (beta)"));let c=vo("codex",["mcp","add","devcoach","--",r.command,...r.args],e.force?["mcp","remove","devcoach"]:null);c||(c=`${a$1.yellow("Manual step")} \u2014 codex CLI not found. Add to ${X}:
6
+ [mcp_servers.devcoach]
7
+ command = "${r.command}"
8
+ args = [${r.args.map(l=>`"${l}"`).join(", ")}]`),d(` MCP server\u2026 ${c}`),e.skipHook||d(` Hooks\u2026 ${we(H,qo())}`),d(` Skill\u2026 ${he(N,e.force)}`),d(` ${a$1.yellow("\u2192")} Codex asks once to trust new hooks \u2014 approve devcoach on the next run.`),d();}a&&d(`${a$1.yellow("\u2192")} Restart Claude Desktop to pick up the new server.
9
+ `),d(a$1.dim(`Tip: run devcoach backup to export your profile, lessons and settings.
10
+ run devcoach restore <file> to import a backup on a new machine.
11
+ After upgrading devcoach (npm, Homebrew), re-run devcoach install to refresh the skill.`));}function Se(e){let o=[];for(let[t,s]of Object.entries(e.hooks??{}))for(let r of s??[])for(let a of r.hooks??[])ee(a.command??"")&&o.push({event:t,cmd:a});return o}function _e(e,o,t){for(let{cmd:s}of o){let r=s.command.split(" ")[0]??"";r.startsWith("/")&&!existsSync(r)&&e.bad(`hook command not found: ${r} \u2014 re-run ${a$1.bold(t)}`),s.command.startsWith("npx ")&&e.warn("hook runs via npx \u2014 needs the npx cache (or network) on every stop"),s.timeout==null&&e.warn(`hook entry has no timeout (${s.command})`);}}function on(e){d(a$1.bold(`
12
+ Gemini CLI wiring (beta)`));let o=C(x),t=Q();if(!o.ok){e.bad(`${x} is not valid JSON \u2014 hooks cannot run`);return}let s=Se(o.data);t&&s.length?e.bad("devcoach hooks are registered TWICE (extension + settings.json) \u2014 interactions are double-counted. Uninstall the extension or remove the settings.json entries."):t?e.ok("hooks provided by the devcoach Gemini extension"):s.length?(s.some(a=>a.event==="AfterAgent")?e.ok("AfterAgent stop hook wired"):e.warn(`no AfterAgent stop hook \u2014 run ${a$1.bold("devcoach install --gemini")}`),s.some(a=>a.event==="BeforeAgent")?e.ok("BeforeAgent priming hook wired"):e.warn(`no BeforeAgent priming hook \u2014 run ${a$1.bold("devcoach install --gemini")} (lessons land more reliably)`),_e(e,s,"devcoach install --gemini")):e.warn(`no devcoach hooks in ${x} \u2014 run ${a$1.bold("devcoach install --gemini")}`);let r=B(N);t?e.ok("skill bundled with the devcoach Gemini extension"):r==="current"?e.ok("skill installed (~/.agents/skills, current version)"):r==="outdated"?e.warn(`skill is out of date \u2014 run ${a$1.bold("devcoach install --gemini")}`):e.warn(`skill not installed \u2014 run ${a$1.bold("devcoach install --gemini")}`),o.data.mcpServers?.devcoach?e.ok("MCP server registered (settings.json)"):e.warn(`MCP server not found in settings.json \u2014 it may be registered elsewhere (check with ${a$1.bold("gemini mcp list")})`);}function nn(e){d(a$1.bold(`
13
+ Codex CLI wiring (beta)`));let o=C(H);if(!o.ok){e.bad(`${H} is not valid JSON \u2014 hooks cannot run`);return}let t=Se(o.data);t.length?(t.some(a=>a.event==="Stop")?e.ok("Stop hook wired"):e.warn(`no Stop hook \u2014 run ${a$1.bold("devcoach install --codex")}`),t.some(a=>a.event==="UserPromptSubmit")?e.ok("UserPromptSubmit priming hook wired"):e.warn(`no UserPromptSubmit priming hook \u2014 run ${a$1.bold("devcoach install --codex")} (lessons land more reliably)`),_e(e,t,"devcoach install --codex"),e.warn("Codex runs hooks only after you trust them once \u2014 check the prompt on the next run")):e.warn(`no devcoach hooks in ${H} \u2014 run ${a$1.bold("devcoach install --codex")}`);let s=B(N);s==="current"?e.ok("skill installed (~/.agents/skills, current version)"):s==="outdated"?e.warn(`skill is out of date \u2014 run ${a$1.bold("devcoach install --codex")}`):e.warn(`skill not installed \u2014 run ${a$1.bold("devcoach install --codex")}`);let r=existsSync(X)?readFileSync(X,"utf8"):"";/\[mcp_servers\.devcoach\]/.test(r)?e.ok("MCP server registered (config.toml)"):e.warn(`MCP server not found in config.toml \u2014 it may be registered elsewhere (check with ${a$1.bold("codex mcp list")})`);}function Oo(){let e={ok:c=>d(` ${a$1.green("\u2713")} ${c}`),warn:c=>d(` ${a$1.yellow("\u2192")} ${c}`),bad:c=>d(` ${a$1.red("\u2717")} ${c}`)},{ok:o,warn:t,bad:s}=e;d(`
14
+ ${a$1.bold("devcoach doctor")} ${a$1.dim(`v${a}`)}
15
+ `),d(a$1.bold("Environment")),Number.parseInt(process.versions.node.split(".")[0]??"0",10)>=24?o(`Node ${process.versions.node} (\u2265 24)`):s(`Node ${process.versions.node} \u2014 devcoach needs Node \u2265 24 (embedded node:sqlite)`),d(a$1.bold(`
16
+ Claude Code wiring`));let a$2=C(I);if(!a$2.ok)s(`${I} is not valid JSON \u2014 hooks cannot run`);else {let c=ve(a$2.data),l=Se(a$2.data),u=Lo(a$2.data);if(u.length>1&&s(`${u.length} devcoach plugins enabled (${u.join(", ")}) \u2014 their hooks fire twice and interactions are double-counted. Keep one enabled (/plugin).`),c&&l.length)s("devcoach hooks are registered TWICE (plugin + settings.json) \u2014 interactions are double-counted. Disable the plugin or remove the settings.json entries.");else if(c)o("hooks provided by the devcoach plugin");else if(!l.length)s(`no devcoach hooks in ${I} \u2014 run ${a$1.bold("devcoach install")}`);else {let m=l.filter(({cmd:k})=>k.command.includes("onboard-hook")||k.command.includes("lesson-ready")),p=l.filter(k=>k.event==="Stop").length;m.length?t(`legacy two-entry Stop layout \u2014 run ${a$1.bold("devcoach install")} to merge into one stop-hook entry (fewer spawns per stop)`):p>1?t(`${p} devcoach Stop entries \u2014 interactions are counted ${p}\xD7 per stop; run ${a$1.bold("devcoach install")} to keep only the current one`):o(`Stop hook wired (${p} entry)`),l.some(k=>k.event==="UserPromptSubmit")?o("UserPromptSubmit priming hook wired"):t(`no UserPromptSubmit priming hook \u2014 run ${a$1.bold("devcoach install")} to add it (lessons land more reliably)`),_e(e,l,"devcoach install");}let f=B(q);f==="current"?o("Claude Code skill installed (current version)"):c?o("Claude Code skill bundled with the plugin"):t(f==="outdated"?`Claude Code skill is out of date \u2014 run ${a$1.bold("devcoach install")}`:`Claude Code skill not installed \u2014 run ${a$1.bold("devcoach install")}`);let g=C(join(homedir(),".claude.json"));g.ok&&g.data.mcpServers?.devcoach?o("MCP server registered (user scope)"):t(`MCP server not found in ~/.claude.json \u2014 it may be registered elsewhere (check with ${a$1.bold("claude mcp get devcoach")})`);}if(existsSync(ke)&&on(e),existsSync($e)&&nn(e),d(a$1.bold(`
17
+ Database & pacing`)),!existsSync(n$1)){t(`no database yet (${n$1}) \u2014 onboarding runs on the first technical task`),d();return}try{A(c=>{o(`database opens (${n$1})`);let l=x$1(c);if(l)s(v(l)),d(" this build is READ-ONLY on it: hooks cannot count interactions, lessons cannot be saved \u2014 update this install (brew upgrade devcoach / npm, or the plugin) or run the newer channel");else {let $=y(c);o(`schema v${u}`+($.upgradedBy?`, last upgraded by devcoach ${$.upgradedBy}`:""));}Z$1(c).knowledge_ready?o("onboarding complete"):t("onboarding not complete \u2014 the next stop cues it");let u$1=T$1(c);d(` settings: max_per_day=${u$1.max_per_day} \xB7 min_gap_minutes=${u$1.min_gap_minutes} \xB7 nudge_every=${u$1.nudge_every} \xB7 nudge_scope=${u$1.nudge_scope}`);let f=V(c),g=f.reduce(($,A)=>$+A.interactions,0);d(` pacing: ${f.length} session(s) counted, ${g} interaction(s) total`+(f[0]?` \u2014 latest ${f[0].session_id.slice(0,8)}\u2026 at ${f[0].interactions}`:""));let m=X$1(c);m.pending?t(`a cue is pending since ${m.last_cue_at} (retry threshold armed)`):m.last_skip_reason&&d(` last skip: "${m.last_skip_reason}"`);let p=xa(c);p.allowed?o("rate limit: allowed"):t(`rate limit: ${p.reason}`),d(a$1.bold(`
18
+ Verdict`));let k=Fa(c,f[0]?.session_id??null);k.wouldCue?o("the next eligible stop WOULD cue a lesson"):t("the next eligible stop would NOT cue a lesson:");for(let $ of k.reasons)d(` \xB7 ${$}`);});}catch(c){s(`database check failed: ${c}`);}d();}function pe(e){if(!existsSync(e))return `${a$1.yellow("Not registered")} (${e} does not exist)`;let o=C(e);if(!o.ok)return o.error;let t=o.data.mcpServers;return t?.devcoach?(delete t.devcoach,writeFileSync(e,`${JSON.stringify(o.data,null,2)}
19
+ `),`${a$1.green("\u2713")} Removed from ${e}`):`${a$1.yellow("Not registered")} in ${e}`}function ge(e,o){if(!Z(e))return "";let t=spawnSync(e,o,{encoding:"utf8"}),s=`${t.stderr??""}${t.stdout??""}`.toLowerCase();return t.status===0?`${a$1.green("\u2713")} Removed via \`${e} mcp remove\``:/not found|no .*server|does not exist|no such/.test(s)?`${a$1.yellow("Not registered")} in ${e}`:`${a$1.red(`${e} mcp remove failed:`)} ${(t.stderr||t.stdout||"").trim()}`}function fe(e){if(!existsSync(e))return `${a$1.yellow("No hooks")} (${e} does not exist)`;let o=C(e);if(!o.ok)return o.error;let t=o.data.hooks??{},s=[];for(let[r,a]of Object.entries(t)){if(!a)continue;let c=a.filter(l=>!(l.hooks??[]).some(u=>ee(u.command??"")));c.length!==a.length&&(s.push(r),c.length?t[r]=c:delete t[r]);}return s.length===0?`${a$1.yellow("No devcoach hooks")} in ${e}`:(Object.keys(t).length===0&&delete o.data.hooks,writeFileSync(e,`${JSON.stringify(o.data,null,2)}
20
+ `),`${a$1.green("\u2713")} Hooks removed from ${e} (${s.join(" + ")})`)}function wo(e){return existsSync(join(e,"SKILL.md"))?(rmSync(e,{recursive:true,force:true}),`${a$1.green("\u2713")} Removed ${e}`):`${a$1.yellow("Not installed")} (${e})`}async function tn(e){if(e)return true;if(!process.stdin.isTTY)return d(`${a$1.yellow("\u2192")} Not a terminal \u2014 pass --yes to delete ${m$1} without a prompt.`),false;let o=createInterface({input:process.stdin,output:process.stdout});try{let t=await o.question(`Delete ${m$1} \u2014 every lesson, your profile and the notebook? [y/N] `);return /^y(es)?$/i.test(t.trim())}finally{o.close();}}async function Ho(e){let o=e.claudeCode||e.claudeDesktop||e.gemini||e.codex,t=e.all||e.claudeCode||!o,s=e.all||e.claudeDesktop||!o,r=e.all||e.gemini,a=e.all||e.codex;if(d(a$1.bold("Removing devcoach from your agents")),d(),t){d(a$1.bold("Claude Code"));let c=C(I);c.ok&&ve(c.data)&&d(` ${a$1.yellow("\u2192")} The devcoach plugin is enabled \u2014 its hooks, skill and MCP server go away with /plugin uninstall devcoach; only user-level entries are removed here.`);let l=ge("claude",["mcp","remove","--scope","user","devcoach"]);l||(l=pe(join(homedir(),".claude.json"))),d(` MCP server\u2026 ${l}`),d(` Hooks\u2026 ${fe(I)}`),d(` Skill\u2026 ${wo(q)}`),d();}if(s&&(d(a$1.bold("Claude Desktop")),d(` MCP server\u2026 ${pe(_o())}`),d(` ${a$1.yellow("\u2192")} Restart Claude Desktop to drop the server.`),d()),r){d(a$1.bold("Gemini CLI (beta)"));let c=ge("gemini",["mcp","remove","-s","user","devcoach"]);c||(c=pe(x)),d(` MCP server\u2026 ${c}`),d(` Hooks\u2026 ${fe(x)}`),Q()&&d(` ${a$1.yellow("\u2192")} The devcoach Gemini extension is installed \u2014 remove it with: gemini extensions uninstall devcoach`),d();}if(a){d(a$1.bold("Codex CLI (beta)"));let c=ge("codex",["mcp","remove","devcoach"]);c||(c=`${a$1.yellow("Manual step")} \u2014 codex CLI not found. Delete the [mcp_servers.devcoach] table from ${X}`),d(` MCP server\u2026 ${c}`),d(` Hooks\u2026 ${fe(H)}`),d();}if(r||a){let c=!r&&T(x,"AfterAgent")||!a&&T(H,"Stop");d(a$1.bold("Shared skill (Gemini + Codex)")),d(` Skill\u2026 ${c?`${a$1.yellow("Kept")} \u2014 still used by the other client (${N})`:wo(N)}`),d();}e.data?(d(a$1.bold("Coaching data")),existsSync(m$1)?await tn(e.yes)?(rmSync(m$1,{recursive:true,force:true}),d(` ${a$1.green("\u2713")} Deleted ${m$1}`)):d(` ${a$1.yellow("Kept")} ${m$1}`):d(` ${a$1.yellow("Nothing to delete")} (${m$1} does not exist)`),d()):d(a$1.dim(`Your lessons, profile and notebook are still in ${m$1} \u2014 keep them for a
21
+ reinstall, or delete them with: devcoach uninstall --data (devcoach backup first).`)),d(a$1.dim(`Then remove the program itself: brew uninstall devcoach \xB7 npm uninstall -g devcoach
22
+ (npx: nothing to remove).`));}function rn(e,o){return e==="darwin"?["open",[o]]:e==="win32"?["cmd",["/c","start","",o]]:["xdg-open",[o]]}function xe(e,o=process.platform){let[t,s]=rn(o,e);try{let r=spawn(t,s,{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref();}catch{}}var i=(e="")=>{console.log(e);},Mo=e=>e==="junior"?a$1.green(e):e==="mid"?a$1.yellow(e):e==="senior"?a$1.red(e):e,mn=e=>e==="know"?` ${a$1.green("\u2713")}`:e==="understood"?` ${a$1.cyan("\u{1F4A1}")}`:e==="dont_know"?` ${a$1.red("\u2717")}`:"",Ro=e=>e==="know"?a$1.green("\u2713 I knew this"):e==="understood"?a$1.cyan("\u{1F4A1} Understood"):e==="dont_know"?a$1.red("\u2717 Couldn't follow"):a$1.dim("no feedback"),No=["know","understood","dont_know","clear"];function jo(e,o){let t=new Map;for(let r of e.groups)for(let a of r.topics)t.set(a,r.name);let s=[...e.knowledge].sort((r,a)=>a.confidence-r.confidence).map(r=>{let a=g$2(r.confidence);return [r.topic,t.get(r.topic)??"Other",b$2(a,`${r.confidence}/10`),b$2(a,f(r.confidence))]});return d$2(o,[{header:"Topic"},{header:"Group"},{header:"Confidence",justify:"right"},{header:"Bar"}],s)}function Le(e){e&&i(a$1.yellow(`\u2192 ${v(e)}`));}function un(){let{profile:e,compat:o}=A(t=>({profile:ya(t),compat:x$1(t)}));i(jo(e,"Knowledge Map")),Le(o);}function pn(e){let o=null,t=A(l=>(o=x$1(l),D(l,{period:e.period==="all"?null:e.period,category:e.category,level:e.level,project:e.project,repository:e.repository,branch:e.branch,commit:e.commit,starred:e.starred?true:null,imported:e.imported||e.sharedBy?true:null,shared_by:e.sharedBy,feedback:e.feedback,date_from:e.dateFrom,date_to:e.dateTo,sort:e.sort,order:e.order})));if(t.length===0){i(a$1.dim("No lessons found."));return}let s=t.some(l=>l.project||l.branch||l.commit_hash),r=[{header:""},{header:"Date"},{header:"Topic"},{header:"Title"},{header:"Level",justify:"center"},{header:"Categories"}];s&&r.push({header:"Project"},{header:"Branch"},{header:"Commit"});let a=t.some(l=>l.imported);a&&r.push({header:"Shared by"});let c=t.map(l=>{let u=[l.starred?a$1.yellow("\u2605"):a$1.dim("\xB7"),l.timestamp.slice(0,10),a$1.cyan(l.topic_id),l.title+mn(l.feedback),Mo(l.level),l.categories.join(", ")];return s&&u.push(l.project??"",l.branch?a$1.magenta(l.branch):"",l.commit_hash?a$1.cyan(l.commit_hash.slice(0,7)):""),a&&u.push(l.imported?l.shared_by??a$1.dim("anonymous"):""),u});i(d$2("Lessons",r,c)),Le(o);}function gn(e){let o=A(s=>K(s,e));o===null&&(i(a$1.red(`Lesson '${e}' not found.`)),process.exit(1)),i(e$1(a$1.bold(o.title))),i(`${a$1.dim("ID:")} ${o.id}`),i(`${a$1.dim("Date:")} ${o.timestamp.slice(0,19).replace("T"," ")}`),i(`${a$1.dim("Topic:")} ${o.topic_id}`),i(`${a$1.dim("Categories:")} ${o.categories.join(", ")}`),i(`${a$1.dim("Level:")} ${Mo(o.level)}`);let t=o.starred?a$1.yellow("\u2605 starred"):a$1.dim("\u2606 not starred");if(i(`${a$1.dim("Star:")} ${t} ${a$1.dim("Feedback:")} ${Ro(o.feedback)}`),o.imported&&i(`${a$1.dim("Shared by:")} ${o.shared_by??a$1.dim("anonymous")}`),o.task_context&&i(`${a$1.dim("Context:")} ${o.task_context}`),o.project||o.repository||o.branch||o.commit_hash||o.folder){let s=[];o.project&&s.push(`project=${o.project}`),o.repository&&s.push(`repo=${o.repository}`),o.branch&&s.push(`branch=${a$1.magenta(o.branch)}`),o.commit_hash&&s.push(`commit=${a$1.cyan(o.commit_hash.slice(0,7))}`),o.folder&&s.push(`folder=${o.folder}`),i(`${a$1.dim("Git:")} ${s.join(" \xB7 ")}`);}i(e$1()),i(o.summary);}function Ao(e,o){A(s=>K(s,e)===null?false:(G(s,e,o),true))||(i(a$1.red(`Lesson '${e}' not found.`)),process.exit(1)),i(o?`Lesson ${a$1.cyan(e)} \u2192 ${a$1.yellow("\u2605 starred")}`:`Lesson ${a$1.cyan(e)} \u2192 ${a$1.dim("\u2606 unstarred")}`);}function fn(e){A(t=>E(t,e))||(i(a$1.red(`Lesson '${e}' not found.`)),process.exit(1)),i(`Lesson ${a$1.cyan(e)} deleted.`);}var Po=e=>e==="completed"?a$1.green(e):e==="abandoned"?a$1.dim(e):a$1.cyan(e);function hn(){let e=A(s=>h(s));if(e.length===0){i(a$1.dim("No courses yet. Start one in your agent: /devcoach:course, or say yes after a \u274C."));return}let o=[{header:"ID"},{header:"Title"},{header:"Progress",justify:"center"},{header:"Status"},{header:"Updated"}],t=e.map(s=>{let r=m(s);return [a$1.cyan(s.id),s.title,`${r.done}/${r.total}`,Po(s.status),s.updated_at.slice(0,10)]});i(d$2("Courses",o,t));}function bn(e){let o=A(r=>g$1(r,e));o===null&&(i(a$1.red(`Course '${e}' not found.`)),process.exit(1));let t=m(o);i(e$1(a$1.bold(o.title))),i(`${a$1.dim("ID:")} ${o.id}`),i(`${a$1.dim("Topic:")} ${a$1.cyan(o.topic_id)} ${a$1.dim("Status:")} ${Po(o.status)} ${a$1.dim("Progress:")} ${t.done}/${t.total}`),o.goal&&i(`${a$1.dim("Goal:")} ${o.goal}`),o.lesson_id&&i(`${a$1.dim("From:")} lesson ${a$1.cyan(o.lesson_id)}`);let s=e$2(o.id);if(i(`${a$1.dim("Document:")} ${s??a$1.dim(`not written yet \u2192 ${d$3(o.id)}`)}`),o.prerequisites.length&&i(`${a$1.dim("Chain:")} ${o.prerequisites.map(r=>r.known?a$1.green(`\u2713 ${r.concept}`):a$1.red(`\u2717 ${r.concept}`)).join(a$1.dim(" \u2192 "))}`),i(""),o.steps.length===0){i(a$1.dim("No steps registered yet."));return}for(let r of o.steps){let a=r.status==="done"?a$1.green("\u25CF"):r.status==="skipped"?a$1.dim("\u25CC"):a$1.cyan("\u25CB");i(` ${a} ${r.position}. ${r.title} ${a$1.dim(`${r.kind} \xB7 #${r.anchor}${r.status!=="todo"?` \xB7 ${r.status}`:""}`)}`);}}function kn(e,o){No.includes(o)||(i(a$1.red(`Invalid feedback '${o}'. Use: ${No.join(" | ")}`)),process.exit(1));let t=o==="clear"?null:o,s=A(a=>Aa(a,e,t));s===null&&(i(a$1.red(`Lesson '${e}' not found.`)),process.exit(1));let r;if(t===null)r="feedback cleared";else if(s.delta!==0&&s.confidence!==null){let a=s.confidence-s.delta;r=`${a$1.cyan(s.topic_id)} confidence: ${a} \u2192 ${a$1.bold(String(s.confidence))}`;}else r=`${a$1.cyan(s.topic_id)} confidence unchanged`;i(`Lesson ${a$1.cyan(e)} \u2192 ${Ro(t)} (${r})`);}function $n(){let e=A(r=>T$1(r)),o=Math.floor(e.min_gap_minutes/60),t=e.min_gap_minutes%60,s=o?`${o}h ${t}m`:`${t}m`;i(d$2("Settings",[{header:"Key"},{header:"Value",justify:"right"}],[["max_per_day",String(e.max_per_day)],["min_gap_minutes",`${e.min_gap_minutes} (${s})`],["nudge_every",e.nudge_every===0?"0 (off)":String(e.nudge_every)],["nudge_scope",e.nudge_scope],["share_name",e.share_name??a$1.dim("(unset \u2192 git user.name)")]]));}function yn(){let{stats:e,rateLimit:o,settings:t,compat:s}=A(f=>({stats:Ba(f),rateLimit:xa(f),settings:T$1(f),compat:x$1(f)})),r=f=>Number(e[f]??0),a=o.allowed?a$1.green("Available now"):a$1.yellow(o.reason??"");i(d$2("Coaching Stats",[{header:"Metric"},{header:"Value",justify:"right"}],[["Total lessons",String(r("total_lessons"))],["Lessons today (24h)",`${r("lessons_today")} / ${t.max_per_day}`],["Lessons this week",String(r("lessons_this_week"))],["Next lesson",a]],false));let c=e.weakest_topics??[],l=e.strongest_topics??[];if(c.length||l.length){let f=[];for(let g=0;g<Math.max(c.length,l.length);g++){let m=c[g],p=l[g];f.push([m?`${a$1.red(m.topic)} ${a$1.dim(`(${m.confidence})`)}`:"",p?`${a$1.green(p.topic)} ${a$1.dim(`(${p.confidence})`)}`:""]);}i(d$2(void 0,[{header:"Weakest topics"},{header:"Strongest topics"}],f));}let u=Ce();u&&i(`
23
+ ${u}`),Le(s);}function vn(e,o){let t$1=["max_per_day","min_gap_minutes","nudge_every","nudge_scope","share_name"];if(t$1.includes(e)||(i(a$1.red(`Unknown key '${e}'. Valid keys: ${t$1.join(", ")}`)),process.exit(1)),e==="nudge_scope"&&o!=="session"&&o!=="global"&&(i(a$1.red(`Invalid nudge_scope '${o}'. Use: session | global`)),process.exit(1)),e==="share_name"){o.trim().length>s&&(i(a$1.red(`share_name must be at most ${s} characters.`)),process.exit(1));let s$1=t(o);A(r=>U(r,e,s$1)),i(s$1?a$1.green(`Set share_name = ${s$1}`):a$1.green("Cleared share_name"));return}if(e==="nudge_every"){let s=Number.parseInt(o,10);(!Number.isInteger(s)||s<0)&&(i(a$1.red(`Invalid nudge_every '${o}'. Use a non-negative integer (0 = off).`)),process.exit(1));}A(s=>U(s,e,o)),i(a$1.green(`Set ${e} = ${o}`));}function wn(e,o,t){let s=e.trim();s||(i(a$1.red("Topic name must not be empty.")),process.exit(1)),A(a=>{N$1(a,s,o),t&&t!=="Other"&&R(a,s,t);});let r=t&&t!=="Other"?` \u2192 ${a$1.cyan(t)}`:"";i(`${a$1.green("Added")} ${a$1.bold(s)} (confidence ${a$1.cyan(String(o))})${r}`);}function Cn(e){let o=A(t=>O(t,e));i(o?`${a$1.green("Removed")} ${a$1.bold(e)} from knowledge map`:a$1.yellow(`Topic '${e}' not found.`));}function Sn(e){let o=e.trim();(!o||o==="Other")&&(i(a$1.red("Invalid group name.")),process.exit(1)),A(t=>P(t,o)),i(`${a$1.green(`Group '${a$1.cyan(o)}' ready.`)} Assign topics with: devcoach group-assign <topic> "${o}"`);}function _n(e){let o=A(t=>Q$1(t,e));i(o?`${a$1.green(`Removed group '${a$1.cyan(e)}'`)}`:a$1.yellow(`Group '${e}' not found.`));}function xn(e,o){A(s=>s.prepare("SELECT topic FROM knowledge WHERE topic = ?").get(e)===void 0?false:(o==="Other"?S$1(s,e):R(s,e,o),true))||(i(a$1.red(`Topic '${e}' not in knowledge map. Add it first.`)),process.exit(1)),i(o==="Other"?`${a$1.green("Moved")} ${a$1.bold(e)} \u2192 Other (ungrouped)`:`${a$1.green("Moved")} ${a$1.bold(e)} \u2192 ${a$1.cyan(o)}`);}function In(e){let{lessonsCount:o$1,knowledgeCount:t,data:s}=A(a=>({lessonsCount:H$1(a).length,knowledgeCount:M(a).length,data:ka(a)}));writeFileSync(e,s);let r=existsSync(o)?" + notebook":"";i(`${a$1.green("Backup saved:")} ${e} (${a$1.cyan(String(o$1))} lessons, ${a$1.cyan(String(t))} topics${r})`);}function Ln(e){existsSync(e)||(i(a$1.red(`File not found: ${e}`)),process.exit(1));let o=A(s=>ma(s,readFileSync(e)));o.settings&&i(`${a$1.green("\u2713")} Settings restored`),o.topics&&i(`${a$1.green("\u2713")} Knowledge map restored (${a$1.cyan(String(o.topics))} topics)`);let t=[`${a$1.cyan(String(o.lessons))} imported`];o.skipped&&t.push(`${a$1.yellow(String(o.skipped))} duplicates skipped`),o.invalid&&t.push(`${a$1.red(String(o.invalid))} rejected (invalid)`),i(`${a$1.green("\u2713")} Lessons: ${t.join(", ")}`),o.learning_state&&i(`${a$1.green("\u2713")} Notebook restored`);}var oe=e=>{console.error(a$1.dim(e));};function Dn(e,o){o.by!==void 0&&o.anonymous&&(i(a$1.red("Use either --by <name> or --anonymous, not both.")),process.exit(1)),!e&&!o.last&&(i(a$1.red("Give a lesson id, or --last for the most recent one.")),process.exit(2));let t$1=A(a=>{let c=o.last?D(a,{imported:false,page:1,per_page:1})[0]??null:K(a,e);if(!c)return null;let l=T$1(a),u=pa({explicit:o.by??null,anonymous:o.anonymous,setting:l.share_name,gitUserName:n()}),f=false;return o.by?.trim()&&!l.share_name&&(U(a,"share_name",t(o.by)),f=true),{payload:oa(c,{includeContext:!!o.withContext,sharedBy:u}),remembered:f}});t$1||(i(a$1.red(o.last?"No lessons to share yet.":`Lesson '${e}' not found.`)),process.exit(1));let{payload:s,remembered:r}=t$1;if(o.file!==void 0&&o.file!==false){let a=typeof o.file=="string"?o.file:va(s);writeFileSync(a,wa(s)),i(`${a$1.green("Saved:")} ${a}`);}else o.link?i(ta(s)):(i(sa(s)),qa(s).length>16e3&&oe("Long lesson \u2014 prefer --file for a friendlier hand-off."));r&&oe("(remembered as share_name \u2014 change it with: devcoach set share_name <name>)"),s.shared_by===null&&oe("Shared anonymously (set a name with: devcoach set share_name <name>)");}function On(){let e=process.platform==="darwin"?[["pbpaste",[]]]:process.platform==="win32"?[["powershell",["-NoProfile","-Command","Get-Clipboard"]]]:[["wl-paste",["--no-newline"]],["xclip",["-selection","clipboard","-o"]],["xsel",["--clipboard","--output"]]];for(let[o,t]of e)try{let s=execFileSync(o,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});if(s.trim())return s}catch{}throw new na("Clipboard is empty or unavailable \u2014 pass the code, a link or a file, or pipe it: devcoach import -")}async function Hn(e){return e===void 0?On():e==="-"?text(process.stdin):existsSync(e)?readFileSync(e,"utf8"):p(e)&&!e.includes("#devcoach:lesson:")?q$1(e):e}async function Nn(e){try{let o=await Hn(e),t=A(a=>Ca(a,o));if(t.kind==="lessons"){let a=[`${a$1.cyan(String(t.inserted))} imported`];t.duplicated&&a.push(`${a$1.yellow(String(t.duplicated))} duplicates skipped`),t.invalid&&a.push(`${a$1.red(String(t.invalid))} rejected (invalid)`),i(`${a$1.green("\u2713")} Lessons: ${a.join(", ")}`);return}let s=t.lesson;s||(i(a$1.red("Could not store the lesson.")),process.exit(1));let r=s.shared_by?`shared by ${s.shared_by}`:"shared anonymously";t.duplicated?i(`${a$1.yellow("Already in your log")} as ${a$1.cyan(s.id)} (${r})`):i(`${a$1.green("\u2713 Imported")} ${a$1.bold(`"${s.title}"`)} (${r}) as ${a$1.cyan(s.id)} \u2014 topic ${a$1.cyan(s.topic_id)}`),t.topic_tracked===!1&&oe(`Topic '${s.topic_id}' is not in your knowledge map \u2014 track it with: devcoach knowledge-add ${s.topic_id}`);}catch(o){if(!(o instanceof na))throw o;i(a$1.red(o.message)),process.exit(1);}}async function An(){let e=createInterface({input:process.stdin,output:process.stdout}),o=async(s,r="")=>{let a=r?` [${r}]`:"";return (await e.question(`${s}${a}: `)).trim()||r},t=async(s,r,a,c)=>{for(;;){let l=await o(s,String(r)),u=Number.parseInt(l,10);if(!Number.isNaN(u)&&u>=a&&u<=c)return u;i(a$1.red(`Must be ${a}\u2013${c}.`));}};try{i(e$1(a$1.bold("devcoach setup"))),i(`
24
+ ${a$1.bold("Step 1")} \u2014 Restore from backup`);let s=await o("Path to existing backup zip (Enter to skip)","");if(s){existsSync(s)||(i(a$1.red(`File not found: ${s}`)),process.exit(1));let g=A(m=>ma(m,readFileSync(s)));i(`${a$1.green("\u2713")} Restored: ${g.topics} topics, ${g.lessons} lessons${g.learning_state?", notebook":""}`),i(a$1.green("Setup complete!"));return}i(`
25
+ ${a$1.bold("Step 2")} \u2014 Build your knowledge profile`);let r=(await o("Mode: [a]utomatic (detect from files) / [m]anual (type your stack)","a")).toLowerCase(),a={};if(r.startsWith("a")){let m=o$1().folder??process.cwd(),p=c(),k=b$1(a$2(m),p.detected_stack),$=Object.keys(k).sort((v,E)=>v.localeCompare(E));if(p.scanned_projects>0){i(`
26
+ ${a$1.dim(`Scanned ${p.scanned_projects} Claude Code project(s) from your history:`)}`);for(let v of p.projects.slice(0,8))i(a$1.dim(` ${v.name} \u2014 ${v.topics.join(", ")||"no stack signals"}`));}if($.length){i(`
27
+ ${a$1.dim(`Detected (history + ${a$1.cyan(m)}):`)}`);for(let v of $){let E=k[v]??5,De=await o(` ${a$1.cyan(v)} (Enter=keep, 0-10=override, s=skip)`,String(E));if(De.toLowerCase()==="s")continue;let Oe=Number.parseInt(De,10);a[v]=Number.isNaN(Oe)?E:Math.max(0,Math.min(10,Oe));}}else i(a$1.dim("No technology files detected in current directory."));let A=await o(`
28
+ Add additional topics (comma-separated, or Enter to skip)`,"");for(let v of A.split(",").map(E=>E.trim()).filter(Boolean))a[v]=await t(` Confidence for ${a$1.cyan(v)}`,5,0,10);}else for(i(a$1.dim(`
29
+ Enter topics: 'topic_id confidence' (e.g. python 7). Blank line when done.`));;){let g=(await o("Topic (Enter when done)","")).trim();if(!g)break;let m=g.split(/\s+/),p=m[0]??"",k=Number.parseInt(m[1]??"",10),$=Number.isNaN(k)?5:Math.max(0,Math.min(10,k));a[p]=$,i(` ${a$1.green("+")} ${a$1.cyan(p)} \u2192 ${$}`);}let c$1={};if(Object.keys(a).length&&(i(`
30
+ ${a$1.bold("Step 3")} \u2014 Organise into groups`),(await o("Organise topics into groups? [y/N]","n")).toLowerCase().startsWith("y"))){let m=[];for(let p of Object.keys(a).sort((k,$)=>k.localeCompare($))){let k=m.length?m.join(", "):"(none yet)",$=await o(` Group for ${a$1.cyan(p)} existing: ${a$1.dim(k)} (Enter=Other)`,"");if($&&$!=="Other"){let A=c$1[$]??[];A.push(p),c$1[$]=A,m.includes($)||m.push($);}}}i(`
31
+ ${a$1.bold("Step 4")} \u2014 Rate-limit settings`);let l=await t("Max lessons per day",2,1,20),u=await t("Min gap between lessons (minutes)",240,0,1440),f=A(g=>{g.exec("DELETE FROM knowledge; DELETE FROM knowledge_groups; DELETE FROM knowledge_group_names;");for(let[m,p]of Object.entries(a))N$1(g,m,p);for(let[m,p]of Object.entries(c$1))for(let k of p)R(g,k,m);return U(g,"max_per_day",String(l)),U(g,"min_gap_minutes",String(u)),ya(g)});i(jo(f,"Knowledge Profile")),i(`
32
+ ${a$1.green("Setup complete!")} ${Object.keys(a).length} topics saved.`);}finally{e.close();}}function En(){let e=[["mcp","Start the MCP server (stdio) for Claude Code / Claude Desktop"],["ui [--port N] [--open|--stop]","Launch the web dashboard (default port: 7860)"],["setup","First-run wizard: import backup or build your knowledge profile"],["install","Register MCP server + hooks + skill (Claude default; --gemini/--codex beta)"],["uninstall","Remove the MCP server, hooks and skill (--all: every agent; --data: wipe ~/.devcoach)"],["onboard-hook","Claude Code Stop hook: cue onboarding when no profile exists"],["lesson-ready","Claude Code Stop hook: cue a lesson when one is due"],["doctor","Diagnose the agent wiring \u2014 explains why a lesson would(n't) fire"],["profile","Show the knowledge map"],["stats","Coaching statistics and rate-limit status"],["settings / set","Show / update settings (max_per_day | min_gap_minutes)"],["lessons / lesson","List past lessons / show one in detail"],["courses / course","List your courses / show one with its steps"],["star / unstar / delete","Manage a lesson"],["feedback <id>","Record know / understood / dont_know feedback"],["share / import","Hand a lesson to a teammate / add a shared lesson to your log"],["knowledge-add / -remove","Add / remove a topic"],["group-add / -remove / -assign","Manage knowledge groups"],["backup / restore","Export / import a full backup zip"]];i(`
33
+ ${a$1.bold(`devcoach ${a$1.dim(`v${a}`)}`)}`);for(let[t,s]of e)i(` ${a$1.cyan(`devcoach ${t}`.padEnd(32))} ${a$1.dim(s)}`);i(`
34
+ ${a$1.dim("Run")} ${a$1.bold("devcoach <command> --help")} ${a$1.dim("for per-command options.")}
35
+ `);let o=Ce();o&&i(`${o}
36
+ `);}function S(e){return e??null}function Mn(){let e$1=new Command;return e$1.exitOverride(),e$1.name("devcoach").description("devcoach \u2014 progressive technical coaching").version(`devcoach ${a}`,"-v, --version","output the version number").allowExcessArguments(false).showHelpAfterError("(add --help for usage)").action(()=>En()),e$1.command("mcp").description("Start the MCP server (stdio transport)").action(async()=>{let{runStdio:o}=await import('./server-VAF6ODVD.js');await o();}),e$1.command("profile").description("Show the knowledge map").action(un),e$1.command("lessons").description("List past lessons").option("--period <period>","today | week | month | year | all","all").option("--category <category>","Filter by category tag").option("--project <project>","Filter by project (fuzzy)").option("--repository <repository>","Filter by repository (fuzzy)").option("--branch <branch>","Filter by branch (fuzzy)").option("--commit <commit>","Filter by commit hash prefix (fuzzy)").option("--starred","Show only starred lessons").option("--imported","Show only lessons shared with you").option("--from <name>","Show only lessons shared by this person").option("--feedback <feedback>","know | understood | dont_know | none").option("--level <level>","junior | mid | senior").option("--date-from <date>","Show lessons on or after this date (YYYY-MM-DD[THH:MM])").option("--date-to <date>","Show lessons on or before this date (YYYY-MM-DD[THH:MM])").option("--sort <column>","timestamp | level | topic_id | title | feedback","timestamp").option("--order <order>","asc | desc","desc").action(o=>pn({period:o.period??"all",category:S(o.category),project:S(o.project),repository:S(o.repository),branch:S(o.branch),commit:S(o.commit),starred:!!o.starred,imported:!!o.imported,sharedBy:S(o.from),feedback:S(o.feedback),level:S(o.level),dateFrom:S(o.dateFrom),dateTo:S(o.dateTo),sort:o.sort??"timestamp",order:o.order??"desc"})),e$1.command("lesson").description("Show a single lesson in detail").argument("<id>","Lesson ID").action(o=>gn(o)),e$1.command("courses").description("List your step-by-step courses").action(()=>hn()),e$1.command("course").description("Show a course: steps, progress, document path").argument("<id>","Course ID").action(o=>bn(o)),e$1.command("star").description("Mark a lesson as starred").argument("<id>","Lesson ID").action(o=>Ao(o,true)),e$1.command("unstar").description("Remove the starred mark from a lesson").argument("<id>","Lesson ID").action(o=>Ao(o,false)),e$1.command("delete").description("Permanently delete a lesson").argument("<id>","Lesson ID").action(o=>fn(o)),e$1.command("feedback").description("Record your answer under a lesson: know / understood / dont_know").argument("<id>","Lesson ID").argument("<value>","know | understood | dont_know | clear").action((o,t)=>kn(o,t)),e$1.command("share").description("Share a lesson: copyable text (default), --link, or a .devcoach.md file").argument("[id]","Lesson ID (or use --last)").option("--last","Share the most recent lesson").option("--link","Print the share link only").option("--file [path]","Write a .devcoach.md file (default: <lesson-id>.devcoach.md)").option("--with-context","Include project/branch/commit/task context (off by default)").option("--by <name>","Sender name (remembered as share_name when unset)").option("--anonymous","Share without a sender name").action((o,t)=>Dn(o,t)),e$1.command("import").description("Import a shared lesson: a devcoach:lesson code, a share link, a URL, a .devcoach.md or lessons .json file, - for stdin \u2014 or the clipboard when omitted").argument("[source]","Code, link, URL, file path, or - (stdin); omit to read the clipboard").action(o=>Nn(o)),e$1.command("settings").description("Show current settings").action($n),e$1.command("stats").description("Coaching statistics and rate-limit status").action(yn),e$1.command("set").description("Update a setting (max_per_day | min_gap_minutes | nudge_every | nudge_scope | share_name)").argument("<key>","Setting key").argument("<value>","New value").action((o,t)=>vn(o,t)),e$1.command("knowledge-add").description("Add or update a topic in the knowledge map").argument("<topic>","Topic ID").option("--confidence <n>","Initial confidence 0-10","5").option("--group <group>","Assign to a named group").action((o,t)=>wn(o,Math.max(0,Math.min(10,Number.parseInt(t.confidence??"5",10)||5)),S(t.group))),e$1.command("knowledge-remove").description("Remove a topic from the knowledge map").argument("<topic>","Topic ID").action(o=>Cn(o)),e$1.command("group-add").description("Register a new knowledge group").argument("<name>","Group name").action(o=>Sn(o)),e$1.command("group-remove").description("Delete a knowledge group (topics move to Other)").argument("<name>","Group name").action(o=>_n(o)),e$1.command("group-assign").description("Move a topic to a group").argument("<topic>","Topic ID").argument("<group>","Group name (use 'Other' to ungroup)").action((o,t)=>xn(o,t)),e$1.command("backup").description("Export a full backup (settings + knowledge + lessons) as zip").argument("[file]","Output zip path","devcoach-backup.zip").action(o=>In(o)),e$1.command("restore").description("Restore from a backup zip file").argument("<file>","Path to backup zip").action(o=>Ln(o)),e$1.command("install").description("Register the MCP server + hooks + skill in Claude Code / Claude Desktop (default), Gemini CLI (--gemini, beta), or Codex CLI (--codex, beta)").option("--claude-code","Target Claude Code only").option("--claude-desktop","Target Claude Desktop only").option("--gemini","Target Google Gemini CLI (beta)").option("--codex","Target OpenAI Codex CLI (beta)").option("--force","Overwrite existing devcoach entry").option("--skip-hook","Register MCP server only \u2014 skip the hooks").action(o=>Do({claudeCode:!!o.claudeCode,claudeDesktop:!!o.claudeDesktop,gemini:!!o.gemini,codex:!!o.codex,force:!!o.force,skipHook:!!o.skipHook})),e$1.command("uninstall").description("Remove devcoach's MCP server, hooks and skill from Claude Code / Claude Desktop (default), Gemini CLI (--gemini), Codex CLI (--codex) or every agent (--all). Coaching data is kept unless --data is given. Run it before brew/npm uninstall.").option("--claude-code","Target Claude Code only").option("--claude-desktop","Target Claude Desktop only").option("--gemini","Also remove from Google Gemini CLI (beta)").option("--codex","Also remove from OpenAI Codex CLI (beta)").option("--all","Every agent: Claude Code, Claude Desktop, Gemini CLI, Codex CLI").option("--data","Also delete ~/.devcoach (lessons, profile, notebook) \u2014 asks first").option("--yes","Do not ask before deleting the data (with --data)").action(async o=>Ho({claudeCode:!!o.claudeCode,claudeDesktop:!!o.claudeDesktop,gemini:!!o.gemini,codex:!!o.codex,all:!!o.all,data:!!o.data,yes:!!o.yes})),e$1.command("doctor").description("Diagnose the devcoach \u21C4 agent wiring and the lesson pacing state").action(Oo),e$1.command("ui").description("Launch the web dashboard (Ctrl+C stops it gracefully; --stop stops a running one)").option("--port <port>","Port","7860").option("-o, --open","Open the dashboard in your default browser").option("--stop","Stop the dashboard running on --port (e.g. one started by your agent)").action(async o=>{let t=Number.parseInt(o.port??"7860",10)||7860,{startUi:s,stopUi:r}=await import('./app-TSWVQY4O.js');if(o.stop){i(await r(t)?a$1.green(`\u2713 devcoach UI on port ${t} stopped`):a$1.yellow(`No devcoach UI is running on port ${t}`));return}s(t,{onReady:a=>{o.open&&xe(a);},onListenError:a=>{console.error(a.message),o.open&&a.existingUrl&&xe(a.existingUrl),process.exit(a.exitCode);}});}),e$1.command("setup").description("First-run wizard: import backup or build your knowledge profile").action(An),e$1.command("stop-hook",{hidden:true}).description("Claude Code Stop hook: onboarding check + lesson cue in one spawn").action(()=>e()),e$1.command("prompt-hook",{hidden:true}).description("Claude Code UserPromptSubmit hook: prime the model when a lesson is due").action(()=>g()),e$1.command("gemini-stop-hook",{hidden:true}).description("Gemini CLI AfterAgent hook: onboarding check + lesson cue in one spawn").action(()=>e(void 0,"gemini")),e$1.command("gemini-prompt-hook",{hidden:true}).description("Gemini CLI BeforeAgent hook: prime the model when a lesson is due").action(()=>g(void 0,"gemini")),e$1.command("codex-stop-hook",{hidden:true}).description("Codex CLI Stop hook: onboarding check + lesson cue in one spawn").action(()=>e(void 0,"codex")),e$1.command("codex-prompt-hook",{hidden:true}).description("Codex CLI UserPromptSubmit hook: prime the model when a lesson is due").action(()=>g(void 0,"codex")),e$1.command("onboard-hook",{hidden:true}).description("Claude Code Stop hook: cue onboarding (legacy two-entry layout)").action(()=>b()),e$1.command("lesson-ready",{hidden:true}).description("Claude Code Stop hook: signal a lesson is due (legacy two-entry layout)").action(()=>d$1()),e$1}async function ct(){let e=Mn();try{await e.parseAsync(process.argv);}catch(o){let t=o.code??"";if(!t.startsWith("commander."))throw o;if(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.version")return;process.exit(2);}}export{ct as runCli};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- export{c as buildLessonCue,f as buildPromptPrime,d as cmdLessonReady,b as cmdOnboardHook,g as cmdPromptHook,e as cmdStopHook,a as parseHookPayload,h as runHook}from'./chunk-PLIU5NYQ.js';import'./chunk-RUBF2HCU.js';
2
+ export{c as buildLessonCue,f as buildPromptPrime,d as cmdLessonReady,b as cmdOnboardHook,g as cmdPromptHook,e as cmdStopHook,a as parseHookPayload,h as runHook}from'./chunk-RGZN7AZO.js';import'./chunk-C3PYOEBP.js';
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import {d as d$2,f as f$2,e as e$1,c as c$2,b as b$3,a as a$2}from'./chunk-MRABMPXO.js';import {o,n,p,q,b as b$2,f as f$1,d as d$3,c as c$1,i as i$1,g as g$1,j as j$1,k as k$1,h as h$1}from'./chunk-MKH6XAM4.js';import {b as b$1,d as d$1,c,h,g,f,a as a$1,A,_,l,B,W,za,D,G,E,Aa,Y,e,N,R,O,P,Q,s,t,ya,o as o$1,K,pa,T,oa,va,wa,ta,sa,qa,Ca,na,k,j,i,Ba,Da,C,xa,U,Z,x,r}from'./chunk-C3PYOEBP.js';import {spawn}from'child_process';import {mkdirSync,existsSync,statSync,writeFileSync,readFileSync}from'fs';import {dirname}from'path';import {McpServer,ResourceTemplate}from'@modelcontextprotocol/server';import {StdioServerTransport}from'@modelcontextprotocol/server/stdio';import {z}from'zod';var d=o=>({type:"text",text:o}),Ne=o=>({content:[d(JSON.stringify(o))]}),a=o=>({isError:true,content:[d(o)]}),b=o=>({content:[d(JSON.stringify(o))],structuredContent:o}),De=z.object({id:z.string(),timestamp:z.string(),topic_id:z.string(),categories:z.array(z.string()),title:z.string(),level:b$1,summary:z.string(),body:z.string().nullable(),task_context:z.string().nullable(),project:z.string().nullable(),repository:z.string().nullable(),branch:z.string().nullable(),commit_hash:z.string().nullable(),folder:z.string().nullable(),repository_platform:c.nullable(),starred:z.boolean(),feedback:d$1.nullable(),imported:z.boolean(),shared_by:z.string().nullable()}),Ve=De.extend({reply_check:z.string()}),Pe="Saved \u2014 but saving does NOT display anything. The user sees ONLY plain text you write in your reply; the title/body inside this tool call's ARGUMENTS are invisible to them, and having composed them does not count as having shown the card. Did you already write the full card (both ### band headings + title line + body + tip) as plain reply text, outside any tool call? If yes: output nothing. If no: write the card now, as the final text of your reply. Never write it twice.",Xe=z.object({readOnly:z.literal(true),dbSchema:z.number().int(),appSchema:z.number().int(),upgradedBy:z.string().nullable(),minApp:z.string().nullable()}).nullable().optional(),Ie=z.object({knowledge:z.array(z.object({topic:z.string(),confidence:z.number().int()})),groups:z.array(z.object({name:z.string(),topics:z.array(z.string())})),compat:Xe}),Qe=z.object({max_per_day:z.number().int(),min_gap_minutes:z.number().int(),ui_theme:f,ui_home:g,nudge_every:z.number().int(),nudge_scope:h,share_name:z.string().nullable()}),Ze=z.object({transport:z.enum(["text","link","file"]),code:z.string(),text:z.string().nullable(),link:z.string().nullable(),markdown:z.string().nullable(),filename:z.string().nullable(),shared_by:z.string().nullable(),include_context:z.boolean(),reply_check:z.string()}),et=z.object({kind:z.enum(["shared","lessons"]),inserted:z.number().int(),duplicated:z.number().int(),invalid:z.number().int(),lesson:De.nullable(),topic_tracked:z.boolean().nullable(),reply_check:z.string()}),tt={text:"Reply with `text` verbatim as the final message: the card as markdown, then the last line (devcoach:lesson:1:\u2026) inside a fenced code block, character for character \u2014 never paraphrase, wrap, truncate or split it.",link:"Reply with `link` on its own line, unchanged.",file:"Write `markdown` to `filename` (in the workspace unless the user named a path) with your file tool, then confirm the path in one line; do not print the markdown."},nt="Confirm in one line: the title, who shared it, and that it joined the coaching log (feedback works as usual; it does not count against the daily limit). If topic_tracked is false, offer to track the topic with add_topic \u2014 only on confirmation.",ot=z.object({window_months:z.number().int(),cutoff:z.string(),candidate_count:z.number().int(),over_soft_limit:z.boolean(),candidates:z.array(z.object({name:z.string(),path:z.string(),last_activity:z.string().nullable(),prompt_count:z.number().int()}))});function u(o,p){return {contents:[{uri:o.href,mimeType:"application/json",text:JSON.stringify(p)}]}}function $e(){try{return A(o=>({...ya(o),compat:x(o)}))}catch(o){return {error:String(o)}}}function Ue(){try{let o="";try{existsSync(o$1)&&(o=readFileSync(o$1,"utf8"));}catch{}return {...A(m=>{let g=Z(m).knowledge_ready,f=o.length>0,l=xa(m),t={allowed:l.allowed,total_lessons:C(m)};return l.reason!=null&&(t.reason=l.reason),{onboarding:{knowledge_ready:g,notebook_ready:f,needs_onboarding:!(g&&f)},rate_limit:t,taught_topics:Da(m),profile:ya(m),compat:x(m)}}),notebook:o,notebook_path:o$1}}catch(o){return {error:String(o)}}}function Ge(){try{let{status:o$2,compat:p}=A(n=>({status:Z(n),compat:x(n)})),m=o$2.knowledge_ready,g=existsSync(o$1)&&statSync(o$1).size>0,f=o(),l=c$2(),t=b$3(a$2(f.folder??process.cwd()),l.detected_stack);return {compat:p,knowledge_ready:m,notebook_ready:g,needs_onboarding:!(m&&g),detected_stack:t,detected_projects:l.projects,scanned_projects:l.scanned_projects,default_topics:r,context_ready:f.branch!==null,notebook_path:o$1}}catch(o){return {error:String(o)}}}var F=(o,p)=>typeof p.error=="string"?a(`${o} failed: ${p.error}`):b(p);function rt(){let o$2=new McpServer({name:"devcoach",version:a$1},{instructions:"Progressive technical coaching server. Use the devcoach_instructions prompt for full coaching behaviour guidelines. Read coaching state with the get_briefing / get_onboarding / get_profile tools; the devcoach:// resources expose the same data for clients that browse resources. share_lesson hands a lesson to another person (text, link or file); import_lesson stores one they were given."});o$2.registerTool("log_lesson",{title:"Log Lesson",description:"Save a delivered lesson to the coaching log. Git metadata (project, repository, branch, commit_hash, folder, repository_platform) is auto-detected from the workspace when omitted. timestamp is always stamped server-side with the current time \u2014 there is no argument for it. Returns the saved Lesson with all resolved fields.",inputSchema:z.object({id:z.string().describe("Unique lesson id (uuid or random string)"),topic_id:z.string().describe("Primary topic id, e.g. 'python'"),categories:z.array(z.string()).describe("Category tags, e.g. ['python','performance']"),title:z.string().describe("Short lesson title"),level:b$1.describe("Difficulty level: junior | mid | senior"),summary:z.string().describe("1-3 sentence summary shown in the lesson card"),body:z.string().min(1).describe("Clean lesson markdown: the prose + \u{1F4A1} Senior tip only \u2014 NO card bands, NO '>' blockquote, and do not repeat title/category/level (those are their own fields). Required, non-empty."),task_context:z.string().nullish().describe("What the user was doing when taught"),project:z.string().nullish().describe("Project name (auto-detected from git if omitted)"),repository:z.string().nullish().describe("org/repo or path (auto-detected if omitted)"),branch:z.string().nullish().describe("git branch (auto-detected if omitted)"),commit_hash:z.string().nullish().describe("git commit hash (auto-detected if omitted)"),folder:z.string().nullish().describe("workspace folder (auto-detected if omitted)"),repository_platform:c.nullish().describe("github | gitlab | bitbucket | local (auto-detected if omitted)")}),outputSchema:Ve,annotations:{title:"Log Lesson",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=o(),r={};try{r=A(c=>_(c));}catch{r={};}let i=l({id:t.id,timestamp:new Date,topic_id:t.topic_id,categories:t.categories,title:t.title,level:t.level,summary:t.summary,body:t.body,task_context:t.task_context??null,project:t.project??n.project??r.project??null,repository:t.repository??n.repository??r.repository??null,branch:t.branch??n.branch??r.branch??null,commit_hash:t.commit_hash??n.commit_hash??null,folder:t.folder??n.folder??null,repository_platform:t.repository_platform??n.repository_platform??r.repository_platform??null});return A(c=>{B(c,i),W(c);}),{content:[d(`Lesson saved. ${Pe}`),d(JSON.stringify(i))],structuredContent:{...i,reply_check:Pe}}}catch(n){return a(`log_lesson failed: ${n}`)}}),o$2.registerTool("update_knowledge",{title:"Update Knowledge",description:"Adjust the confidence score for a topic by delta (e.g. +1 or -1). Returns the new confidence (0-10). Creates the topic at confidence 5 if it does not exist.",inputSchema:z.object({topic:z.string().describe("Topic id, e.g. 'python'"),delta:z.number().int().describe("Signed change to apply, e.g. +1 or -1")}),annotations:{title:"Update Knowledge",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>za(r,t.topic,t.delta));return {content:[d(String(n))]}}catch(n){return a(`update_knowledge failed for '${t.topic}': ${n}`)}}),o$2.registerTool("get_lessons",{title:"Get Lessons",description:"Query the coaching lesson history. All filters combine. period defaults to all; date_from/date_to override period; limit caps results newest-first (0 = all).",inputSchema:z.object({period:z.enum(["today","week","month","year","all"]).nullish().describe("Time window"),category:z.string().nullish().describe("Filter by a category tag, e.g. 'python'"),level:z.enum(["junior","mid","senior"]).nullish().describe("Filter by difficulty level"),project:z.string().nullish().describe("Fuzzy match on git project"),repository:z.string().nullish().describe("Fuzzy match on git repository"),branch:z.string().nullish().describe("Fuzzy match on git branch"),commit:z.string().nullish().describe("Fuzzy match on commit hash"),starred:z.boolean().nullish().describe("True to return only starred lessons"),imported:z.boolean().nullish().describe("True = only lessons shared with you, false = only your own"),shared_by:z.string().nullish().describe("Only lessons shared by this person (exact sender name; implies imported)"),feedback:z.enum(["know","understood","dont_know","none"]).nullish().describe("Filter by feedback: know (already knew), understood (new, now clear), dont_know (couldn't follow \u2014 a course seed), none (no response)"),search:z.string().nullish().describe("Full-text search over title, topic_id, summary, body and the sender's name"),date_from:z.string().nullish().describe("ISO date/datetime lower bound"),date_to:z.string().nullish().describe("ISO date/datetime upper bound (date-only = end-of-day)"),limit:z.number().int().default(10).describe("Max lessons, newest first. Pass 0 for all.")}),annotations:{title:"Get Lessons",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},t=>{try{let n=A(r=>D(r,{period:t.period,category:t.category,level:t.level,project:t.project,repository:t.repository,branch:t.branch,commit:t.commit,starred:t.starred,imported:t.imported,shared_by:t.shared_by,feedback:t.feedback,search:t.search,date_from:t.date_from,date_to:t.date_to,page:t.limit>0?1:null,per_page:t.limit}));return Ne(n)}catch{return Ne([])}}),o$2.registerTool("star_lesson",{title:"Star Lesson",description:"Set the starred (favourite) flag on a lesson. Returns true if found and updated. Idempotent.",inputSchema:z.object({lesson_id:z.string().describe("Lesson id"),starred:z.boolean().describe("true to favourite, false to unmark")}),annotations:{title:"Star Lesson",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>G(r,t.lesson_id,t.starred));return {content:[d(String(n))]}}catch(n){return a(`star_lesson failed for '${t.lesson_id}': ${n}`)}}),o$2.registerTool("delete_lesson",{title:"Delete Lesson",description:"Permanently delete a lesson by id. Returns true if found and deleted.",inputSchema:z.object({lesson_id:z.string().describe("Lesson id to delete")}),annotations:{title:"Delete Lesson",destructiveHint:true,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>E(r,t.lesson_id));return {content:[d(String(n))]}}catch(n){return a(`delete_lesson failed for '${t.lesson_id}': ${n}`)}}),o$2.registerTool("submit_feedback",{title:"Submit Feedback",description:"Record the user's answer under a lesson card. know = already knew it (confidence +1); understood = new and now clear (no confidence change); dont_know = couldn't follow this session (no confidence change; the lesson becomes a course seed); clear = remove the answer. Idempotent \u2014 repeating the stored answer changes nothing.",inputSchema:z.object({lesson_id:z.string().describe("Lesson id"),feedback:z.enum(["know","understood","dont_know","clear"]).describe("know | understood | dont_know | clear")}),annotations:{title:"Submit Feedback",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=t.feedback==="clear"?null:t.feedback,r=A(i=>Aa(i,t.lesson_id,n));return {content:[d(String(r!==null))]}}catch(n){return a(`submit_feedback failed for '${t.lesson_id}': ${n}`)}}),o$2.registerTool("skip_lesson",{title:"Skip Lesson",description:"Decline a lesson cue: call this when the coaching hook asked for a lesson but the completed work does not warrant one (pure questions, chat, nothing technical). Re-arms the pacing counter so the cue is not repeated immediately. Never call it after delivering a lesson \u2014 log_lesson already resolves the cue.",inputSchema:z.object({reason:z.string().min(1).describe("One line: why no lesson was warranted (shown in `devcoach doctor`)")}),annotations:{title:"Skip Lesson",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{return A(n=>Y(n,t.reason)),{content:[d("Cue skipped \u2014 pacing re-armed. Output nothing to the user.")]}}catch(n){return a(`skip_lesson failed: ${n}`)}}),o$2.registerTool("add_topic",{title:"Add Topic",description:"Add a topic to the knowledge map, or update its confidence if it exists. Optionally assign to a group (auto-created). Prefer a single-word topic id. Idempotent.",inputSchema:z.object({topic:z.string().describe("Topic id \u2014 prefer a single word, max 3 words"),confidence:e.default(5).describe("Initial confidence 0-10 (default 5)"),group:z.string().nullish().describe("Optional group name; 'Other' if omitted")}),annotations:{title:"Add Topic",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{return A(n=>{N(n,t.topic,t.confidence),t.group&&t.group!=="Other"&&R(n,t.topic,t.group);}),{content:[d("true")]}}catch(n){return a(`add_topic failed for '${t.topic}': ${n}`)}}),o$2.registerTool("remove_topic",{title:"Remove Topic",description:"Remove a topic from the knowledge map entirely. Returns true if it existed.",inputSchema:z.object({topic:z.string().describe("Topic id to remove")}),annotations:{title:"Remove Topic",destructiveHint:true,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>O(r,t.topic));return {content:[d(String(n))]}}catch(n){return a(`remove_topic failed for '${t.topic}': ${n}`)}}),o$2.registerTool("add_group",{title:"Add Group",description:"Create a new (initially empty) knowledge group. Idempotent \u2014 returns true either way.",inputSchema:z.object({name:z.string().describe("Group name, e.g. 'Machine Learning'")}),annotations:{title:"Add Group",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{return A(n=>P(n,t.name.trim())),{content:[d("true")]}}catch(n){return a(`add_group failed for '${t.name}': ${n}`)}}),o$2.registerTool("remove_group",{title:"Remove Group",description:"Delete a knowledge group. Its topics move to Other. Returns true if it existed.",inputSchema:z.object({name:z.string().describe("Group name to delete")}),annotations:{title:"Remove Group",destructiveHint:true,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>Q(r,t.name));return {content:[d(String(n))]}}catch(n){return a(`remove_group failed for '${t.name}': ${n}`)}}),o$2.registerTool("update_settings",{title:"Update Settings",description:"Update a coaching setting. max_per_day: integer 1-20. min_gap_minutes: integer 0-1440 (0 = no cooldown). nudge_every: integer 0-1000 interactions between lesson cues (0 = cue every turn). nudge_scope: 'session' | 'global'. share_name: the sender name proposed when sharing a lesson (max 80 chars, empty clears). Returns the full updated Settings.",inputSchema:z.object({key:z.enum(["max_per_day","min_gap_minutes","nudge_every","nudge_scope","share_name"]).describe("Setting key"),value:z.string().describe("New value (integer string; 'session'|'global' for nudge_scope; free text for share_name)")}),outputSchema:Qe,annotations:{title:"Update Settings",destructiveHint:false,idempotentHint:true,openWorldHint:false}},t$1=>{let n=i=>b(A(c=>(U(c,t$1.key,i),T(c))));if(t$1.key==="share_name")return t$1.value.trim().length>s?a(`share_name must be at most ${s} characters`):n(t(t$1.value));if(t$1.key==="nudge_scope")return t$1.value!=="session"&&t$1.value!=="global"?a("nudge_scope must be 'session' or 'global'"):n(t$1.value);let r=Number.parseInt(t$1.value,10);return Number.isNaN(r)?a(`Value must be an integer, got '${t$1.value}'`):t$1.key==="max_per_day"&&!(r>=1&&r<=20)?a("max_per_day must be between 1 and 20"):t$1.key==="min_gap_minutes"&&!(r>=0&&r<=1440)?a("min_gap_minutes must be between 0 and 1440"):t$1.key==="nudge_every"&&!(r>=0&&r<=1e3)?a("nudge_every must be between 0 and 1000"):n(String(r))}),o$2.registerTool("open_ui",{title:"Open UI",description:"Launch the devcoach web dashboard in the background. port must be 1024-65535.",inputSchema:z.object({port:z.number().int().default(7860).describe("Port (default 7860)")}),annotations:{title:"Open UI",destructiveHint:false,idempotentHint:false,openWorldHint:true}},async t=>{let n=t.port;if(!(n>=1024&&n<=65535))return {content:[d(`error: port ${n} is out of valid range (1024-65535)`)]};let{pingUi:r}=await import('./app-TSWVQY4O.js');return await r(n)?{content:[d(`devcoach UI is already running at http://localhost:${n}`)]}:(spawn(process.execPath,[process.argv[1]??"","ui","--port",String(n)],{detached:true,stdio:"ignore"}).unref(),{content:[d(`devcoach UI starting at http://localhost:${n}`)]})}),o$2.registerTool("stop_ui",{title:"Stop UI",description:"Stop the devcoach web dashboard listening on port (whoever started it \u2014 open_ui or a terminal). Graceful: in-flight requests finish first. Reports stopped=false when nothing is running there. port must be 1024-65535.",inputSchema:z.object({port:z.number().int().default(7860).describe("Port (default 7860)")}),annotations:{title:"Stop UI",destructiveHint:false,idempotentHint:true,openWorldHint:true}},async t=>{let n=t.port;if(!(n>=1024&&n<=65535))return {content:[d(`error: port ${n} is out of valid range (1024-65535)`)]};let{stopUi:r}=await import('./app-TSWVQY4O.js'),i=await r(n);return {content:[d(i?`devcoach UI on port ${n} stopped`:`No devcoach UI is running on port ${n}`)],structuredContent:{stopped:i,port:n}}}),o$2.registerTool("complete_onboarding",{title:"Complete Onboarding",description:"Save the user's initial knowledge profile and mark onboarding complete. Wipes any default-seeded profile. topics: {topic_id: confidence_0_to_10}. groups: {group_name: [topic_id,...]} (topics not in any group go to 'Other'). Ensures learning-state.md exists and is non-empty (a placeholder if needed) \u2014 there is no notebook argument here. Write the real personalized notebook yourself right after, directly to the path in devcoach://onboarding's notebook_path field. Returns the updated Profile.",inputSchema:z.object({topics:z.record(z.string(),e).describe("{topic_id: confidence 0-10}"),groups:z.record(z.string(),z.array(z.string())).optional().describe("{group_name: [topic_id, ...]}")}),outputSchema:Ie,annotations:{title:"Complete Onboarding",destructiveHint:true,idempotentHint:false,openWorldHint:false}},async t=>{try{let n=A(r=>{r.exec("DELETE FROM knowledge; DELETE FROM knowledge_groups; DELETE FROM knowledge_group_names;");for(let[i,c]of Object.entries(t.topics))N(r,i,Math.max(0,Math.min(10,c)));if(t.groups)for(let[i,c]of Object.entries(t.groups))for(let D of c)D in t.topics&&R(r,D,i);return ya(r)});return mkdirSync(dirname(o$1),{recursive:!0}),(!existsSync(o$1)||statSync(o$1).size===0)&&writeFileSync(o$1,`# devcoach \u2014 Coaching Notebook
3
+ `),b(n)}catch(n){return a(`complete_onboarding failed: ${n}`)}}),o$2.registerTool("preview_deep_scan",{title:"Preview Deep Scan",description:"Cheap, metadata-only pre-check for 'Automatic (Deep)' onboarding. Counts and lists Claude Code projects whose last recorded activity falls within a rolling window (months back from now) \u2014 a real date window, not a fixed top-N. Reads no prompt/conversation text, only project paths and activity timestamps. Call this BEFORE spawning the deep-read subagent: over_soft_limit true means there are enough candidates that the user should be asked whether to narrow the window, proceed anyway, or pick specific projects.",inputSchema:z.object({months:z.number().int().min(1).max(24).default(3).describe("Rolling window size in months, counting back from now")}),outputSchema:ot,annotations:{title:"Preview Deep Scan",readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}},t=>{try{return b({...d$2(t.months)})}catch(n){return a(`preview_deep_scan failed: ${n}`)}});let p$1=t=>({title:t,readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false});o$2.registerTool("get_briefing",{title:"Lesson Briefing",description:"Everything needed before delivering a lesson, in ONE call: onboarding status, rate limit, taught topics, knowledge profile, the coaching notebook text and its notebook_path. Same data as the devcoach://briefing resource \u2014 call the tool, it needs no server name.",inputSchema:z.object({}),annotations:p$1("Lesson Briefing")},()=>F("get_briefing",Ue())),o$2.registerTool("get_onboarding",{title:"Onboarding Status & Detected Stack",description:"Onboarding status (knowledge_ready, notebook_ready, needs_onboarding), the stack detected across the full Claude Code history with per-project provenance, the default topics and the notebook_path. Same data as the devcoach://onboarding resource.",inputSchema:z.object({}),annotations:p$1("Onboarding Status & Detected Stack")},()=>F("get_onboarding",Ge())),o$2.registerTool("get_profile",{title:"Knowledge Profile",description:"Current knowledge map: topics with confidence 0\u201310 and their groups. Same data as the devcoach://profile resource.",inputSchema:z.object({}),outputSchema:Ie,annotations:p$1("Knowledge Profile")},()=>F("get_profile",$e())),o$2.registerTool("share_lesson",{title:"Share Lesson",description:"Hand a lesson to another person. transport 'text' (default) returns the card plus a one-line code to paste anywhere; 'link' a server-less URL that previews the lesson and imports it into their dashboard; 'file' the contents of a .devcoach.md file. Only title, summary, body, topic, categories and level travel unless include_context is true; local paths never do. Pick the lesson with get_lessons first.",inputSchema:z.object({lesson_id:z.string().describe("Lesson id (from get_lessons)"),transport:z.enum(["text","link","file"]).default("text").describe("text = card + code to paste; link = share URL; file = .devcoach.md contents"),include_context:z.boolean().default(false).describe("Include project/branch/commit/task context (off by default \u2014 privacy). Local paths are never included."),shared_by:z.string().nullish().describe("Sender name. Omit \u2192 the share_name setting, then git user.name. Empty string \u2192 anonymous.")}),outputSchema:Ze,annotations:p$1("Share Lesson")},t=>{try{let n$1=A(r=>{let i=K(r,t.lesson_id);if(!i)return null;let c=pa({explicit:t.shared_by??null,setting:T(r).share_name,gitUserName:n()});return oa(i,{includeContext:t.include_context,sharedBy:c})});return n$1?b({transport:t.transport,code:qa(n$1),text:t.transport==="text"?sa(n$1):null,link:t.transport==="link"?ta(n$1):null,markdown:t.transport==="file"?wa(n$1):null,filename:t.transport==="file"?va(n$1):null,shared_by:n$1.shared_by,include_context:t.include_context,reply_check:tt[t.transport]}):a(`share_lesson: lesson '${t.lesson_id}' not found \u2014 call get_lessons to pick one`)}catch(n){return a(`share_lesson failed: ${n}`)}}),o$2.registerTool("import_lesson",{title:"Import Lesson",description:"Store a lesson someone shared. Pass whatever the user handed you, verbatim: the devcoach:lesson:1:\u2026 code, the whole copied card, the share link, a URL to the lesson text, the contents of a .devcoach.md file, or a lessons JSON export. The lesson joins the coaching log as their own (feedback works as usual) but never counts against the daily limit; re-importing the same share is reported as a duplicate, not an error.",inputSchema:z.object({payload:z.string().min(1).describe("The code, link, URL, card text, file text or JSON \u2014 verbatim")}),outputSchema:et,annotations:{title:"Import Lesson",destructiveHint:false,idempotentHint:true,openWorldHint:true}},async t=>{try{let n=p(t.payload)&&!t.payload.includes("#devcoach:lesson:")?await q(t.payload):t.payload,r=A(i=>Ca(i,n));return b({...r,reply_check:nt})}catch(n){return n instanceof na?a(`import_lesson: ${n.message}`):a(`import_lesson failed: ${n}`)}});let m=z.object({course_id:z.string(),position:z.number().int(),title:z.string(),kind:j,anchor:z.string(),status:k,done_at:z.string().nullable()}),g=z.object({id:z.string(),lesson_id:z.string().nullable(),topic_id:z.string(),title:z.string(),goal:z.string().nullable(),prerequisites:z.array(z.object({concept:z.string(),known:z.boolean()})),status:i,created_at:z.string(),updated_at:z.string(),completed_at:z.string().nullable(),steps:z.array(m)}),f='Write ONE self-contained HTML document at document_path (inline CSS + JS, no external URLs, no fetch, no <form>, no alert/confirm/prompt) with one <section id="step-N"> per step, using your file tools \u2014 never paste HTML into the chat. Then register every section with add_course_step (position order, anchor = the section id). Teach one step per message and tell the user the course is on the dashboard under Courses (/devcoach:ui).';o$2.registerTool("create_course",{title:"Create Course",description:"Start a step-by-step course, usually from a lesson the user couldn't follow. Pass the prerequisite chain you explored ([{concept, known}], top-down). Returns the course row, course_dir and document_path \u2014 write the document there yourself, then call add_course_step for each section.",inputSchema:z.object({title:z.string().min(1).describe("Course title, e.g. 'From sums to logarithms'"),topic_id:z.string().min(1).describe("The lesson-style topic id the course belongs to"),goal:z.string().nullish().describe("One sentence: what the user will be able to do"),lesson_id:z.string().nullish().describe("The seed lesson's id, when the course grows from one"),prerequisites:z.array(z.object({concept:z.string().min(1),known:z.boolean()})).default([]).describe("The explored chain, top-down: [{concept, known}]")}),outputSchema:g.extend({course_dir:z.string(),document_path:z.string(),seed_context:z.object({task_context:z.string().nullable(),project:z.string().nullable(),repository:z.string().nullable(),branch:z.string().nullable()}).nullable(),reply_check:z.string()}),annotations:{title:"Create Course",destructiveHint:false,idempotentHint:false,openWorldHint:false}},async t=>{try{let n=A(r=>{let i=t.lesson_id?K(r,t.lesson_id):null;if(t.lesson_id&&!i)throw new b$2(`lesson '${t.lesson_id}' not found \u2014 call get_lessons to pick one`);return {course:f$1(r,{title:t.title,topic_id:t.topic_id,goal:t.goal??null,lesson_id:t.lesson_id??null,prerequisites:t.prerequisites}),seed:i}});return b({...n.course,course_dir:c$1(n.course.id),document_path:d$3(n.course.id),seed_context:n.seed?{task_context:n.seed.task_context,project:n.seed.project,repository:n.seed.repository,branch:n.seed.branch}:null,reply_check:f})}catch(n){return a(`create_course failed: ${n}`)}}),o$2.registerTool("add_course_step",{title:"Add Course Step",description:"Register a step of a course: the section with id=<anchor> must already exist in the course document. Appended by default; pass `after` to insert it after that step (0 = first) \u2014 the following steps are renumbered.",inputSchema:z.object({course_id:z.string().describe("Course id (from create_course)"),title:z.string().min(1).describe("Step title"),kind:j.describe("concept | example | practice | check"),anchor:z.string().regex(/^[a-z0-9][a-z0-9-]*$/).describe("The section's id in the document, e.g. step-1"),after:z.number().int().min(0).nullish().describe("Insert after this step number (0 = first); omit to append")}),outputSchema:g.extend({step:m}),annotations:{title:"Add Course Step",destructiveHint:false,idempotentHint:false,openWorldHint:false}},async t=>{try{let n=A(r=>{let i=i$1(r,t.course_id,{title:t.title,kind:t.kind,anchor:t.anchor,after:t.after});return {...g$1(r,t.course_id),step:i}});return b(n)}catch(n){return a(`add_course_step failed: ${n}`)}}),o$2.registerTool("update_course_progress",{title:"Update Course Progress",description:"With position: set that step to todo | done | skipped (the course completes itself once every step is done or skipped). Without position: set the course to active | completed | abandoned.",inputSchema:z.object({course_id:z.string().describe("Course id"),position:z.number().int().min(1).nullish().describe("Step number (1-based); omit for the course"),status:z.string().describe("Step: todo | done | skipped \u2014 course: active | completed | abandoned")}),outputSchema:g,annotations:{title:"Update Course Progress",destructiveHint:false,idempotentHint:true,openWorldHint:false}},async t=>{try{let n=A(r=>{if(t.position!=null){let i=k.parse(t.status);return j$1(r,t.course_id,t.position,i)}return k$1(r,t.course_id,i.parse(t.status))});return n?b(n):a(`update_course_progress: course '${t.course_id}'${t.position!=null?` step ${t.position}`:""} not found \u2014 call get_courses`)}catch(n){return a(`update_course_progress failed: ${n}`)}}),o$2.registerTool("get_courses",{title:"Get Courses",description:"List courses with their steps and progress; filter by id, seed lesson or status. 'continue the course' = status active.",inputSchema:z.object({course_id:z.string().nullish().describe("One course"),lesson_id:z.string().nullish().describe("Courses seeded by this lesson"),status:i.nullish().describe("active | completed | abandoned")}),outputSchema:z.object({courses:z.array(g.extend({course_dir:z.string()}))}),annotations:p$1("Get Courses")},t=>{try{let n=A(r=>{if(t.course_id){let i=g$1(r,t.course_id);return i?[i]:[]}return h$1(r,{lesson_id:t.lesson_id,status:t.status})});return b({courses:n.map(r=>({...r,course_dir:c$1(r.id)}))})}catch{return b({courses:[]})}});let l$1=(t,n)=>({title:t,description:n,mimeType:"application/json"});return o$2.registerResource("profile","devcoach://profile",l$1("Knowledge Profile","Current knowledge map \u2014 topics, confidence scores, and groups."),t=>u(t,$e())),o$2.registerResource("notebook","devcoach://notebook",{title:"Coaching Notebook",description:"The coaching notebook (learning-state.md): observations, recurring patterns, recommended focus, and open hypotheses about the user. Read it to decide what to teach.",mimeType:"text/markdown"},t=>{let n="";try{existsSync(o$1)&&(n=readFileSync(o$1,"utf8"));}catch{}return {contents:[{uri:t.href,mimeType:"text/markdown",text:n}]}}),o$2.registerResource("settings","devcoach://settings",l$1("Settings","Current coaching settings (rate limits, UI theme)."),t=>{try{return u(t,A(n=>T(n)))}catch(n){return u(t,{error:String(n)})}}),o$2.registerResource("recent-lessons","devcoach://lessons/recent",l$1("Recent Lessons","Last 10 lessons from the current week."),t=>{try{return u(t,A(n=>D(n,{period:"week",page:1,per_page:10})))}catch(n){return u(t,[{error:String(n)}])}}),o$2.registerResource("stats","devcoach://stats",l$1("Stats","Aggregate coaching statistics: counts and weakest/strongest topics."),t=>{try{return u(t,A(n=>Ba(n)))}catch(n){return u(t,{error:String(n)})}}),o$2.registerResource("taught-topics","devcoach://taught-topics",l$1("Taught Topics","All topic_ids already taught \u2014 read before selecting a new lesson topic."),t=>{try{return u(t,A(n=>Da(n)))}catch{return u(t,[])}}),o$2.registerResource("rate-limit","devcoach://rate-limit",l$1("Rate Limit","Current rate-limit status and running lesson total."),t=>{try{let{r:n,total:r}=A(c=>({r:xa(c),total:C(c)})),i={allowed:n.allowed,total_lessons:r};return n.reason!=null&&(i.reason=n.reason),u(t,i)}catch(n){return u(t,{allowed:false,reason:`Rate limit check unavailable: ${n}`})}}),o$2.registerResource("briefing","devcoach://briefing",l$1("Lesson Briefing","Everything needed before delivering a lesson in ONE read: onboarding status, rate limit, taught topics, knowledge profile, and the coaching notebook."),t=>u(t,Ue())),o$2.registerResource("context","devcoach://context",l$1("Workspace Context","Auto-detected git context and most-used lesson metadata defaults."),t=>{try{let n=o(),r=A(i=>_(i));return u(t,{git:n,usage_defaults:r})}catch(n){return u(t,{error:String(n)})}}),o$2.registerResource("onboarding","devcoach://onboarding",l$1("Onboarding","Onboarding status, the stack detected across the full Claude Code history (with per-project provenance), and project topic defaults."),t=>u(t,Ge())),o$2.registerResource("lesson",new ResourceTemplate("devcoach://lessons/{lesson_id}",{list:void 0}),l$1("Lesson","A single lesson by id."),(t,n)=>{try{let r=String(n.lesson_id),i=A(c=>K(c,r));return i?u(t,i):u(t,{error:`Lesson '${r}' not found`})}catch(r){return u(t,{error:String(r)})}}),o$2.registerPrompt("devcoach_instructions",{title:"devcoach coaching instructions",description:"Full coaching instructions for the devcoach skill (SKILL.md plus its reference files)."},()=>{let t=f$2().map(n=>`
4
+
5
+ ---
6
+
7
+ <!-- reference: ${n.name} -->
8
+
9
+ ${n.content}`).join("");return {messages:[{role:"user",content:{type:"text",text:e$1()+t}}]}}),o$2}async function St(){let o=rt(),p=new StdioServerTransport;await o.connect(p);}export{rt as createServer,St as runStdio};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devcoach",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "mcpName": "io.github.UltimaPhoenix/devcoach",
5
5
  "description": "Stay sharp while your AI does the work — learn from every task with in-context coaching, all local, all free",
6
6
  "license": "AGPL-3.0-only",
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env node
2
- import {m as m$1,u,T as T$1,da,Aa,l as l$1,t,za}from'./chunk-RUBF2HCU.js';import {existsSync,mkdirSync,statSync,writeFileSync,appendFileSync,fstatSync,readFileSync}from'fs';import {join}from'path';function A(e){try{let o=JSON.parse(e);return {stop_hook_active:o?.stop_hook_active===!0,permission_mode:typeof o?.permission_mode=="string"?o.permission_mode:null,session_id:typeof o?.session_id=="string"?o.session_id:null}}catch{return {stop_hook_active:false,permission_mode:null,session_id:null}}}function l(){let e={stop_hook_active:false,permission_mode:null,session_id:null};try{let o=fstatSync(0);return !o.isFIFO()&&!o.isFile()&&!o.isSocket()?e:A(readFileSync(0,"utf8"))}catch{return e}}function N(e){return e.stop_hook_active||e.permission_mode==="plan"}function s(e,o,t){if(process.env.DEVCOACH_HOOK_DEBUG==="1")try{mkdirSync(l$1,{recursive:!0});let n=join(l$1,"hook.log");existsSync(n)&&statSync(n).size>256*1024&&writeFileSync(n,""),appendFileSync(n,`${new Date().toISOString()} ${e} ${(o??"-").slice(0,8)} ${t}
3
- `);}catch{}}var $={claude:"block",gemini:"deny",codex:"block"};function h(e,o,t){let n={decision:$[e],reason:o};t&&(n.systemMessage=t),process.stdout.write(`${JSON.stringify(n)}
4
- `),process.exit(0);}var b="devcoach: the user has no coaching profile yet. Ask them how they want to set it up and STRONGLY recommend Automatic \u2014 devcoach scans their full Claude Code history across all their projects (call get_onboarding for the detected stack and per-project evidence) so the profile reflects what they actually build. Also offer Guided (a short conversation to map topics and confidence levels) and Import (restore from a backup), but lead with Automatic; do not pick for them. After they choose, build the profile and save it by calling the devcoach `complete_onboarding` MCP tool (not a shell command) before ending your turn.";function E(e=l()){if(N(e)&&process.exit(0),existsSync(m$1)){let o;try{o=u(t=>T$1(t).knowledge_ready);}catch(t){s("onboard-hook",e.session_id,`error: ${t}`),process.exit(0);}o&&process.exit(0);}s("onboard-hook",e.session_id,"onboarding cue"),h("claude",b);}var a=10,y={claude:{cue:"Invoke the `devcoach` skill (Skill tool)",prime:"invoke the `devcoach` skill (Skill tool)"},gemini:{cue:"Activate the `devcoach` skill (activate_skill tool)",prime:"activate the `devcoach` skill (activate_skill tool)"},codex:{cue:"Activate the `devcoach` skill",prime:"activate the `devcoach` skill"}};function I(e,o="claude"){let t=e%a===0,n=Math.ceil(e/a)*a,i=t?`This is lesson #${e} \u2014 a notebook checkpoint (every ${a} lessons): after log_lesson returns the feedback, also read references/calibration.md in the devcoach skill and run its notebook-update step (a direct file write), recording "(updated after ${e} lessons)".`:`Skip the notebook update this time \u2014 it is refreshed only every ${a} lessons (next checkpoint at lesson #${n}).`;return `devcoach: a lesson is due for the technical work just completed. Do it now \u2014 do not acknowledge this message and do not explain what you are about to do.
5
-
6
- ${y[o].cue} NOW and follow it exactly \u2014 the skill is the single source of truth for the entire flow, including the explicit no-op when the completed work does not warrant a lesson.
7
- ${i}
8
-
9
- If the devcoach skill is not available, fall back to: call get_briefing (one call: profile, taught topics, notebook); pick ONE untaught profile topic at or above the user's confidence band; call log_lesson silently (body = 3\u20136 short paragraphs tied to the task plus a \`\u{1F4A1} *Senior tip:*\` line, clean markdown without bands or a title line); THEN write the card as the FINAL message of the turn: plain markdown (no '>' blockquote) between two band headings \`### \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u{1F393} devcoach \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\` and \`### \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 [topic] \xB7 [level] \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\`, with \`**[Title]** \xB7 [Category] \xB7 [Level]\`, the body you passed, and the tip \u2014 saving is not showing; the card in the final message is the only thing the user sees. If instead the work does not warrant a lesson (pure questions, chat, nothing technical), call the devcoach \`skip_lesson\` tool with a one-line reason.
10
-
11
- The rate-limit check is already done by this hook \u2014 skip it. Work in silence: never narrate devcoach tool calls or resource reads ('checking your profile\u2026'). Output only the lesson card (or nothing). No preamble, no meta-commentary.`}function T(e,o,t){let n=o.permission_mode==="plan";if(o.stop_hook_active)return {kind:"silent",note:"hook-forced continuation"};if(!T$1(e).knowledge_ready)return !t.onboardCue||n?{kind:"silent",note:"onboarding not complete"}:{kind:"onboard",note:"onboarding cue (empty knowledge)"};if(da(e))return {kind:"silent",note:"course in progress \u2014 cues paused"};let i=za(e,o.session_id,{planMode:n});return i.cue?{kind:"cue",nextLessonNumber:i.nextLessonNumber,note:i.reason}:{kind:"silent",note:i.reason}}function w(e,o,t$1){let n;try{n=u(i=>t(i,()=>T(i,o,t$1)));}catch(i){s(e,o.session_id,`error: ${i}`),process.exit(0);}switch(s(e,o.session_id,n.note),n.kind){case "onboard":h(t$1.client,b);break;case "cue":h(t$1.client,I(n.nextLessonNumber,t$1.client),"\u{1F393} devcoach: checking whether a lesson is due\u2026");break;}process.exit(0);}function R(e=l()){existsSync(m$1)||process.exit(0),w("lesson-ready",e,{onboardCue:false,client:"claude"});}function m(e=l(),o="claude"){let t=o==="claude"?"stop-hook":`${o}-stop-hook`;existsSync(m$1)||((e.stop_hook_active||e.permission_mode==="plan")&&process.exit(0),s(t,e.session_id,"onboarding cue (no DB)"),h(o,b)),w(t,e,{onboardCue:true,client:o});}function B(e="claude"){return `devcoach: the lesson pacing threshold will be reached at the end of this turn. Resolve it before finishing:
12
- - If this task is technical: ${y[e].prime} and follow it exactly to close your reply \u2014 the skill is the single source of truth for the entire lesson flow.
13
- - If it is not technical: silently call the devcoach \`skip_lesson\` tool with a one-line reason and output nothing about it.
14
- - Either way, work in silence: never narrate devcoach tool calls or resource reads ('checking your profile\u2026').`}var L={claude:"UserPromptSubmit",gemini:"BeforeAgent",codex:"UserPromptSubmit"};function f(e=l(),o="claude"){let t=o==="claude"?"prompt-hook":`${o}-prompt-hook`;e.permission_mode==="plan"&&process.exit(0),existsSync(m$1)||process.exit(0);let n;try{n=u(i=>!da(i)&&Aa(i,e.session_id).wouldCue);}catch(i){s(t,e.session_id,`error: ${i}`),process.exit(0);}s(t,e.session_id,n?"priming":"no prime"),n||process.exit(0),process.stdout.write(`${JSON.stringify({hookSpecificOutput:{hookEventName:L[o],additionalContext:B(o)}})}
15
- `),process.exit(0);}function j(e,o){let t=()=>o??l();switch(e){case "stop-hook":m(t());break;case "gemini-stop-hook":m(t(),"gemini");break;case "codex-stop-hook":m(t(),"codex");break;case "prompt-hook":f(t());break;case "gemini-prompt-hook":f(t(),"gemini");break;case "codex-prompt-hook":f(t(),"codex");break;case "onboard-hook":E(t());break;case "lesson-ready":R(t());break;default:process.exit(0);}}export{A as a,E as b,I as c,R as d,m as e,B as f,f as g,j as h};