@lovek4d/kickflip 0.5.0 → 0.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.
Files changed (110) hide show
  1. package/CONTEXT.md +105 -68
  2. package/README.md +1 -1
  3. package/SKILL.md +27 -21
  4. package/bin/kickflip.mjs +27 -18
  5. package/bin/wait-events.mjs +2 -2
  6. package/board/agents.mjs +2 -0
  7. package/board/arch-review.mjs +4 -4
  8. package/board/bin/board.mjs +199 -79
  9. package/board/build-script.mjs +2 -1
  10. package/board/domain.mjs +9 -7
  11. package/board/finish.mjs +4 -4
  12. package/board/headless.mjs +9 -4
  13. package/board/on-host.mjs +1 -1
  14. package/board/onboarding.mjs +11 -0
  15. package/board/prototype-base.mjs +1 -0
  16. package/board/prototype-page.mjs +1 -0
  17. package/board/public/app-arch.js +1 -1
  18. package/board/public/app-asks.js +6 -6
  19. package/board/public/app-banner.js +7 -13
  20. package/board/public/app-cards.js +75 -37
  21. package/board/public/app-core.js +26 -8
  22. package/board/public/app-header.js +8 -8
  23. package/board/public/app-lanes.js +67 -58
  24. package/board/public/app-needs.js +140 -10
  25. package/board/public/app-reader.js +1 -1
  26. package/board/public/app-snapshot.js +46 -72
  27. package/board/public/app-threads.js +78 -75
  28. package/board/public/app.html +9 -4
  29. package/board/public/app.js +114 -38
  30. package/board/public/attach.js +2 -2
  31. package/board/public/dialogs.js +9 -39
  32. package/board/public/hub-kit.js +66 -4
  33. package/board/public/hub.css +2 -0
  34. package/board/public/linear-key.js +46 -35
  35. package/board/public/new-task.js +20 -39
  36. package/board/public/progress-review.html +46 -0
  37. package/board/public/progress-review.js +158 -0
  38. package/board/public/prototype-kit.js +137 -7
  39. package/board/public/prototype-switcher.js +152 -123
  40. package/board/public/prototype.html +57 -3
  41. package/board/public/router.js +7 -6
  42. package/board/public/shell.js +68 -26
  43. package/board/public/sidebar.css +1 -0
  44. package/board/public/sidebar.js +16 -30
  45. package/board/public/style.css +205 -83
  46. package/board/public/ui-cards.js +91 -65
  47. package/board/public/ui-enums.js +1 -1
  48. package/board/public/ui-header.js +27 -18
  49. package/board/public/ui-hub.js +12 -1
  50. package/board/public/ui-links.js +7 -7
  51. package/board/public/ui-order.js +12 -10
  52. package/board/public/ui-page-header.js +19 -7
  53. package/board/public/ui-patch.js +7 -33
  54. package/board/public/ui-progress-bar.js +28 -0
  55. package/board/public/ui-questions.js +47 -52
  56. package/board/public/ui-sidebar.js +34 -26
  57. package/board/public/ui-snapshot.js +43 -52
  58. package/board/public/ui-threads.js +59 -30
  59. package/board/public/ui.js +125 -18
  60. package/board/public/view-hub-settings.js +22 -67
  61. package/board/public/view-hub.js +19 -4
  62. package/board/public/view-notes.js +27 -7
  63. package/board/public/view-questions.js +205 -240
  64. package/board/public/view-settings.js +313 -76
  65. package/board/render-check.mjs +10 -0
  66. package/board/review.mjs +1 -1
  67. package/board/server.mjs +19 -20
  68. package/board/stop.mjs +1 -0
  69. package/board/store.mjs +29 -15
  70. package/board/sync.mjs +2 -0
  71. package/board/tickets.mjs +3 -3
  72. package/board/transcript.mjs +2 -0
  73. package/board/worktree.mjs +25 -20
  74. package/hooks-plugin/hooks/board-data-gate.mjs +50 -0
  75. package/hooks-plugin/hooks/hooks.json +9 -0
  76. package/hooks-plugin/hooks/usage-gate.mjs +20 -3
  77. package/hub/board-repo.mjs +1 -1
  78. package/hub/boards.mjs +4 -4
  79. package/hub/front-door.mjs +5 -5
  80. package/hub/github.mjs +3 -3
  81. package/hub/hub.mjs +11 -11
  82. package/hub/incoming.mjs +2 -2
  83. package/hub/linear.mjs +1 -2
  84. package/hub/live.mjs +2 -2
  85. package/hub/locks.mjs +1 -1
  86. package/hub/owner-checks.mjs +1 -1
  87. package/hub/pr-report.mjs +2 -2
  88. package/hub/presence.mjs +1 -1
  89. package/hub/push.mjs +2 -2
  90. package/hub/readiness.mjs +1 -2
  91. package/hub/review-send.mjs +1 -0
  92. package/hub/secrets.mjs +2 -0
  93. package/hub/self-restart.mjs +2 -0
  94. package/hub/sessions.mjs +2 -2
  95. package/hub/share.mjs +1 -0
  96. package/hub/slack.mjs +2 -2
  97. package/hub/stream.mjs +10 -13
  98. package/hub/try.mjs +7 -7
  99. package/hub/upgrade.mjs +1 -1
  100. package/hub/usage.mjs +3 -3
  101. package/hub/views.mjs +1 -1
  102. package/package.json +2 -1
  103. package/shared/audit.mjs +4 -0
  104. package/shared/card-prs.mjs +1 -1
  105. package/shared/fake-gh.mjs +17 -4
  106. package/shared/machine-gate.mjs +2 -0
  107. package/shared/prototype-frame.js +1 -0
  108. package/shared/service.mjs +4 -4
  109. package/shared/usage-gate.mjs +1 -1
  110. package/board/public/ui-phase-bars.js +0 -17
package/bin/kickflip.mjs CHANGED
@@ -37,7 +37,7 @@
37
37
  // --template board runs the shared board (../board/server.mjs) from the site dir,
38
38
  // writing its board.json; --items is "waves" (default) or a wave.json-format file, made with no
39
39
  // items when missing.
40
- // It then runs handshake, unless this session already answered the board's hello, and
40
+ // It then runs handshake, unless this session already answered the board's ping, and
41
41
  // asks the hub for one poll (as poll-now --keep-queue), so the board's GitHub link passes
42
42
  // without waiting for the next slot. Prints poll: "reached this board", or why not
43
43
  // --icon names a line icon from ../hub/icons.mjs and --color tints it in the
@@ -88,9 +88,9 @@
88
88
  // kickflip sessions [--json]
89
89
  // one line per board: route, session id, live (background or terminal) or not, folder
90
90
  // kickflip handshake <route>
91
- // tests a board's hub links (../hub/boards.mjs handshake): appends a `hello` event, which the
92
- // owning session's watcher answers when it prints it. The board shows a setup checklist
93
- // until the watcher answered and the hub's GitHub check reached it. Prints {route, hello}
91
+ // tests a board's hub links (../hub/boards.mjs handshake): appends a `ping` event, which the
92
+ // owning session's watcher answers when it sees it. The board shows a setup checklist
93
+ // until the watcher answered and the hub's GitHub check reached it. Prints {route, ping}
94
94
  // kickflip set <route> [--icon <key>] [--color <hex>] [--hub | --no-hub]
95
95
  // changes an existing site's icon or color without joining; '' clears one. --hub makes the board the
96
96
  // hub board, whose session runs in tmux and `hub` attaches to (`hub: true` in its entry), clearing the flag from any other
@@ -101,7 +101,8 @@
101
101
  // prints the hub's HTTPS address on the tailnet, the one to open on the phone, or with a route that
102
102
  // site's (./install.mjs tailnetUrl). Exit 1 when Tailscale isn't installed or running, or HTTPS isn't on for the tailnet,
103
103
  // 2 for a route with no site
104
- // kickflip restart <route>
104
+ // kickflip restart [route]
105
+ // restarts the site at that route; with no route, restarts the hub through its service
105
106
  // kickflip logs <route> [--lines <n>]
106
107
  // kickflip init [--dry-run] | uninstall
107
108
  // init is the first-run name for doctor --fix. It links the running package or clone, hooks plugin
@@ -112,8 +113,10 @@
112
113
  // --dry-run prints what init would move, link and start, and changes nothing.
113
114
  // uninstall stops the hub and removes its service, kickflip's status-line link and Tailscale /;
114
115
  // Claude settings and skill links are kept
115
- // kickflip update
116
- // installs @lovek4d/kickflip@latest globally with npm, then restarts the hub.
116
+ // kickflip update [--no-restart]
117
+ // installs @lovek4d/kickflip@latest globally with npm. When the version changed it prints
118
+ // "<old> > <new>" and restarts the hub; otherwise it prints "no new version available" and leaves the hub running.
119
+ // --no-restart leaves the hub running on its old code (the hub pulls this way, then restarts itself).
117
120
  // A clone refuses (exit 2); update it with git pull
118
121
  // kickflip push --kind action|prompt|fault|reminder --title <t> [--body <b>] [--url </route/path>] [--tag <tag>]
119
122
  // [--now | --urgent]
@@ -124,7 +127,7 @@
124
127
  // news stays on the board.
125
128
  // The push queues, replacing a queued one with the same
126
129
  // --tag, and goes out after the hub's next GitHub check, every minute while the owner is here
127
- // and every 5 while away, or when a GitHub tick ends (board.mjs checked); a board's
130
+ // and every 5 while away; a board's
128
131
  // several queued pushes go as one summary. --now sends at once unless pushes are held
129
132
  // (quiet hours, snoozed or the weekend), and queues if no device takes it; it is for questions,
130
133
  // steps only the owner can run and prototypes. --urgent sends at once through
@@ -148,15 +151,20 @@
148
151
  // prints {pause_at, state, window, used, resets_at, codex: {past, window, used, resets_at}}; a read exits 0.
149
152
  // pause-at saves the line in steps of 5 (default 90, 100 Off); keep-going lifts the current Claude pause
150
153
  // until its window resets; stop restores it. Codex hands work to Opus past the same line.
154
+ // kickflip audit
155
+ // prints the hub's audit log of the last 30 days (~/.claude/kickflip/audit.jsonl): each call the hub's code
156
+ // made on its own for no one board (usage-pause, usage-resume, linear-move) as
157
+ // "<at> <call> [<ticket>]: <result>. <reason>" and the inputs it read. A board's own calls are in its
158
+ // data/audit.jsonl: board.mjs --site <route> audit (docs/adr/2026-11-05-0913-the-hub-and-each-board-keep-an-audit-log-of-the-calls-their-code-makes.md)
151
159
  // kickflip poll-now [--keep-queue]
152
160
  // asks the hub for one poll now (GitHub check, github-change events,
153
161
  // checked.json, then the queue unless --keep-queue) and prints its result
154
162
  // Exit codes: 0 ok, 1 error, 2 bad usage, 3 route owned by another session (join/leave), or its recorded session is
155
163
  // live (start/resume/hub). hub passes through claude's exit code.
156
- var xe=Object.defineProperty;var p=(e,t)=>xe(e,"name",{value:t,configurable:!0});import w from"node:fs";import u from"node:path";import L from"node:os";import ie from"node:net";import _e from"node:readline/promises";import{execFileSync as re,spawnSync as K}from"node:child_process";import{fileURLToPath as Ne}from"node:url";import{ICON_KEYS as ae}from"../hub/icons.mjs";import{liveSessions as ce}from"../hub/live.mjs";import{isBoardSite as P,writeManifest as v}from"../hub/boards.mjs";import{joinName as Te,routeFromName as F,routeRecord as g,validRoute as C}from"../hub/routes.mjs";import{defaultBranch as Ie,githubFromOrigin as Fe}from"../hub/repos.mjs";import{uninstallStatusLine as Ce,storedPath as Re,nodeBin as U,watcherCommand as Ee,tailnetUrl as Be}from"./install.mjs";import{hubService as de}from"../shared/service.mjs";import{tailscaleBin as ue}from"../shared/tailscale.mjs";import{runDoctor as De}from"./doctor.mjs";import{cloneRoot as Le}from"../shared/repos.mjs";const j=Le(),_=u.join(L.homedir(),".claude","kickflip"),Pe=u.join(_,"manifest.json"),le=u.join(_,"logs"),T=Number(process.env.KICKFLIP_HUB_PORT||4500),G=4600,Ae=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,[W,...S]=process.argv.slice(2),s=Object.assign(Object.create(null),{_:[]});for(let e=0;e<S.length;e++){const t=S[e];if(t.startsWith("--")){const n=t.slice(2);n==="fix"||n==="force"||n==="json"||n==="urgent"||n==="now"||n==="keep-queue"||n==="hub"||n==="no-hub"||n==="dry-run"||n==="watch"&&(e+1>=S.length||S[e+1].startsWith("--"))?s[n]=!0:s[n]=S[++e]}else s._.push(t)}const h=p(e=>console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),"out");class I extends Error{static{p(this,"Exit")}constructor(t,n){super(t),this.code=n}}const i=p((e,t=1)=>{throw new I(e,t)},"fail");function Y(){s.icon&&!ae.includes(s.icon)&&i(`--icon takes one of: ${ae.join(", ")}`,2),s.color&&!Ae.test(s.color)&&i("--color takes a CSS hex color, such as #3b82f6",2)}p(Y,"checkLook");function Q(e){for(const t of["icon","color"])s[t]===""?delete e[t]:s[t]!==void 0&&(e[t]=s[t])}p(Q,"applyLook");const fe=p(()=>s.hub&&s["no-hub"]&&i("pass --hub or --no-hub, not both",2),"checkHub"),he=p(e=>i(`/${e} is not a board; only a board can be the hub board`,2),"notBoard");function X(e,t,n){if(s["no-hub"]&&delete n.hub,!!s.hub){P(n)||he(t);for(const[o,l]of Object.entries(e.sites))o!==t&&l?.hub&&delete l.hub;n.hub=!0}}p(X,"applyHub");function y(){try{const e=JSON.parse(w.readFileSync(Pe,"utf8"));return e.sites||={},e}catch(e){if(e.code==="ENOENT")return{version:1,sites:{}};i("manifest unreadable: "+e.message)}}p(y,"readManifest");const pe=p(e=>{try{return JSON.parse(w.readFileSync(e,"utf8"))}catch{return null}},"readJSON"),R=p(()=>import(u.join(j,"hub","sessions.mjs")),"sessionsModule");async function A(e){const{SessionError:t}=await R();try{return await e()}catch(n){throw n instanceof t&&i(n.message,n.reason==="live"?3:n.reason==="hub"?2:1),n}}p(A,"sessionCall");async function me(e){const{handshake:t}=await import(u.join(j,"hub","boards.mjs"));try{return await t(e,y())}catch(n){return i(n.message,2)}}p(me,"runHandshake");async function Je(e){for(let t=0;t<2;t++){let n;try{n=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!1}),signal:AbortSignal.timeout(5*6e4)})}catch(l){return`not run (${l.message})`}if(!n.ok)return`not run (the hub answered ${n.status})`;const o=await n.json();if(o.checked?.includes(e))return"reached this board";if(o.failed?.length)return`missed this board: ${o.failed[0]}`}return"missed this board"}p(Je,"pollFor");async function O(e){const{withManifestLock:t}=await import(u.join(j,"hub","boards.mjs"));try{return await t(e)}catch(n){throw n.code==="ELOCKED"&&i(n.message),n}}p(O,"withLock");function we(e){return new Promise(t=>{const n=ie.connect({port:e,host:"127.0.0.1"}),o=p(l=>{n.destroy(),t(l)},"done");n.setTimeout(500,()=>o(!1)),n.on("connect",()=>o(!0)),n.on("error",()=>o(!1))})}p(we,"connects");function He(e){return new Promise(t=>{const n=ie.createServer();n.once("error",()=>t(!1)),n.listen(e,"0.0.0.0",()=>n.close(()=>t(!0)))})}p(He,"bindable");async function J(e){const t=new Set([...Object.values(e.sites),...Object.values(e.closed||{}).map(n=>n.site)].map(n=>n?.port));for(let n=G;n<G+400;n++)if(!t.has(n)&&!await we(n)&&await He(n))return n;i("no free port found from "+G)}p(J,"freePort");function qe(){const e=ue();if(!e)return"";try{return(JSON.parse(re(e,["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})).Self?.DNSName||"").replace(/\.$/,"")}catch{return""}}p(qe,"tailnetHost");const Z=p(e=>{const t=qe();return t?`https://${t}/${e}/`:`http://127.0.0.1:${T}/${e}/`},"siteUrl");async function H(){try{return await(await fetch(`http://127.0.0.1:${T}/_hub/status.json`,{signal:AbortSignal.timeout(1500)})).json()}catch{return null}}p(H,"hubStatus");const ge=p(e=>{try{return w.statSync(e).isDirectory()}catch{return!1}},"isFolder"),ze=p(e=>{try{return w.realpathSync(e)}catch{return null}},"realPath");function be(e=t=>{}){(typeof s.name!="string"||!s.name.trim())&&i('join needs --name "<name>": the board or page name, which gives its route',2);const t=s.name.trim().replace(/\s+/g," "),n=F(t);return C(n)||i(`--name "${t}" needs a letter or digit for its route`,2),{route:n,title:t===n&&e(n)?.title||t}}p(be,"named");function ye(e,{title:t,items:n,tickets:o}){w.mkdirSync(u.join(e,"data"),{recursive:!0});const l=u.join(e,"board.json"),c=w.existsSync(l)?JSON.parse(w.readFileSync(l,"utf8")):{};c.title=t,c.items=Re(n||c.items||"waves"),o&&(c.tickets=o),w.writeFileSync(l,JSON.stringify(c,null,2)+`
157
- `);const r=c.items==="waves"?null:u.resolve(e,c.items);return r&&!w.existsSync(r)&&(w.mkdirSync(u.dirname(r),{recursive:!0}),w.writeFileSync(r,JSON.stringify({title:c.title,items:[]},null,2)+`
158
- `)),[U(),u.join(j,"board","server.mjs"),e]}p(ye,"boardFiles");async function V(e,t){const{startSession:n,withSessionLock:o}=await R();return o(e,async()=>{const l=await A(()=>n(e,{manifest:y(),...t}));return await O(async()=>{const c=y(),r={session:l.session,label:l.name,since:new Date().toISOString(),repo:l.repo,...l.model?{model:l.model}:{}};g(c.sites,e)?(c.sites[e].owner=r,c.sites[e].updated=r.since):c.starting={...c.starting,[e]:{...g(c.starting,e),...r}},await v(c)}),l})}p(V,"startRecorded");async function q(e){const{hubSession:t}=await R(),n=await A(()=>t({manifest:y(),repo:e}));process.exitCode=n.status}p(q,"openHub");const ke=p((e,...t)=>{const n=K("git",["-C",e,...t],{encoding:"utf8"});return n.status===0?n.stdout.trim():null},"git"),ee=p(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"canAsk");async function te(e,t="stopped at the prompt; nothing changed"){const n=_e.createInterface({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()}catch(o){throw o.code==="ABORT_ERR"&&i(t),o}finally{n.close()}}p(te,"ask");const Se=p((e,t)=>!!(g(e.sites,t)||g(e.starting,t)||g(e.closed,t)),"taken");function Me(e){return!/^[A-Za-z0-9 ]+$/.test(e)||!C(F(e))?"A board name takes letters, digits and spaces, up to 41 characters of route.":Se(y(),F(e))?`/${F(e)} is taken; pick another name.`:null}p(Me,"nameProblem");const je="--template board --items data/wave.json";async function Ke(){const e=ke(process.cwd(),"rev-parse","--show-toplevel");e||i(`${process.cwd()} is not in a git repo; run kickflip join in the folder of the repo to add as a board`,2);const t=w.realpathSync(e);await H()||i("the hub is not running; run kickflip init to set it up, then kickflip join here again");const n=Object.entries(y().sites).find(([,f])=>P(f)&&f.owner?.repo&&ze(f.owner.repo)===t),o=await Ie(t);if(n)return Ue(...n,o);const l=u.basename(t).replace(/[^A-Za-z0-9]+/g," ").trim();let c=s.name?.trim();for(c===void 0&&!ee()&&i('join needs --name "<Board name>" when it has no terminal to ask in',2);;){c===void 0&&(c=await te(`Board name${l?` (${l})`:""}: `)||l);const f=Me(c);if(!f)break;s.name!==void 0&&i(f,2),h(f),c=void 0}const r=c.replace(/\s+/g," "),m=F(r),d=ke(t,"remote","get-url","origin"),a=d?Fe(d):null,{trustFolder:b}=await import("../hub/trust.mjs");try{b(t)}catch(f){i(`Couldn't trust this folder for Claude Code: ${f.message}`)}if(await O(async()=>{const f=y();Se(f,m)&&i(`/${m} is taken; pick another name`,2);const k=u.join(_,"sites",m),$=new Date().toISOString(),x={dir:k,port:await J(f),cmd:ye(k,{title:r,items:"data/wave.json"}),watch:["data/events.jsonl"],title:r,local:!0,...a?{github:a}:{},...o?{branch:o}:{},owner:{repo:t},created:$,updated:$};f.sites={...f.sites,[m]:x},X(f,m,x),await v(f)}),h(`Made ${r} at ${Z(m)}, working in ${t}${a?` (${a})`:""}.`),s.hub)return h("It is the hub board, so its session runs in tmux, attached here."),q(t);try{await V(m,{repo:t,prompt:je})}catch(f){throw f instanceof I&&i(`${f.message}
159
- The board is made; run kickflip join here again to start its session.`,f.code),f}h("Its session is starting in the background, and joins the board shortly.")}p(Ke,"joinFolder");async function Ue(e,t,n){const o=t.title||e;h(`This folder already has a board: ${o} (/${e}).`),n&&n!==t.branch&&(await O(async()=>{const m=y();Object.assign(g(m.sites,e),{branch:n,updated:new Date().toISOString()}),await v(m)}),h(`Its branch is now ${n}${t.branch?` (it was ${t.branch})`:""}.`)),ee()||i(t.hub===!0?"Open its session with kickflip hub.":"Run kickflip join in a terminal to restart its session, or tap Restart on its row of the Hub page.");const l=(await te("Restart its session? (Y/n) ")).toLowerCase();if(l&&!"yes".startsWith(l))return;if(!t.owner.session)return t.hub===!0?q(t.owner.repo):(await V(e,{repo:t.owner.repo,prompt:je}),h("Its session is starting in the background."));const c=await fetch(`http://127.0.0.1:${T}/_hub/restart-board`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:e}),signal:AbortSignal.timeout(5*6e4)}),r=await c.json();if(c.ok||i(r.error),h(`Restarted ${o}'s session.`),t.hub===!0)return q(t.owner.repo)}p(Ue,"restartFolderBoard");const ne=["title","description","icon","color","created","watch","filter","hub","github","remote","branch","local"],$e=["notifications","quiet","codexShare"],E="kickflip-board",Ge=/^(\.watch-cursor-.*\.json|watcher\.json)$/,B=p((e,t)=>Object.fromEntries(t.filter(n=>e[n]!==void 0).map(n=>[n,e[n]])),"pick"),z=p(e=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${String(e).replace(/'/g,"'\\''")}'`,"shellQuote");function ve(e){const t=K("tar",e[0]==="-czf"?["--no-xattrs",...e]:e,{encoding:"utf8",env:{...process.env,COPYFILE_DISABLE:"1"}});t.status!==0&&i(`tar ${e[0]} failed: ${(t.stderr||t.error?.message||"").trim()}`)}p(ve,"tar");function We(e,t){const n=e.entry.title||e.route,o=Object.keys(e.settings).map(l=>({notifications:"Notifications",quiet:"Quiet hours",codexShare:"Codex share"})[l]);return`# Moving ${n} (/${e.route}) to another machine
164
+ var Ne=Object.defineProperty;var h=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import w from"node:fs";import d from"node:path";import D from"node:os";import re from"node:net";import Te from"node:readline/promises";import{execFileSync as ae,spawnSync as K}from"node:child_process";import{fileURLToPath as Ie}from"node:url";import{ICON_KEYS as ce}from"../hub/icons.mjs";import{liveSessions as G}from"../hub/live.mjs";import{isBoardSite as L,writeManifest as v}from"../hub/boards.mjs";import{joinName as Fe,routeFromName as F,routeRecord as g,validRoute as C}from"../hub/routes.mjs";import{defaultBranch as Ce,githubFromOrigin as Ee}from"../hub/repos.mjs";import{hasBuildScript as Re,onboardingItems as Be}from"../board/onboarding.mjs";import{uninstallStatusLine as Ae,storedPath as De,nodeBin as U,watcherCommand as Le,tailnetUrl as Pe}from"./install.mjs";import{hubService as de}from"../shared/service.mjs";import{tailscaleBin as ue}from"../shared/tailscale.mjs";import{runDoctor as He}from"./doctor.mjs";import{cloneRoot as Je}from"../shared/repos.mjs";const j=Je(),N=d.join(D.homedir(),".claude","kickflip"),ze=d.join(N,"manifest.json"),le=d.join(N,"logs"),T=Number(process.env.KICKFLIP_HUB_PORT||4500),W=4600,qe=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,[Y,...S]=process.argv.slice(2),s=Object.assign(Object.create(null),{_:[]});for(let e=0;e<S.length;e++){const t=S[e];if(t.startsWith("--")){const n=t.slice(2);n==="fix"||n==="force"||n==="json"||n==="urgent"||n==="now"||n==="keep-queue"||n==="hub"||n==="no-hub"||n==="dry-run"||n==="no-restart"||n==="watch"&&(e+1>=S.length||S[e+1].startsWith("--"))?s[n]=!0:s[n]=S[++e]}else s._.push(t)}const f=h(e=>console.log(typeof e=="string"?e:JSON.stringify(e,null,2)),"out");class I extends Error{static{h(this,"Exit")}constructor(t,n){super(t),this.code=n}}const i=h((e,t=1)=>{throw new I(e,t)},"fail");function Q(){s.icon&&!ce.includes(s.icon)&&i(`--icon takes one of: ${ce.join(", ")}`,2),s.color&&!qe.test(s.color)&&i("--color takes a CSS hex color, such as #3b82f6",2)}h(Q,"checkLook");function X(e){for(const t of["icon","color"])s[t]===""?delete e[t]:s[t]!==void 0&&(e[t]=s[t])}h(X,"applyLook");const fe=h(()=>s.hub&&s["no-hub"]&&i("pass --hub or --no-hub, not both",2),"checkHub"),he=h(e=>i(`/${e} is not a board; only a board can be the hub board`,2),"notBoard");function Z(e,t,n){if(s["no-hub"]&&delete n.hub,!!s.hub){L(n)||he(t);for(const[o,p]of Object.entries(e.sites))o!==t&&p?.hub&&delete p.hub;n.hub=!0}}h(Z,"applyHub");function y(){try{const e=JSON.parse(w.readFileSync(ze,"utf8"));return e.sites||={},e}catch(e){if(e.code==="ENOENT")return{version:1,sites:{}};i("manifest unreadable: "+e.message)}}h(y,"readManifest");const pe=h(e=>{try{return JSON.parse(w.readFileSync(e,"utf8"))}catch{return null}},"readJSON"),E=h(()=>import(d.join(j,"hub","sessions.mjs")),"sessionsModule");async function P(e){const{SessionError:t}=await E();try{return await e()}catch(n){throw n instanceof t&&i(n.message,n.reason==="live"?3:n.reason==="hub"?2:1),n}}h(P,"sessionCall");async function me(e){const{handshake:t}=await import(d.join(j,"hub","boards.mjs"));try{return await t(e,y())}catch(n){return i(n.message,2)}}h(me,"runHandshake");async function Me(e){for(let t=0;t<2;t++){let n;try{n=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!1}),signal:AbortSignal.timeout(5*6e4)})}catch(p){return`not run (${p.message})`}if(!n.ok)return`not run (the hub answered ${n.status})`;const o=await n.json();if(o.checked?.includes(e))return"reached this board";if(o.failed?.length)return`missed this board: ${o.failed[0]}`}return"missed this board"}h(Me,"pollFor");async function O(e){const{withManifestLock:t}=await import(d.join(j,"hub","boards.mjs"));try{return await t(e)}catch(n){throw n.code==="ELOCKED"&&i(n.message),n}}h(O,"withLock");function we(e){return new Promise(t=>{const n=re.connect({port:e,host:"127.0.0.1"}),o=h(p=>{n.destroy(),t(p)},"done");n.setTimeout(500,()=>o(!1)),n.on("connect",()=>o(!0)),n.on("error",()=>o(!1))})}h(we,"connects");function Ke(e){return new Promise(t=>{const n=re.createServer();n.once("error",()=>t(!1)),n.listen(e,"0.0.0.0",()=>n.close(()=>t(!0)))})}h(Ke,"bindable");async function H(e){const t=new Set([...Object.values(e.sites),...Object.values(e.closed||{}).map(n=>n.site)].map(n=>n?.port));for(let n=W;n<W+400;n++)if(!t.has(n)&&!await we(n)&&await Ke(n))return n;i("no free port found from "+W)}h(H,"freePort");function Ge(){const e=ue();if(!e)return"";try{return(JSON.parse(ae(e,["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})).Self?.DNSName||"").replace(/\.$/,"")}catch{return""}}h(Ge,"tailnetHost");const V=h(e=>{const t=Ge();return t?`https://${t}/${e}/`:`http://127.0.0.1:${T}/${e}/`},"siteUrl");async function J(){try{return await(await fetch(`http://127.0.0.1:${T}/_hub/status.json`,{signal:AbortSignal.timeout(1500)})).json()}catch{return null}}h(J,"hubStatus");const ge=h(e=>{try{return w.statSync(e).isDirectory()}catch{return!1}},"isFolder"),Ue=h(e=>{try{return w.realpathSync(e)}catch{return null}},"realPath");function be(e=t=>{}){(typeof s.name!="string"||!s.name.trim())&&i('join needs --name "<name>": the board or page name, which gives its route',2);const t=s.name.trim().replace(/\s+/g," "),n=F(t);return C(n)||i(`--name "${t}" needs a letter or digit for its route`,2),{route:n,title:t===n&&e(n)?.title||t}}h(be,"named");function ye(e,{title:t,items:n,tickets:o,repo:p,ref:l}){w.mkdirSync(d.join(e,"data"),{recursive:!0});const r=d.join(e,"board.json"),u=w.existsSync(r)?JSON.parse(w.readFileSync(r,"utf8")):{};u.title=t,u.items=De(n||u.items||"waves"),o&&(u.tickets=o),w.writeFileSync(r,JSON.stringify(u,null,2)+`
165
+ `);const c=u.items==="waves"?null:d.resolve(e,u.items);if(c&&!w.existsSync(c)){w.mkdirSync(d.dirname(c),{recursive:!0});const a=u.tickets?.source==="internal"?u.tickets.prefix:void 0,b=Be(c,{prefix:a,hasBuild:Re(p,l)});w.writeFileSync(c,JSON.stringify({title:u.title,items:b},null,2)+`
166
+ `)}return[U(),d.join(j,"board","server.mjs"),e]}h(ye,"boardFiles");async function ee(e,t){const{startSession:n,withSessionLock:o}=await E();return o(e,async()=>{const p=await P(()=>n(e,{manifest:y(),...t}));return await O(async()=>{const l=y(),r={session:p.session,label:p.name,since:new Date().toISOString(),repo:p.repo,...p.model?{model:p.model}:{}};g(l.sites,e)?(l.sites[e].owner=r,l.sites[e].updated=r.since):l.starting={...l.starting,[e]:{...g(l.starting,e),...r}},await v(l)}),p})}h(ee,"startRecorded");async function z(e){const{hubSession:t}=await E(),n=await P(()=>t({manifest:y(),repo:e}));process.exitCode=n.status}h(z,"openHub");const ke=h((e,...t)=>{const n=K("git",["-C",e,...t],{encoding:"utf8"});return n.status===0?n.stdout.trim():null},"git"),te=h(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"canAsk");async function ne(e,t="stopped at the prompt; nothing changed"){const n=Te.createInterface({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()}catch(o){throw o.code==="ABORT_ERR"&&i(t),o}finally{n.close()}}h(ne,"ask");const Se=h((e,t)=>!!(g(e.sites,t)||g(e.starting,t)||g(e.closed,t)),"taken");function We(e){return!/^[A-Za-z0-9 ]+$/.test(e)||!C(F(e))?"A board name takes letters, digits and spaces, up to 41 characters of route.":Se(y(),F(e))?`/${F(e)} is taken; pick another name.`:null}h(We,"nameProblem");const je="--template board --items data/wave.json";async function Ye(){const e=ke(process.cwd(),"rev-parse","--show-toplevel");e||i(`${process.cwd()} is not in a git repo; run kickflip join in the folder of the repo to add as a board`,2);const t=w.realpathSync(e);await J()||i("the hub is not running; run kickflip init to set it up, then kickflip join here again");const n=Object.entries(y().sites).find(([,m])=>L(m)&&m.owner?.repo&&Ue(m.owner.repo)===t),o=await Ce(t);if(n)return Qe(...n,o);const p=d.basename(t).replace(/[^A-Za-z0-9]+/g," ").trim();let l=s.name?.trim();for(l===void 0&&!te()&&i('join needs --name "<Board name>" when it has no terminal to ask in',2);;){l===void 0&&(l=await ne(`Board name${p?` (${p})`:""}: `)||p);const m=We(l);if(!m)break;s.name!==void 0&&i(m,2),f(m),l=void 0}const r=l.replace(/\s+/g," "),u=F(r),c=ke(t,"remote","get-url","origin"),a=c?Ee(c):null,{trustFolder:b}=await import("../hub/trust.mjs");try{b(t)}catch(m){i(`Couldn't trust this folder for Claude Code: ${m.message}`)}if(await O(async()=>{const m=y();Se(m,u)&&i(`/${u} is taken; pick another name`,2);const k=d.join(N,"sites",u),$=new Date().toISOString(),x={dir:k,port:await H(m),cmd:ye(k,{title:r,items:"data/wave.json",repo:t,ref:o||"HEAD"}),watch:["data/events.jsonl"],title:r,local:!0,...a?{github:a}:{},...o?{branch:o}:{},owner:{repo:t},created:$,updated:$};m.sites={...m.sites,[u]:x},Z(m,u,x),await v(m)}),f(`Made ${r} at ${V(u)}, working in ${t}${a?` (${a})`:""}.`),s.hub)return f("It is the hub board, so its session runs in tmux, attached here."),z(t);try{await ee(u,{repo:t,prompt:je})}catch(m){throw m instanceof I&&i(`${m.message}
167
+ The board is made; run kickflip join here again to start its session.`,m.code),m}f("Its session is starting in the background, and joins the board shortly.")}h(Ye,"joinFolder");function $e(e){const t=de(),n=t.restart();n&&i(`${e}: ${n}; run ${t.restartCommand}`),f("restarted the hub")}h($e,"restartHub");async function Qe(e,t,n){const o=t.title||e;f(`This folder already has a board: ${o} (/${e}).`),n&&n!==t.branch&&(await O(async()=>{const u=y();Object.assign(g(u.sites,e),{branch:n,updated:new Date().toISOString()}),await v(u)}),f(`Its branch is now ${n}${t.branch?` (it was ${t.branch})`:""}.`)),te()||i(t.hub===!0?"Open its session with kickflip hub.":"Run kickflip join in a terminal to restart its session, or tap Restart on its row of the Hub page.");const p=(await ne("Restart its session? (Y/n) ")).toLowerCase();if(p&&!"yes".startsWith(p))return;if(!t.owner.session)return t.hub===!0?z(t.owner.repo):(await ee(e,{repo:t.owner.repo,prompt:je}),f("Its session is starting in the background."));const l=await fetch(`http://127.0.0.1:${T}/_hub/restart-board`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:e}),signal:AbortSignal.timeout(5*6e4)}),r=await l.json();if(l.ok||i(r.error),f(`Restarted ${o}'s session.`),t.hub===!0)return z(t.owner.repo)}h(Qe,"restartFolderBoard");const se=["title","description","icon","color","created","watch","filter","hub","github","remote","branch","local"],ve=["notifications","quiet","codexShare"],R="kickflip-board",Xe=/^(\.watch-cursor-.*\.json|watcher\.json)$/,B=h((e,t)=>Object.fromEntries(t.filter(n=>e[n]!==void 0).map(n=>[n,e[n]])),"pick"),q=h(e=>/^[\w@%+=:,./-]+$/.test(e)?e:`'${String(e).replace(/'/g,"'\\''")}'`,"shellQuote");function Oe(e){const t=K("tar",e[0]==="-czf"?["--no-xattrs",...e]:e,{encoding:"utf8",env:{...process.env,COPYFILE_DISABLE:"1"}});t.status!==0&&i(`tar ${e[0]} failed: ${(t.stderr||t.error?.message||"").trim()}`)}h(Oe,"tar");function Ze(e,t){const n=e.entry.title||e.route,o=Object.keys(e.settings).map(p=>({notifications:"Notifications",quiet:"Quiet hours",codexShare:"Codex share"})[p]);return`# Moving ${n} (/${e.route}) to another machine
160
168
 
161
169
  Exported from ${e.from} at ${e.exported_at}. This bundle holds the board's folder and manifest entry${o.length?`, and the hub's ${o.length>1?`${o.slice(0,-1).join(", ")} and ${o.at(-1)}`:o[0]} settings, which import writes over the new machine's`:""}.
162
170
 
@@ -174,15 +182,16 @@ The bundle carries no secret and nothing tied to the old machine. Set these up o
174
182
 
175
183
  - GitHub sign-in: \`gh auth login\`.
176
184
  - Linear API key: Hub \u2192 Linear.
177
- - Slack: Claude's Slack connector in the new session, and the hub's Slack identity with \`board.mjs slack set --self-dm <D\u2026> --user <U\u2026>\`.
185
+ - Slack user token: Hub \u2192 Slack. Digests follow the hub's Slack timezone, set with \`board.mjs slack set --timezone Area/City\`.
178
186
  - Codex: \`codex login\`, if Codex builds.
179
187
  - Notifications: open the Hub page on each phone and tap Turn on.
180
188
  - Other hub settings, such as the pause line and Rules for every board, stay on the old machine.
181
189
 
182
190
  Manifest fields left out, which the new machine sets itself: ${e.dropped.length?e.dropped.join(", "):"none"}.
183
- `}p(We,"exportReadme");async function Ye(){Y();const e=s.port===void 0?void 0:Number(s.port);e!==void 0&&!(Number.isInteger(e)&&e>0&&e<65536)&&i("--port takes a port number",2),e===T&&i(`--port ${e} is the hub's own port`,2);let t;if(s.cmd!==void 0){try{t=JSON.parse(s.cmd)}catch{t=null}(!Array.isArray(t)||!t.length||!t.every(d=>typeof d=="string"))&&i(`--cmd takes a JSON array of strings, such as '["/abs/node","/abs/server.mjs"]'`,2)}const n=s.dir===void 0?void 0:u.resolve(s.dir);n!==void 0&&!t&&e===void 0&&!ge(n)&&i(`--dir ${n} is not a folder`,2);const{route:o,title:l}=be(d=>g(y().sites,d)),c=await O(async()=>{const d=y();g(d.closed,o)&&i("That board is closed; use kickflip reopen "+o,2),g(d.starting,o)&&i(`/${o} is a board that is starting; pick another route`,2);const a=g(d.sites,o);if(a?.owner?.session)throw h({error:"owned",route:o,owner:a.owner,hint:"a session owns this route: pick another route, or that session leaves it first"}),new I("",3);const b=new Date().toISOString(),f=a?{...a}:{created:b};delete f.watch,delete f.filter;{const k=t?{cmd:t,dir:n||a?.dir||process.cwd(),port:e??(a?.cmd?a.port:void 0)??await J(d)}:e!==void 0?{port:e,...n?{dir:n}:{}}:{dir:n};for(const $ of["cmd","dir","port","cwd","env"])delete f[$];Object.assign(f,k)}return f.title=l,s.description&&(f.description=s.description),Q(f),f.updated=b,d.sites={...d.sites,[o]:f},await v(d),f}),r=c.cmd?"cmd":c.port?"port":"files",m=await H();h({route:o,url:Z(o),serves:r,...c.port?{port:c.port}:{},...c.dir?{dir:c.dir}:{},...r==="port"?{answering:await we(c.port)}:{},hub:m?"running":"NOT running: run `kickflip doctor --fix`"})}p(Ye,"joinPage");const se={async doctor(){s["dry-run"]&&!s.fix&&i("--dry-run needs --fix",2);const e=ee()&&!s.json?n=>te(n,"stopped at the prompt; the clones not yet answered are kept"):void 0,{exitCode:t}=await De({fix:!!s.fix,dryRun:!!s["dry-run"],json:!!s.json,ask:e});process.exitCode=t},async join(){if(s._.length&&i(`join takes no route: --name "<name>" gives the title and the route, as in kickflip join --name ${z(s._[0])}`,2),s.title!==void 0&&i('join takes no --title: --name "<name>" gives the title and the route',2),!s.session){const r=["port","dir","cmd"].some(d=>s[d]!==void 0),m=["watch","template","filter","label","model","repo","force","items",...r?["hub"]:[]].find(d=>s[d]!==void 0);return m&&i(`--${m} needs --session <id> (this session's id)`,2),r?Ye():Ke()}const{route:e,title:t}=be(r=>g(y().sites,r));s.template&&s.template!=="board"&&i('--template takes "board"',2),Y(),fe();const n=await O(async()=>{const r=y();g(r.closed,e)&&i("That board is closed; use kickflip reopen "+e,2);const m=new Date().toISOString(),d=g(r.sites,e);if(d?.owner?.session&&d.owner.session!==s.session&&!s.force)throw h({error:"owned",route:e,owner:d.owner,hint:"ask the user, then rerun with --force to take it over"}),new I("",3);s.hub&&s.template!=="board"&&!P({dir:"",cmd:s.cmd?JSON.parse(s.cmd):d?.cmd})&&he(e);const a=d?{...d}:{};let b=!1;if(d||(a.dir=u.resolve(s.dir||u.join(_,"sites",e)),(!w.existsSync(a.dir)||w.readdirSync(a.dir).length===0)&&!s.cmd&&!s.template&&(w.cpSync(u.join(j,"starter"),a.dir,{recursive:!0}),b=!0),a.port=s.port?Number(s.port):await J(r),a.cmd=s.cmd?JSON.parse(s.cmd):[U(),u.join(a.dir,"server.mjs")],a.watch=["data/events.jsonl"],a.created=m),s.dir&&d&&(a.dir=u.resolve(s.dir)),s.port&&d&&(a.port=Number(s.port)),s.cmd&&d&&(a.cmd=JSON.parse(s.cmd)),s.template==="board"){const N=g(r.starting,e),Oe=!d&&N?.tickets&&(!N.session||N.session===s.session)?N.tickets:void 0;a.cmd=ye(a.dir,{title:t,items:s.items,tickets:Oe}),b=!d}a.title=t,s.description&&(a.description=s.description),typeof s.watch=="string"&&(a.watch=s.watch.split(",").map(N=>N.trim()).filter(Boolean)),s.filter!==void 0&&(a.filter=s.filter||void 0),Q(a),X(r,e,a);const f=d?.owner&&d.owner.session!==s.session?d.owner:null,k=g(r.starting,e)?.session===s.session?g(r.starting,e):null,$=g(r.starting,e);!d&&($?.github||$?.remote)&&(!$.session||$.session===s.session)&&($.github?a.github=$.github:a.remote=$.remote,a.branch=$.branch);const x=d?.owner?.session===s.session?d.owner:null,D=x||k||f;a.owner={...x||{session:s.session,since:m},label:s.label||D?.label||"",repo:s.repo?u.resolve(s.repo):(a.github||a.remote)&&D?.repo||ce()?.get(s.session)?.cwd||D?.repo||process.cwd()};const oe=s.model||D?.model;oe&&(a.owner.model=oe);const M=g(r.starting,e);return M&&(r.starting[e]={...M,joined_at:M.joined_at||m}),a.updated=m,r.sites={...r.sites,[e]:a},await v(r),{route:e,created:b,previousOwner:f,site:a}}),o=await H();let l,c;if(s.template==="board"){const r=pe(u.join(n.site.dir,"data","handshake.json"));l=r?.ack&&r.hello?.session===s.session?"answered before":await me(e),c=o?await Je(e):"not run (the hub is not running)"}h({route:e,url:Z(e),dir:n.site.dir,port:n.site.port,owner:n.site.owner,createdFromStarter:n.created,previousOwner:n.previousOwner,log:u.join(le,e+".log"),watcher:Ee(e,s.session,j),hub:o?"running":"NOT running: run `kickflip doctor --fix`",...l?{handshake:l}:{},...c?{poll:c}:{}})},async handshake(){const e=s._[0];e||i("handshake needs a route",2),h(await me(e))},async leave(){const e=s._[0];e||i("leave needs a route",2),await O(async()=>{const t=y(),n=g(t.sites,e);if(n||i("no site at /"+e),n.owner?.session&&!s.session&&!s.force&&i("a session owns /"+e+"; leave needs --session <id>, or --force",2),n.owner?.session&&n.owner.session!==s.session&&!s.force)throw h({error:"owned",route:e,owner:n.owner}),new I("",3);delete t.sites[e],await v(t),h({left:e,filesKept:n.dir})})},async start(){const e=s._[0];C(e)||i("start needs a route: lowercase letters, digits and dashes",2);const t=await V(e,{repo:s.repo,model:s.model,prompt:s.prompt});h({route:t.route,session:t.session,confirmed:t.confirmed,repo:t.repo,argv:t.argv,output:t.output})},async resume(){const e=s._[0];e||i("resume needs a route",2);const{resumeSession:t}=await R();h(await A(()=>t(e,{manifest:y()})))},async close(){const{closeBoard:e}=await import("../hub/close-board.mjs");try{h(await e(s._[0],s.name))}catch(t){i(t.message,t.status?2:1)}},async reopen(){const{reopenBoard:e}=await import("../hub/close-board.mjs");try{h(await A(()=>e(s._[0])))}catch(t){throw t.status&&i(t.message,2),t}},async export(){const e=s._[0];C(e)||i("export needs a route: lowercase letters, digits and dashes",2);const t=u.resolve(s.out||`kickflip-${e}.tgz`);w.existsSync(t)&&i(`${t} already exists; pass another --out`,2);const n=g(y().sites,e)||i("no site at /"+e);P(n)||i(`/${e} is not a board; export moves a board`,2);const o=w.realpathSync(n.dir),{itemSources:l,openBoardBuilders:c}=await import("../board/store.mjs"),r=(await l(o)).find(k=>u.relative(o,k.file).startsWith(".."));r&&i(`/${e}'s cards live outside its folder (${r.file}); export moves only a board whose board.json items is a file in its folder`);const m=await c(o);m.length&&i(`a builder is open on /${e}: ${m.map(k=>`${k.key} (${k.label})`).join(", ")}; export once it is done`);const{readSettingsFile:d}=await import("../hub/push.mjs"),a=B(n,ne),b={kickflip_export:1,route:e,exported_at:new Date().toISOString(),from:L.hostname(),entry:a,owner:B(n.owner||{},["label","model"]),settings:B(d(),$e),dropped:Object.keys(n).filter(k=>!ne.includes(k))},f=w.mkdtempSync(u.join(L.tmpdir(),"kickflip-export-"));try{const k=u.join(f,E),$=u.join(o,"data");w.cpSync(o,u.join(k,"site"),{recursive:!0,filter:p(x=>!(u.dirname(x)===$&&Ge.test(u.basename(x))),"filter")}),w.writeFileSync(u.join(k,"export.json"),JSON.stringify(b,null,2)+`
184
- `),w.writeFileSync(u.join(k,"README.md"),We(b,u.basename(t))),ve(["-czf",t,"-C",f,E])}finally{w.rmSync(f,{recursive:!0,force:!0})}h({route:e,file:t,entry:Object.keys(a),dropped:b.dropped,settings:Object.keys(b.settings)})},async import(){s._[0]||i("import needs the file kickflip export wrote",2);const e=u.resolve(s._[0]);w.existsSync(e)||i(`no file at ${e}`,2),w.mkdirSync(_,{recursive:!0});const t=w.mkdtempSync(u.join(_,".import-"));try{ve(["-xzf",e,"-C",t]);const n=pe(u.join(t,E,"export.json"));(n?.kickflip_export!==1||!C(n.route)||!ge(u.join(t,E,"site")))&&i(`${e} is not a kickflip export`,2);const{route:o}=n,l=u.join(_,"sites",o),c=await O(async()=>{const a=y();(g(a.sites,o)||g(a.closed,o)||g(a.starting,o))&&i(`/${o} already exists on this host; import never replaces a board`),w.existsSync(l)&&i(`${l} already exists; import never replaces a board's folder`);const b=B(n.entry||{},ne);b.hub&&Object.values(a.sites).some(k=>k?.hub)&&delete b.hub;const f={...b,dir:l,port:await J(a),cmd:[U(),u.join(j,"board","server.mjs"),l],updated:new Date().toISOString()};return w.mkdirSync(u.dirname(l),{recursive:!0}),w.renameSync(u.join(t,E,"site"),l),a.sites={...a.sites,[o]:f},await v(a),f}),r=B(n.settings||{},$e);if(Object.keys(r).length){const{readSettingsFile:a,writeSettingsFile:b}=await import("../hub/push.mjs");b({...a(),...r})}const{label:m,model:d}=n.owner||{};h({route:o,dir:l,port:c.port,settings:Object.keys(r),hub:c.hub===!0,join:`kickflip join --name ${z(Te(o,c.title))} --session <this session's id> --watch --template board${m?` --label ${z(m)}`:""}${d?` --model ${z(d)}`:""} --force`})}finally{w.rmSync(t,{recursive:!0,force:!0})}},async sessions(){const{sessionOf:e}=await R(),{listBoards:t}=await import(u.join(j,"hub","boards.mjs")),n=y(),o=ce(),c=[...t(n).map(r=>r.route),...Object.keys(n.starting||{}).filter(r=>!g(n.sites,r))].map(r=>{const m=e(n,r),d=m&&o?.get(m.session),a=m?o?d?d.kind==="bg"?"background":"terminal":null:"unknown":null;return{route:r,session:m?.session||null,live:a,repo:m?.repo||null,starting:!g(n.sites,r)}});if(s.json)return h(c);if(!c.length)return h("no boards");for(const r of c)h(`/${r.route} ${r.session||"no session"} ${r.live==="unknown"?"live unknown (ps gave no answer)":r.live?`live (${r.live})`:"not live"} ${r.repo||"no folder"}${r.starting?" (starting: not joined yet)":""}`)},async hub(){await q(s.repo)},async set(){const e=s._[0];e||i("set needs a route",2),s.icon===void 0&&s.color===void 0&&!s.hub&&!s["no-hub"]&&i("set needs --icon, --color, --hub or --no-hub",2),Y(),fe(),await O(async()=>{const t=y(),n=g(t.sites,e)||i("no site at /"+e);Q(n),X(t,e,n),n.updated=new Date().toISOString(),await v(t),h({route:e,icon:n.icon??null,color:n.color??null,hub:n.hub===!0})})},async restart(){const e=s._[0];await O(async()=>{const t=y();g(t.sites,e)||i("no site at /"+e),t.sites[e].restart_at=Date.now(),await v(t)}),h(`restarting /${e}; the hub picks it up within 2 seconds`)},async url(){const e=s._[0];e&&!g(y().sites,e)&&i("no site at /"+e,2);try{h(Be(e))}catch(t){i(t.message)}},async logs(){const e=s._[0],t=u.join(le,e+".log");w.existsSync(t)||i("no log yet for /"+e);const n=Number(s.lines||40);h(w.readFileSync(t,"utf8").split(`
191
+ `}h(Ze,"exportReadme");async function Ve(){Q();const e=s.port===void 0?void 0:Number(s.port);e!==void 0&&!(Number.isInteger(e)&&e>0&&e<65536)&&i("--port takes a port number",2),e===T&&i(`--port ${e} is the hub's own port`,2);let t;if(s.cmd!==void 0){try{t=JSON.parse(s.cmd)}catch{t=null}(!Array.isArray(t)||!t.length||!t.every(c=>typeof c=="string"))&&i(`--cmd takes a JSON array of strings, such as '["/abs/node","/abs/server.mjs"]'`,2)}const n=s.dir===void 0?void 0:d.resolve(s.dir);n!==void 0&&!t&&e===void 0&&!ge(n)&&i(`--dir ${n} is not a folder`,2);const{route:o,title:p}=be(c=>g(y().sites,c)),l=await O(async()=>{const c=y();g(c.closed,o)&&i("That board is closed; use kickflip reopen "+o,2),g(c.starting,o)&&i(`/${o} is a board that is starting; pick another route`,2);const a=g(c.sites,o);if(a?.owner?.session)throw f({error:"owned",route:o,owner:a.owner,hint:"a session owns this route: pick another route, or that session leaves it first"}),new I("",3);const b=new Date().toISOString(),m=a?{...a}:{created:b};delete m.watch,delete m.filter;{const k=t?{cmd:t,dir:n||a?.dir||process.cwd(),port:e??(a?.cmd?a.port:void 0)??await H(c)}:e!==void 0?{port:e,...n?{dir:n}:{}}:{dir:n};for(const $ of["cmd","dir","port","cwd","env"])delete m[$];Object.assign(m,k)}return m.title=p,s.description&&(m.description=s.description),X(m),m.updated=b,c.sites={...c.sites,[o]:m},await v(c),m}),r=l.cmd?"cmd":l.port?"port":"files",u=await J();f({route:o,url:V(o),serves:r,...l.port?{port:l.port}:{},...l.dir?{dir:l.dir}:{},...r==="port"?{answering:await we(l.port)}:{},hub:u?"running":"NOT running: run `kickflip doctor --fix`"})}h(Ve,"joinPage");const oe={async doctor(){s["dry-run"]&&!s.fix&&i("--dry-run needs --fix",2);const e=te()&&!s.json?n=>ne(n,"stopped at the prompt; the clones not yet answered are kept"):void 0,{exitCode:t}=await He({fix:!!s.fix,dryRun:!!s["dry-run"],json:!!s.json,ask:e});process.exitCode=t},async join(){if(s._.length&&i(`join takes no route: --name "<name>" gives the title and the route, as in kickflip join --name ${q(s._[0])}`,2),s.title!==void 0&&i('join takes no --title: --name "<name>" gives the title and the route',2),!s.session){const r=["port","dir","cmd"].some(c=>s[c]!==void 0),u=["watch","template","filter","label","model","repo","force","items",...r?["hub"]:[]].find(c=>s[c]!==void 0);return u&&i(`--${u} needs --session <id> (this session's id)`,2),r?Ve():Ye()}const{route:e,title:t}=be(r=>g(y().sites,r));s.template&&s.template!=="board"&&i('--template takes "board"',2),Q(),fe();const n=await O(async()=>{const r=y();g(r.closed,e)&&i("That board is closed; use kickflip reopen "+e,2);const u=new Date().toISOString(),c=g(r.sites,e);if(c?.owner?.session&&c.owner.session!==s.session&&!s.force)throw f({error:"owned",route:e,owner:c.owner,hint:"ask the user, then rerun with --force to take it over"}),new I("",3);s.hub&&s.template!=="board"&&!L({dir:"",cmd:s.cmd?JSON.parse(s.cmd):c?.cmd})&&he(e);const a=c?{...c}:{};let b=!1;if(c||(a.dir=d.resolve(s.dir||d.join(N,"sites",e)),(!w.existsSync(a.dir)||w.readdirSync(a.dir).length===0)&&!s.cmd&&!s.template&&(w.cpSync(d.join(j,"starter"),a.dir,{recursive:!0}),b=!0),a.port=s.port?Number(s.port):await H(r),a.cmd=s.cmd?JSON.parse(s.cmd):[U(),d.join(a.dir,"server.mjs")],a.watch=["data/events.jsonl"],a.created=u),s.dir&&c&&(a.dir=d.resolve(s.dir)),s.port&&c&&(a.port=Number(s.port)),s.cmd&&c&&(a.cmd=JSON.parse(s.cmd)),s.template==="board"){const _=g(r.starting,e),xe=!c&&_?.tickets&&(!_.session||_.session===s.session)?_.tickets:void 0,_e=s.repo?d.resolve(s.repo):G()?.get(s.session)?.cwd||process.cwd();a.cmd=ye(a.dir,{title:t,items:s.items,tickets:xe,repo:_e,ref:_?.branch||"HEAD"}),b=!c}a.title=t,s.description&&(a.description=s.description),typeof s.watch=="string"&&(a.watch=s.watch.split(",").map(_=>_.trim()).filter(Boolean)),s.filter!==void 0&&(a.filter=s.filter||void 0),X(a),Z(r,e,a);const m=c?.owner&&c.owner.session!==s.session?c.owner:null,k=g(r.starting,e)?.session===s.session?g(r.starting,e):null,$=g(r.starting,e);!c&&($?.github||$?.remote)&&(!$.session||$.session===s.session)&&($.github?a.github=$.github:a.remote=$.remote,a.branch=$.branch);const x=c?.owner?.session===s.session?c.owner:null,A=x||k||m;a.owner={...x||{session:s.session,since:u},label:s.label||A?.label||"",repo:s.repo?d.resolve(s.repo):(a.github||a.remote)&&A?.repo||G()?.get(s.session)?.cwd||A?.repo||process.cwd()};const ie=s.model||A?.model;ie&&(a.owner.model=ie);const M=g(r.starting,e);return M&&(r.starting[e]={...M,joined_at:M.joined_at||u}),a.updated=u,r.sites={...r.sites,[e]:a},await v(r),{route:e,created:b,previousOwner:m,site:a}}),o=await J();let p,l;if(s.template==="board"){const r=pe(d.join(n.site.dir,"data","handshake.json"));p=r?.ack&&(r.ping||r.hello)?.session===s.session?"answered before":await me(e),l=o?await Me(e):"not run (the hub is not running)"}f({route:e,url:V(e),dir:n.site.dir,port:n.site.port,owner:n.site.owner,createdFromStarter:n.created,previousOwner:n.previousOwner,log:d.join(le,e+".log"),watcher:Le(e,s.session,j),hub:o?"running":"NOT running: run `kickflip doctor --fix`",...p?{handshake:p}:{},...l?{poll:l}:{}})},async handshake(){const e=s._[0];e||i("handshake needs a route",2),f(await me(e))},async leave(){const e=s._[0];e||i("leave needs a route",2),await O(async()=>{const t=y(),n=g(t.sites,e);if(n||i("no site at /"+e),n.owner?.session&&!s.session&&!s.force&&i("a session owns /"+e+"; leave needs --session <id>, or --force",2),n.owner?.session&&n.owner.session!==s.session&&!s.force)throw f({error:"owned",route:e,owner:n.owner}),new I("",3);delete t.sites[e],await v(t),f({left:e,filesKept:n.dir})})},async start(){const e=s._[0];C(e)||i("start needs a route: lowercase letters, digits and dashes",2);const t=await ee(e,{repo:s.repo,model:s.model,prompt:s.prompt});f({route:t.route,session:t.session,confirmed:t.confirmed,repo:t.repo,argv:t.argv,output:t.output})},async resume(){const e=s._[0];e||i("resume needs a route",2);const{resumeSession:t}=await E();f(await P(()=>t(e,{manifest:y()})))},async close(){const{closeBoard:e}=await import("../hub/close-board.mjs");try{f(await e(s._[0],s.name))}catch(t){i(t.message,t.status?2:1)}},async reopen(){const{reopenBoard:e}=await import("../hub/close-board.mjs");try{f(await P(()=>e(s._[0])))}catch(t){throw t.status&&i(t.message,2),t}},async export(){const e=s._[0];C(e)||i("export needs a route: lowercase letters, digits and dashes",2);const t=d.resolve(s.out||`kickflip-${e}.tgz`);w.existsSync(t)&&i(`${t} already exists; pass another --out`,2);const n=g(y().sites,e)||i("no site at /"+e);L(n)||i(`/${e} is not a board; export moves a board`,2);const o=w.realpathSync(n.dir),{itemSources:p,openBoardBuilders:l}=await import("../board/store.mjs"),r=(await p(o)).find(k=>d.relative(o,k.file).startsWith(".."));r&&i(`/${e}'s cards live outside its folder (${r.file}); export moves only a board whose board.json items is a file in its folder`);const u=await l(o);u.length&&i(`a builder is open on /${e}: ${u.map(k=>`${k.key} (${k.label})`).join(", ")}; export once it is done`);const{readSettingsFile:c}=await import("../hub/push.mjs"),a=B(n,se),b={kickflip_export:1,route:e,exported_at:new Date().toISOString(),from:D.hostname(),entry:a,owner:B(n.owner||{},["label","model"]),settings:B(c(),ve),dropped:Object.keys(n).filter(k=>!se.includes(k))},m=w.mkdtempSync(d.join(D.tmpdir(),"kickflip-export-"));try{const k=d.join(m,R),$=d.join(o,"data");w.cpSync(o,d.join(k,"site"),{recursive:!0,filter:h(x=>!(d.dirname(x)===$&&Xe.test(d.basename(x))),"filter")}),w.writeFileSync(d.join(k,"export.json"),JSON.stringify(b,null,2)+`
192
+ `),w.writeFileSync(d.join(k,"README.md"),Ze(b,d.basename(t))),Oe(["-czf",t,"-C",m,R])}finally{w.rmSync(m,{recursive:!0,force:!0})}f({route:e,file:t,entry:Object.keys(a),dropped:b.dropped,settings:Object.keys(b.settings)})},async import(){s._[0]||i("import needs the file kickflip export wrote",2);const e=d.resolve(s._[0]);w.existsSync(e)||i(`no file at ${e}`,2),w.mkdirSync(N,{recursive:!0});const t=w.mkdtempSync(d.join(N,".import-"));try{Oe(["-xzf",e,"-C",t]);const n=pe(d.join(t,R,"export.json"));(n?.kickflip_export!==1||!C(n.route)||!ge(d.join(t,R,"site")))&&i(`${e} is not a kickflip export`,2);const{route:o}=n,p=d.join(N,"sites",o),l=await O(async()=>{const a=y();(g(a.sites,o)||g(a.closed,o)||g(a.starting,o))&&i(`/${o} already exists on this host; import never replaces a board`),w.existsSync(p)&&i(`${p} already exists; import never replaces a board's folder`);const b=B(n.entry||{},se);b.hub&&Object.values(a.sites).some(k=>k?.hub)&&delete b.hub;const m={...b,dir:p,port:await H(a),cmd:[U(),d.join(j,"board","server.mjs"),p],updated:new Date().toISOString()};return w.mkdirSync(d.dirname(p),{recursive:!0}),w.renameSync(d.join(t,R,"site"),p),a.sites={...a.sites,[o]:m},await v(a),m}),r=B(n.settings||{},ve);if(Object.keys(r).length){const{readSettingsFile:a,writeSettingsFile:b}=await import("../hub/push.mjs");b({...a(),...r})}const{label:u,model:c}=n.owner||{};f({route:o,dir:p,port:l.port,settings:Object.keys(r),hub:l.hub===!0,join:`kickflip join --name ${q(Fe(o,l.title))} --session <this session's id> --watch --template board${u?` --label ${q(u)}`:""}${c?` --model ${q(c)}`:""} --force`})}finally{w.rmSync(t,{recursive:!0,force:!0})}},async sessions(){const{sessionOf:e}=await E(),{listBoards:t}=await import(d.join(j,"hub","boards.mjs")),n=y(),o=G(),l=[...t(n).map(r=>r.route),...Object.keys(n.starting||{}).filter(r=>!g(n.sites,r))].map(r=>{const u=e(n,r),c=u&&o?.get(u.session),a=u?o?c?c.kind==="bg"?"background":"terminal":null:"unknown":null;return{route:r,session:u?.session||null,live:a,repo:u?.repo||null,starting:!g(n.sites,r)}});if(s.json)return f(l);if(!l.length)return f("no boards");for(const r of l)f(`/${r.route} ${r.session||"no session"} ${r.live==="unknown"?"live unknown (ps gave no answer)":r.live?`live (${r.live})`:"not live"} ${r.repo||"no folder"}${r.starting?" (starting: not joined yet)":""}`)},async hub(){await z(s.repo)},async set(){const e=s._[0];e||i("set needs a route",2),s.icon===void 0&&s.color===void 0&&!s.hub&&!s["no-hub"]&&i("set needs --icon, --color, --hub or --no-hub",2),Q(),fe(),await O(async()=>{const t=y(),n=g(t.sites,e)||i("no site at /"+e);X(n),Z(t,e,n),n.updated=new Date().toISOString(),await v(t),f({route:e,icon:n.icon??null,color:n.color??null,hub:n.hub===!0})})},async restart(){const e=s._[0];if(!e)return $e("the hub did not restart");await O(async()=>{const t=y();g(t.sites,e)||i("no site at /"+e),t.sites[e].restart_at=Date.now(),await v(t)}),f(`restarting /${e}; the hub picks it up within 2 seconds`)},async url(){const e=s._[0];e&&!g(y().sites,e)&&i("no site at /"+e,2);try{f(Pe(e))}catch(t){i(t.message)}},async logs(){const e=s._[0],t=d.join(le,e+".log");w.existsSync(t)||i("no log yet for /"+e);const n=Number(s.lines||40);f(w.readFileSync(t,"utf8").split(`
185
193
  `).slice(-n-1).join(`
186
- `))},async init(){s.fix=!0,await se.doctor()},async update(){w.existsSync(u.join(j,".git"))&&i(`${j} is a clone; update it with git pull`,2);const e=K("npm",["i","-g","@lovek4d/kickflip@latest"],{stdio:"inherit"});e.status!==0&&i(`npm update failed${e.error?": "+e.error.message:""}`);const t=de(),n=t.restart();n&&i(`update finished but the hub did not restart: ${n}; run ${t.restartCommand}`),h("updated kickflip and restarted the hub")},async uninstall(){Ce()&&h(`removed ${u.join(L.homedir(),".claude","statusline.sh")}`);const e=de();e.remove();const t=ue();if(t)try{re(t,["serve","--https=443","--set-path=/","off"],{stdio:"ignore"})}catch{}h(`hub stopped and removed from ${e.manager??"the host"}${t?"; tailscale / unmapped":""}. The manifest and sites are kept in ${_}`)},async push(){const{deliver:e,pushKindError:t}=await import(u.join(j,"hub","push.mjs")),n=t(s.kind);n&&i(n,2),s.title||i("push needs --title",2),s.url&&!s.url.startsWith("/")&&i("--url is a path on the hub, such as /<route>/page.html",2);const{sendWords:o,holdLine:l}=await import(u.join(j,"hub","schedule.mjs"));s.now&&s.urgent&&i("pass --now or --urgent, not both",2);const c=await e({title:s.title,body:s.body||"",url:s.url||"/",tag:s.tag},{kind:s.kind,urgent:!!s.urgent,immediate:!!s.now});if(c.noDevice&&i("no device has turned on notifications; open Hub \u2192 Notifications (/_hub/#notifications) in the Home Screen app and tap Turn on",3),c.dropped)return h("dropped (notifications are off on the Hub page)");if(c.queued){const{count:r,replaced:m,nextFlushAt:d,hold:a,sendFailed:b}=c.queued,f=s.now?a?`${l(a)}; `:b?"no device took it now; ":"":"";h(`queued (${f}${r} in queue${m?"; replaced the queued push with this tag":""}); next send ${o(d)}${d instanceof Date?` (${d.toISOString()})`:""}`),await H()||h("warning: the hub is not running, so the queue goes out only once it runs");return}h(c.sent),c.sent.some(r=>r.status>=200&&r.status<300)||i("every push was refused",1),h(s.urgent?"sent (urgent)":"sent")},async quiet(){const{readSettings:e}=await import(u.join(j,"hub","push.mjs")),{hold:t}=await import(u.join(j,"hub","schedule.mjs")),n=e(),o=t(new Date,n);h({quiet:n.quiet,held:o!==null,held_until:o?o.until instanceof Date?o.until.toISOString():o.until:null,held_why:o?.why??null,notifications:n.notifications})},async notifications(){const{setNotifications:e,readSettings:t}=await import(u.join(j,"hub","push.mjs")),[n,o]=s._,c=n===void 0?null:n==="on"||n==="off"?{on:n==="on"}:n==="weekends"?{weekends_off:p((m,d)=>m==="on"?!0:m==="off"?!1:i(`${d} takes on or off`,2),"onOff")(o,"weekends")}:n==="snooze"?{snooze:o||i("snooze takes a length: <n>m, <n>h, <n>d, <n>w, tonight, morning, monday, forever or a date and time",2)}:n==="unsnooze"?{snooze:"off"}:i("notifications takes on, off, snooze <length>, unsnooze, or weekends on|off",2);if(!c)return h(t().notifications);let r;try{r=await e(c)}catch(m){throw m.status===400&&i(m.message,2),m}h(r.dropped?{...r.notifications,dropped:r.dropped}:r.notifications)},async"codex-share"(){(S.length>1||S.length&&s._.length!==1)&&i("codex-share takes auto, always, or off",2);const{readCodexShare:t,setCodexShare:n}=await import(u.join(j,"hub","push.mjs"));if(!S.length)return h(t());try{h(n(S[0]))}catch(o){throw o.status===400&&i(o.message,2),o.status===409&&i(o.message),o}},async"usage-gate"(){const{readUsageGate:e,setPauseAt:t,setKeepGoing:n}=await import("../shared/usage-gate.mjs");try{S.length&&(S[0]==="pause-at"&&S.length===2?t(S[1]):S[0]==="keep-going"&&S.length===1?n("on"):S[0]==="stop"&&S.length===1?n("off"):i("usage-gate takes pause-at <50..100>, keep-going, or stop",2)),h(e())}catch(o){throw o.status&&i(o.message,o.status===400?2:1),o}},async"poll-now"(){let e;try{e=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!s["keep-queue"]}),signal:AbortSignal.timeout(10*6e4)})}catch(t){i("the hub is not running: "+t.message)}e.ok||i(`the hub answered ${e.status}: ${(await e.text()).slice(0,200)}`),h(await e.json())}};if(!se[W]){const e=w.readFileSync(Ne(import.meta.url),"utf8").split(`
187
- `).slice(1);h(e.slice(0,e.findIndex(t=>!t.startsWith("//"))).map(t=>t.replace(/^\/\/ ?/,"")).join(`
188
- `)),process.exit(W?2:0)}try{await se[W]()}catch(e){if(!(e instanceof I))throw e;e.message&&console.error("kickflip: "+e.message),process.exit(e.code)}
194
+ `))},async init(){s.fix=!0,await oe.doctor()},async update(){w.existsSync(d.join(j,".git"))&&i(`${j} is a clone; update it with git pull`,2);const e=h(()=>JSON.parse(w.readFileSync(d.join(j,"package.json"),"utf8")).version,"installedVersion"),t=e(),n=K("npm",["i","-g","@lovek4d/kickflip@latest"],{stdio:"inherit"});n.status!==0&&i(`npm update failed${n.error?": "+n.error.message:""}`);const o=e();if(o===t)return f("no new version available");f(`${t} > ${o}`),!s["no-restart"]&&$e("update finished but the hub did not restart")},async uninstall(){Ae()&&f(`removed ${d.join(D.homedir(),".claude","statusline.sh")}`);const e=de();e.remove();const t=ue();if(t)try{ae(t,["serve","--https=443","--set-path=/","off"],{stdio:"ignore"})}catch{}f(`hub stopped and removed from ${e.manager??"the host"}${t?"; tailscale / unmapped":""}. The manifest and sites are kept in ${N}`)},async push(){const{deliver:e,pushKindError:t}=await import(d.join(j,"hub","push.mjs")),n=t(s.kind);n&&i(n,2),s.title||i("push needs --title",2),s.url&&!s.url.startsWith("/")&&i("--url is a path on the hub, such as /<route>/page.html",2);const{sendWords:o,holdLine:p}=await import(d.join(j,"hub","schedule.mjs"));s.now&&s.urgent&&i("pass --now or --urgent, not both",2);const l=await e({title:s.title,body:s.body||"",url:s.url||"/",tag:s.tag},{kind:s.kind,urgent:!!s.urgent,immediate:!!s.now});if(l.noDevice&&i("no device has turned on notifications; open Hub \u2192 Notifications (/_hub/#notifications) in the Home Screen app and tap Turn on",3),l.dropped)return f("dropped (notifications are off on the Hub page)");if(l.queued){const{count:r,replaced:u,nextFlushAt:c,hold:a,sendFailed:b}=l.queued,m=s.now?a?`${p(a)}; `:b?"no device took it now; ":"":"";f(`queued (${m}${r} in queue${u?"; replaced the queued push with this tag":""}); next send ${o(c)}${c instanceof Date?` (${c.toISOString()})`:""}`),await J()||f("warning: the hub is not running, so the queue goes out only once it runs");return}f(l.sent),l.sent.some(r=>r.status>=200&&r.status<300)||i("every push was refused",1),f(s.urgent?"sent (urgent)":"sent")},async quiet(){const{readSettings:e}=await import(d.join(j,"hub","push.mjs")),{hold:t}=await import(d.join(j,"hub","schedule.mjs")),n=e(),o=t(new Date,n);f({quiet:n.quiet,held:o!==null,held_until:o?o.until instanceof Date?o.until.toISOString():o.until:null,held_why:o?.why??null,notifications:n.notifications})},async notifications(){const{setNotifications:e,readSettings:t}=await import(d.join(j,"hub","push.mjs")),[n,o]=s._,l=n===void 0?null:n==="on"||n==="off"?{on:n==="on"}:n==="weekends"?{weekends_off:h((u,c)=>u==="on"?!0:u==="off"?!1:i(`${c} takes on or off`,2),"onOff")(o,"weekends")}:n==="snooze"?{snooze:o||i("snooze takes a length: <n>m, <n>h, <n>d, <n>w, tonight, morning, monday, forever or a date and time",2)}:n==="unsnooze"?{snooze:"off"}:i("notifications takes on, off, snooze <length>, unsnooze, or weekends on|off",2);if(!l)return f(t().notifications);let r;try{r=await e(l)}catch(u){throw u.status===400&&i(u.message,2),u}f(r.dropped?{...r.notifications,dropped:r.dropped}:r.notifications)},async"codex-share"(){(S.length>1||S.length&&s._.length!==1)&&i("codex-share takes auto, always, or off",2);const{readCodexShare:t,setCodexShare:n}=await import(d.join(j,"hub","push.mjs"));if(!S.length)return f(t());try{f(n(S[0]))}catch(o){throw o.status===400&&i(o.message,2),o.status===409&&i(o.message),o}},async"usage-gate"(){const{readUsageGate:e,setPauseAt:t,setKeepGoing:n}=await import("../shared/usage-gate.mjs");try{S.length&&(S[0]==="pause-at"&&S.length===2?t(S[1]):S[0]==="keep-going"&&S.length===1?n("on"):S[0]==="stop"&&S.length===1?n("off"):i("usage-gate takes pause-at <50..100>, keep-going, or stop",2)),f(e())}catch(o){throw o.status&&i(o.message,o.status===400?2:1),o}},async audit(){S.length&&i("audit takes no arguments",2);const{readAudit:e,auditLines:t,hubAudit:n}=await import("../shared/audit.mjs");f(t(e(n())).join(`
195
+ `))},async"poll-now"(){let e;try{e=await fetch(`http://127.0.0.1:${T}/_hub/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({flush:!s["keep-queue"]}),signal:AbortSignal.timeout(10*6e4)})}catch(t){i("the hub is not running: "+t.message)}e.ok||i(`the hub answered ${e.status}: ${(await e.text()).slice(0,200)}`),f(await e.json())}};if(!oe[Y]){const e=w.readFileSync(Ie(import.meta.url),"utf8").split(`
196
+ `).slice(1);f(e.slice(0,e.findIndex(t=>!t.startsWith("//"))).map(t=>t.replace(/^\/\/ ?/,"")).join(`
197
+ `)),process.exit(Y?2:0)}try{await oe[Y]()}catch(e){if(!(e instanceof I))throw e;e.message&&console.error("kickflip: "+e.message),process.exit(e.code)}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var q=Object.defineProperty;var s=(e,o)=>q(e,"name",{value:o,configurable:!0});import c from"node:fs";import f from"node:path";import L from"node:os";import{routeRecord as m}from"../hub/routes.mjs";import{readHubRules as P,rulesOf as D,ruleLines as G}from"../hub/rules.mjs";import{boardAt as H,linksOf as U,hubLink as W,stopPreviousWatcher as _}from"../hub/boards.mjs";import{parentOf as J,sessionGone as K}from"../hub/live.mjs";import{ackHello as Q,cardName as B,markWorking as C,settingsLines as M,settingsOf as z,WORKING_KINDS as V}from"../board/store.mjs";import{readUsageGate as E,heldUsageEvent as X}from"../shared/usage-gate.mjs";const[O,g]=process.argv.slice(2);(!O||!g)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const Y=f.join(L.homedir(),".claude","kickflip","manifest.json");function A(){try{return m(JSON.parse(c.readFileSync(Y,"utf8")).sites,O)||null}catch{return}}s(A,"site");function v(e){const o=e.filter?new RegExp(e.filter):null,t=Object.create(null);for(const l of e.watch||["data/events.jsonl"]){let r=[];try{r=c.readFileSync(f.resolve(e.dir,l),"utf8").split(`
3
- `).filter(Boolean)}catch{}t[l]=o?r.filter(i=>o.test(i)):r}return t}s(v,"matching");const Z=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,I={ask:s(e=>`new task ${e.id} received`,"ask"),"owner-answer":s(e=>`answer received to question ${e.data?.id}`,"owner-answer"),hello:s(e=>`hello ${e.id} from the hub answered`,"hello"),"overnight-triage":s(e=>`Overnight triage ${e.data?.date} asked: ${e.data?.cards?.length} cards wait on your answers`,"overnight-triage"),"pr-review":s(e=>`review asked on PR #${e.data?.pr}: the board was idle`,"pr-review"),"orchestrator-waits":s(e=>`waiting on you now: ${(e.data?.added||[]).join(", ")}`,"orchestrator-waits"),"review-answer":s(e=>`${e.data?.answer==="skip"?"skip":"post"} answered on the review of PR #${e.data?.pr}`,"review-answer")},R={"item-message":s(e=>`message received from ${e}'s thread`,"item-message"),"card-merge":s(e=>`merge asked on ${e}`,"card-merge"),"card-done":s(e=>`${e} marked done`,"card-done"),"card-bump":s(e=>`${e} bumped`,"card-bump"),"ask-bump":s(e=>`${e} bumped`,"ask-bump"),"ask-edited":s(e=>`${e} edited`,"ask-edited"),"ask-done":s(e=>`${e} marked done`,"ask-done"),"ask-withdrawn":s(e=>`${e} deleted`,"ask-withdrawn"),"card-hold":s((e,o)=>`${e} ${o.data?.hold?"held":"resumed"}`,"card-hold"),"card-unblocked":s(e=>`${e} unblocked`,"card-unblocked"),"prototype-request":s(e=>`prototype asked on ${e}`,"prototype-request"),"reask-request":s(e=>`question asked again on ${e}`,"reask-request"),"builder-ask":s((e,o)=>`${o.data?.ask} from ${e}'s builder: ${o.data?.text}`,"builder-ask"),"owner-check-broken":s((e,o)=>`${e}'s owner-step check can't run: ${o.data?.error}`,"owner-check-broken")};async function ee(e,o){let t;try{t=JSON.parse(o)}catch{return null}if(typeof t?.kind!="string")return null;const l=typeof t.data?.key=="string"?t.data.key:t.kind.startsWith("ask-")&&typeof t.data?.id=="string"?`ask:${t.data.id}`:null,r=l&&await B(e,l).catch(()=>l);return m(I,t.kind)?I[t.kind](t):r&&m(R,t.kind)?R[t.kind](r,t):r?`${t.kind} on ${r}`:`${t.kind} received`}s(ee,"plainLine");function te(e){let o=[];try{o=JSON.parse(c.readFileSync(f.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return o.map(t=>`waits ${t.kind} ${t.ref} ${t.key} since ${t.since}${t.picked?`, picked up ${t.picked}`:""}: ${t.next}`)}s(te,"waitLines");const k=A();k||(console.log("site-removed"),process.exit(0));const w=f.resolve(k.dir,"data",`.watch-cursor-${g}.json`),S=f.resolve(k.dir,"data","watcher.json"),j=[process.ppid,J(process.ppid)],T=s(()=>{j[1]??=J(j[0]),K(g,j)&&process.exit(0)},"orphaned");_(k.dir,O,g);try{c.mkdirSync(f.dirname(w),{recursive:!0}),c.writeFileSync(S,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(c.readFileSync(S,"utf8"));e.pid===process.pid&&c.writeFileSync(S,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let p;try{p=JSON.parse(c.readFileSync(w,"utf8"))}catch{}for(p||(p=Object.fromEntries(Object.entries(v(k)).map(([e,o])=>[e,o.length])),c.mkdirSync(f.dirname(w),{recursive:!0}),c.writeFileSync(w,JSON.stringify(p)));;){await new Promise(r=>setTimeout(r,2e3));const e=A();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==g&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),T();const o=s(r=>Object.fromEntries(Object.entries(r).map(([i,$])=>[i,[...m(p.$usageHeld,i)||[],...$.slice(m(p,i)||0)]])),"pending"),t=s((r,i)=>i.state!=="paused"||!X(r),"eligible"),l=E();if(Object.values(o(v(e))).some(r=>r.some(i=>t(i,l)))){await new Promise(n=>setTimeout(n,2e3)),T();const r=v(e),i=E(),$=o(r);if(!Object.values($).some(n=>n.some(a=>t(a,i))))continue;const b=Object.create(null),N=[],x=[];for(const[n,a]of Object.entries($)){b[n]=a.filter(h=>!t(h,i));for(const h of a.filter(y=>t(y,i))){console.log(`event ${n} ${h}`);const y=await ee(e.dir,h);y&&console.log(y);try{const u=JSON.parse(h);V.includes(u.kind)&&typeof u.id=="string"&&N.push(u.id),u.kind==="hello"&&typeof u.id=="string"&&x.push(u.id)}catch{}}}let d=null;try{d=JSON.parse(c.readFileSync(f.resolve(e.dir,"board.json"),"utf8"))}catch(n){n.code!=="ENOENT"&&(d={})}if(d&&await C(e.dir,N).catch(n=>console.log(`working marks not written (${n.message})`)),d)for(const n of x)await Q(e.dir,n).catch(a=>console.log(`hello ${n} not answered (${a.message})`));if(d)for(const n of te(e.dir))console.log(n);if(d)for(const n of G(P(),D(d)))console.log(`rule ${n}`);if(d)for(const n of M(z(d)))console.log(n);d&&console.log(Z),i.state==="paused"&&console.log(`usage paused ${i.resets_at} ${i.window} ${i.used}%`);try{const n=d&&H(e.dir);if(n)for(const a of[...U(n,{listen:"listening"}),W()])a.ok||console.log(`link ${a.link} ${a.detail}`)}catch(n){console.log(`link registry could not check the links (${n.message})`)}const F=Object.fromEntries(Object.entries(r).map(([n,a])=>[n,a.length]));Object.values(b).some(n=>n.length)&&(F.$usageHeld=b),c.writeFileSync(w,JSON.stringify(F)),process.exit(0)}}
2
+ var _=Object.defineProperty;var t=(e,i)=>_(e,"name",{value:i,configurable:!0});import u from"node:fs";import h from"node:path";import K from"node:os";import{routeRecord as g}from"../hub/routes.mjs";import{readHubRules as C,rulesOf as Q,ruleLines as M}from"../hub/rules.mjs";import{boardAt as Y,linksOf as z,hubLink as V,stopPreviousWatcher as X}from"../hub/boards.mjs";import{parentOf as R,sessionGone as Z}from"../hub/live.mjs";import{ackPing as ee,cardName as te,markWorking as ne,settingsLines as se,settingsOf as ie,WORKING_KINDS as re}from"../board/store.mjs";import{readUsageGate as A,heldUsageEvent as oe,pausedLine as ae}from"../shared/usage-gate.mjs";import{intakeKeyOf as de,waitsAgainLine as ce}from"../board/domain.mjs";const[j,$]=process.argv.slice(2);(!j||!$)&&(console.error("usage: wait-events.mjs <route> <session-id>"),process.exit(2));const le=h.join(K.homedir(),".claude","kickflip","manifest.json");function I(){try{return g(JSON.parse(u.readFileSync(le,"utf8")).sites,j)||null}catch{return}}t(I,"site");function S(e){const i=e.filter?new RegExp(e.filter):null,n=Object.create(null);for(const c of e.watch||["data/events.jsonl"]){let l=[];try{l=u.readFileSync(h.resolve(e.dir,c),"utf8").split(`
3
+ `).filter(Boolean)}catch{}n[c]=i?l.filter(b=>i.test(b)):l}return n}t(S,"matching");const ue=`quiet The owner doesn't read this session's terminal. Answer a prompt typed in it in full. A wake, a task notification or a builder's result is not one: write no text of your own, since board.mjs and this watcher print one line for each thing done. Talk and questions go on the board, never AskUserQuestion; only a failure the board can't show, such as the hub being down, gets one line here. Each message to the owner stands alone in its card's thread: name cards by label (#96), and a pointer such as "above" or "here" must make sense in that thread, never point into this session.`,fe=["main-pulled","settings","ask-done","reviewers-removed","reviewers-added","question-reopen","repo-changed","ping","hello","card-hold","card-done","card-unbump","card-unblocked","grill-more","prototype-request","visual-request"],P=t(e=>{try{return JSON.parse(e)}catch{return null}},"parsed"),pe=t((e,i)=>{const n=P(e);return fe.includes(n?.kind)||!!i&&n!==null&&(n.kind==="intake-handoff"||de(n)!==null)},"recordOnly");function N(e){try{return JSON.parse(u.readFileSync(h.resolve(e.dir,"board.json"),"utf8"))}catch(i){return i.code==="ENOENT"?null:{}}}t(N,"boardOf");async function T(e,i){for(const n of i){let c;try{c=JSON.parse(n)}catch{continue}(c.kind==="ping"||c.kind==="hello")&&typeof c.id=="string"&&await ee(e,c.id).catch(l=>console.log(`ping ${c.id} not answered (${l.message})`))}}t(T,"ackPings");const D={ask:t(e=>`new task ${e.id} received: intake triage sorts it`,"ask"),"owner-answer":t(e=>`answer received to question ${e.data?.id}`,"owner-answer"),ping:t(e=>`ping ${e.id} from the hub answered`,"ping"),hello:t(e=>`ping ${e.id} from the hub answered`,"hello"),"overnight-triage":t(e=>`Overnight triage ${e.data?.date} asked: ${e.data?.cards?.length} cards wait on your answers`,"overnight-triage"),"pr-review":t(e=>`review asked on PR #${e.data?.pr}: the board was idle`,"pr-review"),"orchestrator-waits":t(e=>[e.data?.added?.length&&`waiting on you now: ${e.data.added.join(", ")}`,e.data?.again?.length&&ce(e.data.again,Date.parse(e.ts))].filter(Boolean).join(" \xB7 "),"orchestrator-waits"),"review-answer":t(e=>`${e.data?.answer==="skip"?"skip":"post"} answered on the review of PR #${e.data?.pr}`,"review-answer")},W={"item-message":t((e,i)=>String(i.data?.key).startsWith("ask:")?`message received from ${e}'s thread: intake triage answers it`:i.data?.intent==="build"?`Implement asked on ${e}: it is staging, the message in its notes; judge it, then item set --state ready, or --state grilling or prototyping`:`message received from ${e}'s thread`,"item-message"),"card-merge":t(e=>`merge asked on ${e}`,"card-merge"),"card-done":t(e=>`${e} marked done`,"card-done"),"card-bump":t(e=>`${e} bumped`,"card-bump"),"ask-bump":t(e=>`${e} bumped`,"ask-bump"),"ask-edited":t(e=>`${e} edited`,"ask-edited"),"ask-done":t(e=>`${e} marked done`,"ask-done"),"ask-withdrawn":t(e=>`${e} deleted`,"ask-withdrawn"),"card-hold":t((e,i)=>`${e} ${i.data?.hold?"held":"resumed"}`,"card-hold"),"card-unblocked":t(e=>`${e} unblocked`,"card-unblocked"),"prototype-request":t(e=>`prototype asked on ${e}`,"prototype-request"),"visual-request":t(e=>`visual asked on ${e}: the board launches its visual agent`,"visual-request"),"reask-request":t(e=>`question asked again on ${e}`,"reask-request"),"builder-ask":t((e,i)=>`${i.data?.ask} from ${e}'s builder: ${i.data?.text}`,"builder-ask"),"owner-check-broken":t((e,i)=>`${e}'s owner-step check can't run: ${i.data?.error}`,"owner-check-broken"),"card-added":t(e=>`${e} added by an agent: intake triage links and files it`,"card-added"),"intake-handoff":t((e,i)=>`intake triage handed ${e} to you: ${i.data?.text}`,"intake-handoff")};async function ge(e,i){let n;try{n=JSON.parse(i)}catch{return null}if(typeof n?.kind!="string")return null;const c=typeof n.data?.key=="string"?n.data.key:n.kind.startsWith("ask-")&&typeof n.data?.id=="string"?`ask:${n.data.id}`:null,l=c&&await te(e,c).catch(()=>c);return g(D,n.kind)?D[n.kind](n):l&&g(W,n.kind)?W[n.kind](l,n):l?`${n.kind} on ${l}`:`${n.kind} received`}t(ge,"plainLine");function he(e){let i=[];try{i=JSON.parse(u.readFileSync(h.resolve(e,"data","orchestrator-waits.json"),"utf8")).waits||[]}catch{}return i.map(n=>`waits ${n.kind} ${n.ref} ${n.key} since ${n.since}${n.picked?`, picked up ${n.picked}`:""}: ${n.next}`)}t(he,"waitLines");const y=I();y||(console.log("site-removed"),process.exit(0));const m=h.resolve(y.dir,"data",`.watch-cursor-${$}.json`),q=h.resolve(y.dir,"data","watcher.json"),E=[process.ppid,R(process.ppid)],B=t(()=>{E[1]??=R(E[0]),Z($,E)&&process.exit(0)},"orphaned");X(y.dir,j,$);try{u.mkdirSync(h.dirname(m),{recursive:!0}),u.writeFileSync(q,JSON.stringify({pid:process.pid,since:new Date().toISOString()}))}catch{}process.on("exit",()=>{try{const e=JSON.parse(u.readFileSync(q,"utf8"));e.pid===process.pid&&u.writeFileSync(q,JSON.stringify({...e,exited_at:new Date().toISOString()}))}catch{}});let d;try{d=JSON.parse(u.readFileSync(m,"utf8"))}catch{}for(d||(d=Object.fromEntries(Object.entries(S(y)).map(([e,i])=>[e,i.length])),u.mkdirSync(h.dirname(m),{recursive:!0}),u.writeFileSync(m,JSON.stringify(d)));;){await new Promise(s=>setTimeout(s,2e3));const e=I();if(e===void 0)continue;e===null&&(console.log("site-removed"),process.exit(0)),e.owner?.session&&e.owner.session!==$&&(console.log("handed-over "+JSON.stringify(e.owner)),process.exit(0)),B();const i=t(s=>Object.fromEntries(Object.entries(s).map(([o,r])=>[o,[...g(d.$quietHeld,o)||[],...g(d.$usageHeld,o)||[],...r.slice(g(d,o)||0)]])),"pending"),n=t((s,o)=>o.state!=="paused"||!oe(s),"eligible"),c=N(e)!==null,l=t(s=>pe(s,c),"quiet"),b=t((s,o)=>Object.values(s).some(r=>r.some(a=>n(a,o)&&!l(a))),"wakes"),G=A({dir:e.dir}),k=S(e);if(!b(i(k),G)){const s=Object.fromEntries(Object.entries(k).map(([r,a])=>[r,a.slice(g(d,r)||0).filter(l)])),o=Object.fromEntries(Object.entries(k).map(([r,a])=>[r,a.slice(g(d,r)||0).filter(f=>!l(f))]));if(Object.values(s).some(r=>r.length)){N(e)&&await T(e.dir,Object.values(s).flat());const r=t((a,f)=>Object.fromEntries(Object.keys(k).map(v=>[v,[...g(a,v)||[],...f[v]]])),"append");d={...Object.fromEntries(Object.entries(k).map(([a,f])=>[a,f.length])),$quietHeld:r(d.$quietHeld,s),$usageHeld:r(d.$usageHeld,o)},Object.values(d.$usageHeld).some(a=>a.length)||delete d.$usageHeld,u.writeFileSync(m,JSON.stringify(d))}continue}await new Promise(s=>setTimeout(s,2e3)),B();const x=S(e),w=A({dir:e.dir}),F=i(x);if(!b(F,w))continue;const O=Object.create(null),J=[],U=new Set(Object.values(d.$quietHeld||{}).flat()),H=[];for(const[s,o]of Object.entries(F)){O[s]=o.filter(r=>!n(r,w));for(const r of o.filter(a=>n(a,w))){U.has(r)||H.push(r),console.log(`event ${s} ${r}`);const a=await ge(e.dir,r);a&&console.log(a);const f=P(r);f&&re.includes(f.kind)&&typeof f.id=="string"&&!l(r)&&J.push(f.id)}}const p=N(e);if(p&&await ne(e.dir,J).catch(s=>console.log(`working marks not written (${s.message})`)),p&&await T(e.dir,H),p)for(const s of he(e.dir))console.log(s);if(p)for(const s of M(C(),Q(p)))console.log(`rule ${s}`);if(p)for(const s of se(ie(p)))console.log(s);p&&console.log(ue),w.state==="paused"&&console.log(ae(w));try{const s=p&&Y(e.dir);if(s)for(const o of[...z(s,{listen:"listening"}),V()])o.ok||console.log(`link ${o.link} ${o.detail}`)}catch(s){console.log(`link registry could not check the links (${s.message})`)}const L=Object.fromEntries(Object.entries(x).map(([s,o])=>[s,o.length]));Object.values(O).some(s=>s.length)&&(L.$usageHeld=O),u.writeFileSync(m,JSON.stringify(L)),process.exit(0)}
@@ -0,0 +1,2 @@
1
+ var v=Object.defineProperty;var t=(e,n)=>v(e,"name",{value:n,configurable:!0});import u from"node:fs";import y from"node:path";import{spawn as w,execFileSync as h}from"node:child_process";import{claudeBin as _,inherited as I}from"../hub/sessions.mjs";function A(e){try{return y.resolve(e,h("git",["-C",e,"rev-parse","--git-common-dir"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim())}catch{return null}}t(A,"gitCommonDir");const O={claude:{bin:_,args:t(({prompt:e,model:n="opus"})=>["-p",e,"--permission-mode","auto","--model",n,"--output-format","stream-json","--verbose"],"args"),session:t(e=>{try{const n=JSON.parse(e);return n.type==="system"&&n.subtype==="init"?n.session_id??null:null}catch{return null}},"session")},codex:{bin:t(()=>process.env.KICKFLIP_CODEX||"codex","bin"),args:t(({prompt:e,cwd:n,site:c})=>["exec","--color","never","--cd",n,"--sandbox","workspace-write",...[c,A(n)].filter(Boolean).flatMap(l=>["--add-dir",l]),"-c","sandbox_workspace_write.network_access=true",e],"args"),session:t(e=>e.match(/^session id: (\S+)/)?.[1]??null,"session")}},P=15e3;function T(e,n,c,l){return new Promise(b=>{let o=!1;const f=t(i=>{o||(o=!0,clearInterval(m),clearTimeout(r),e.off("exit",S),b(i))},"finish"),s=t(()=>{const i=u.readFileSync(n,"utf8").slice(c);for(const d of i.split(`
2
+ `)){const x=l(d);if(x)return f(x)}},"scan"),m=setInterval(s,100),r=setTimeout(()=>f(null),P),S=t(()=>{s(),f(null)},"exited");e.once("exit",S)})}t(T,"sessionOf");function N({kind:e,model:n,cwd:c,site:l,prompt:b,log:o,bin:f}){const s=O[e];if(!s)throw new Error(`no agent of kind ${e}`);const m=f??s.bin();u.mkdirSync(y.dirname(o),{recursive:!0});const r=u.openSync(o,"a"),S=u.fstatSync(r).size,i=Object.fromEntries(Object.entries(process.env).filter(([d])=>!I(d)));return y.isAbsolute(m)&&(i.PATH=`${y.dirname(m)}:${i.PATH||""}`),new Promise((d,x)=>{const a=w(m,s.args({prompt:b,model:n,cwd:c,site:l}),{cwd:c,env:i,detached:!0,stdio:["ignore",r,r]}),g=new Promise(p=>a.once("exit",()=>p()));a.once("spawn",async()=>{u.closeSync(r);const p=await T(a,o,S,s.session);a.unref(),d({pid:a.pid,sessionId:p,log:o,exited:g})}),a.once("error",p=>{u.closeSync(r),x(p)})})}t(N,"launchAgent");export{N as launchAgent};
@@ -1,5 +1,5 @@
1
- var I=Object.defineProperty;var r=(e,n)=>I(e,"name",{value:n,configurable:!0});import v from"node:fs/promises";import L from"node:os";import g from"node:path";import{boardRepo as q}from"../hub/board-repo.mjs";import{samePath as J}from"../hub/boards.mjs";import{cloneRoot as P}from"../shared/repos.mjs";import{readUsageGate as T,pauseReason as U}from"../shared/usage-gate.mjs";import{reviewWaits as W}from"../shared/skills.mjs";import{BoardError as O,addItem as x,appendThread as _,boardConfig as K,cardName as N,changeLineup as Q,createLineup as G,itemSources as F,parseKey as H,readJSON as A,resolveQuestion as E,setItem as M,startBuilder as X,topicQuestions as B,wavesDir as R}from"./store.mjs";const $=r(e=>g.join(e,"data","arch-reviews.json"),"recordsFile"),C=r(async e=>(await A($(e),{reviews:[]})).reviews||[],"readReviews"),z={paths:["hub/","board/","shared/","CONTEXT.md","docs/adr/"],data:["~/.claude/kickflip/manifest.json","~/.claude/kickflip/sites/*/data/wave.json","~/.claude/kickflip/sites/*/data/owner.json","~/.claude/kickflip/sites/*/data/events.jsonl"]},V=r(({github:e,repo:n})=>(e?e.split("/").pop():g.basename(n||""))||"this repo","repoName");function pe(e,n,s,{repo:d,waits:h}){const p=new Map(n.map(a=>[a.key,a])),o=r(a=>{const u=p.get(a.key);if(!u)return null;const t=r(i=>i.key!==a.key&&(a.lineup?i.lineup?.slug===a.wave:i.wave===a.wave),"inWave"),c=u.lane!=="done";return{key:a.key,ref:u.ref,wave:a.title,at:a.at,open:c,running:c&&!u.questions,findings:s.filter(i=>i.topic===`item:${a.key}`&&!i.round_of&&!i.confirm_of).length,built:n.filter(i=>t(i)&&i.lane==="done"&&i.status!=="dropped").length}},"view");return{repo:d,waits:h,last:[...e].reverse().map(o).find(Boolean)||null}}r(pe,"archOf");const Y=r(e=>e.toLocaleDateString("en-CA").replaceAll("-",""),"stampOf"),Z=r(e=>e.toLocaleDateString("en-US",{month:"short",day:"numeric"}),"dayOf");async function D(e,n){let s=e;for(let d=2;await n(s);d++)s=`${e}-${d}`;return s}r(D,"freeSlug");const ee=r(e=>{throw new O(e)},"fail"),te=r(e=>v.stat(e).then(()=>!0,()=>!1),"exists");async function fe(e,n,{now:s=new Date,home:d=L.homedir()}={}){const h=W(d);if(h)throw Object.assign(new O(h),{status:409});const p=T({home:d});if(p.state==="paused")throw Object.assign(new O(U(p)),{status:409});const o=q(n.route),a=V(o),u=`Architecture ${Z(s)}`,t=`arch-${Y(s)}`,c=await F(e),i=(await K(e)).items==="waves";let f,w=null,l;if(i){f=await D(t,S=>te(g.join(R(),S)));const y=g.join(R(),f,"wave.json");await v.mkdir(g.dirname(y),{recursive:!0}),await v.writeFile(y,JSON.stringify({title:u,...o.github?{repo:o.github}:{},items:[]},null,2)+`
2
- `),l=(await x(e,`${f}/audit`,{title:`Architecture review of ${a}`})).key}else{const[y]=c,S=(await Promise.all(c.map(async b=>(await A(b.file,{}))?.lineups||[]))).flat();w=await D(t,b=>c.some(j=>j.slug===b)||S.some(j=>j.slug===b)),f=y.slug,l=(await x(e,f,{title:`Architecture review of ${a}`})).key}w&&await G(e,w,{title:u,goal:`Act on the architecture review of ${a}`,phases:[l],note:`${await N(e,l)} is the audit of ${a}: its Notes are the report, and it asks one question per finding. Each finding you don't skip becomes a card after it, built from the option you pick.`}),await X(e,l,{label:"Architecture review"}),await _(e,l,{text:`Started an architecture review of ${a}. Its report becomes this card's Notes, with one question per finding.`});const k=await C(e);k.push({key:l,wave:w||f,lineup:!!w,title:u,repo:o.repo,at:s.toISOString()}),await v.mkdir(g.dirname($(e)),{recursive:!0}),await v.writeFile($(e)+".tmp",JSON.stringify({reviews:k},null,2)+`
3
- `),await v.rename($(e)+".tmp",$(e));const m={key:l,repo:o.repo,github:o.github||null,branch:o.branch||null,wave:w||f,lineup:!!w,...o.repo&&J(o.repo,P())?{scope:z}:{}};return{key:l,data:m}}r(fe,"startReview");async function we(e,n){const s=(await C(e)).find(t=>t.key===n)||ee(`${n} is not an architecture review's audit card`),{wave:d}=H(n),{asked:h}=await B(e,`item:${n}`),p=[];for(const t of h.filter(c=>c.state==="answered")){const c=t.answers.at(-1),i=t.options.find(m=>m.id===c.choice);if(!i)continue;if(i.id==="skip"||i.label==="Skip"){await E(e,t.id,"Skipped."),p.push(`skipped: ${t.id}`);continue}const f=[i.detail,...(i.practice||[]).map(m=>`- ${m}`),c.note.trim()&&`Owner's note: ${c.note.trim()}`,`From the finding: ${t.question}`].filter(Boolean).join(`
1
+ var I=Object.defineProperty;var r=(e,n)=>I(e,"name",{value:n,configurable:!0});import v from"node:fs/promises";import L from"node:os";import g from"node:path";import{boardRepo as W}from"../hub/board-repo.mjs";import{samePath as q}from"../hub/boards.mjs";import{cloneRoot as J}from"../shared/repos.mjs";import{readUsageGate as P,pauseReason as T,holdsWork as U}from"../shared/usage-gate.mjs";import{reviewWaits as _}from"../shared/skills.mjs";import{unlanded as K}from"./domain.mjs";import{BoardError as O,addItem as x,appendThread as Q,boardConfig as G,cardName as N,changeLineup as H,createLineup as M,itemSources as F,parseKey as X,readJSON as A,resolveQuestion as E,setItem as z,startBuilder as V,topicQuestions as B,wavesDir as R}from"./store.mjs";const $=r(e=>g.join(e,"data","arch-reviews.json"),"recordsFile"),C=r(async e=>(await A($(e),{reviews:[]})).reviews||[],"readReviews"),Y={paths:["hub/","board/","shared/","CONTEXT.md","docs/adr/"],data:["~/.claude/kickflip/manifest.json","~/.claude/kickflip/sites/*/data/wave.json","~/.claude/kickflip/sites/*/data/owner.json","~/.claude/kickflip/sites/*/data/events.jsonl"]},Z=r(({github:e,repo:n})=>(e?e.split("/").pop():g.basename(n||""))||"this repo","repoName");function me(e,n,s,{repo:d,waits:h}){const p=new Map(n.map(a=>[a.key,a])),o=r(a=>{const u=p.get(a.key);if(!u)return null;const t=r(i=>i.key!==a.key&&(a.lineup?i.lineup?.slug===a.wave:i.wave===a.wave),"inWave"),c=u.lane!=="done";return{key:a.key,ref:u.ref,wave:a.title,at:a.at,open:c,running:c&&!u.questions,findings:s.filter(i=>i.topic===`item:${a.key}`&&!i.round_of&&!i.confirm_of).length,built:n.filter(i=>t(i)&&i.lane==="done"&&!K(i)).length}},"view");return{repo:d,waits:h,last:[...e].reverse().map(o).find(Boolean)||null}}r(me,"archOf");const ee=r(e=>e.toLocaleDateString("en-CA").replaceAll("-",""),"stampOf"),te=r(e=>e.toLocaleDateString("en-US",{month:"short",day:"numeric"}),"dayOf");async function D(e,n){let s=e;for(let d=2;await n(s);d++)s=`${e}-${d}`;return s}r(D,"freeSlug");const ae=r(e=>{throw new O(e)},"fail"),ie=r(e=>v.stat(e).then(()=>!0,()=>!1),"exists");async function he(e,n,{now:s=new Date,home:d=L.homedir()}={}){const h=_(d);if(h)throw Object.assign(new O(h),{status:409});const p=P({home:d,dir:e});if(U(p))throw Object.assign(new O(T(p)),{status:409});const o=W(n.route),a=Z(o),u=`Architecture ${te(s)}`,t=`arch-${ee(s)}`,c=await F(e),i=(await G(e)).items==="waves";let f,w=null,l;if(i){f=await D(t,S=>ie(g.join(R(),S)));const y=g.join(R(),f,"wave.json");await v.mkdir(g.dirname(y),{recursive:!0}),await v.writeFile(y,JSON.stringify({title:u,...o.github?{repo:o.github}:{},items:[]},null,2)+`
2
+ `),l=(await x(e,`${f}/audit`,{title:`Architecture review of ${a}`})).key}else{const[y]=c,S=(await Promise.all(c.map(async b=>(await A(b.file,{}))?.lineups||[]))).flat();w=await D(t,b=>c.some(j=>j.slug===b)||S.some(j=>j.slug===b)),f=y.slug,l=(await x(e,f,{title:`Architecture review of ${a}`})).key}w&&await M(e,w,{title:u,goal:`Act on the architecture review of ${a}`,phases:[l],note:`${await N(e,l)} is the audit of ${a}: its Notes are the report, and it asks one question per finding. Each finding you don't skip becomes a card after it, built from the option you pick.`}),await V(e,l,{label:"Architecture review"}),await Q(e,l,{text:`Started an architecture review of ${a}. Its report becomes this card's Notes, with one question per finding.`});const k=await C(e);k.push({key:l,wave:w||f,lineup:!!w,title:u,repo:o.repo,at:s.toISOString()}),await v.mkdir(g.dirname($(e)),{recursive:!0}),await v.writeFile($(e)+".tmp",JSON.stringify({reviews:k},null,2)+`
3
+ `),await v.rename($(e)+".tmp",$(e));const m={key:l,repo:o.repo,github:o.github||null,branch:o.branch||null,wave:w||f,lineup:!!w,...o.repo&&q(o.repo,J())?{scope:Y}:{}};return{key:l,data:m}}r(he,"startReview");async function ve(e,n){const s=(await C(e)).find(t=>t.key===n)||ae(`${n} is not an architecture review's audit card`),{wave:d}=X(n),{asked:h}=await B(e,`item:${n}`),p=[];for(const t of h.filter(c=>c.state==="answered")){const c=t.answers.at(-1),i=t.options.find(m=>m.id===c.choice);if(!i)continue;if(i.id==="skip"||i.label==="Skip"){await E(e,t.id,"Skipped."),p.push(`skipped: ${t.id}`);continue}const f=[i.detail,...(i.practice||[]).map(m=>`- ${m}`),c.note.trim()&&`Owner's note: ${c.note.trim()}`,`From the finding: ${t.question}`].filter(Boolean).join(`
4
4
 
5
- `),w=(await A((await F(e)).find(m=>m.slug===d).file,{items:[]})).items.at(-1)?.id,l=await x(e,d,{title:i.label,notes:f,...s.lineup?{}:{deps:w}});s.lineup&&await Q(e,s.wave,{add:l.key});const k=await N(e,l.key);await E(e,t.id,`Filed as ${k}.`),p.push(`filed: ${k} from ${t.id}`,...l.lines||[])}const o=(await B(e,`item:${n}`)).asked.filter(t=>t.state!=="resolved");if(o.length)return{lines:[...p,`waiting: ${o.map(t=>t.id).join(", ")}`]};const a=(await B(e,`item:${n}`)).asked.filter(t=>/^Filed as /.test(t.resolved||"")).map(t=>t.resolved.slice(9,-1)),u=await M(e,n,{status:"done",text:a.length?`Every finding is settled: filed ${a.join(", ")}.`:"Every finding is settled: none filed."});return{lines:[...p,...u.lines,`closed: ${await N(e,n)}`]}}r(we,"fileFindings");export{z as HUB_SCOPE,pe as archOf,we as fileFindings,C as readReviews,V as repoName,fe as startReview};
5
+ `),w=(await A((await F(e)).find(m=>m.slug===d).file,{items:[]})).items.at(-1)?.id,l=await x(e,d,{title:i.label,notes:f,...s.lineup?{}:{deps:w}});s.lineup&&await H(e,s.wave,{add:l.key});const k=await N(e,l.key);await E(e,t.id,`Filed as ${k}.`),p.push(`filed: ${k} from ${t.id}`,...l.lines||[])}const o=(await B(e,`item:${n}`)).asked.filter(t=>t.state!=="resolved");if(o.length)return{lines:[...p,`waiting: ${o.map(t=>t.id).join(", ")}`]};const a=(await B(e,`item:${n}`)).asked.filter(t=>/^Filed as /.test(t.resolved||"")).map(t=>t.resolved.slice(9,-1)),u=await z(e,n,{done:!0,text:a.length?`Every finding is settled: filed ${a.join(", ")}.`:"Every finding is settled: none filed."});return{lines:[...p,...u.lines,`closed: ${await N(e,n)}`]}}r(ve,"fileFindings");export{Y as HUB_SCOPE,me as archOf,ve as fileFindings,C as readReviews,Z as repoName,he as startReview};