cyc-stack 0.9.1 → 0.11.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 (48) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/README.md +3 -2
  5. package/bin/cyc.mjs +72 -20
  6. package/docs/README.md +2 -0
  7. package/docs/context.md +18 -10
  8. package/docs/project-tools.md +2 -12
  9. package/docs/runtime.md +5 -1
  10. package/docs/work-assessments.md +4 -4
  11. package/docs/work-queue.md +187 -0
  12. package/methods/cyc-build/SKILL.md +1 -1
  13. package/methods/cyc-context/SKILL.md +28 -20
  14. package/methods/cyc-context/references/evidence.md +1 -1
  15. package/methods/cyc-context/references/templates.md +30 -18
  16. package/methods/cyc-design/frontend-design/SKILL.md +132 -21
  17. package/methods/cyc-design/frontend-design/references/color.md +43 -56
  18. package/methods/cyc-design/frontend-design/references/craft-rules.md +17 -14
  19. package/methods/cyc-design/frontend-design/references/decision-sheet.md +95 -93
  20. package/methods/cyc-design/frontend-design/references/experience-review.md +15 -6
  21. package/methods/cyc-design/frontend-design/references/field-guide.md +439 -0
  22. package/methods/cyc-design/frontend-design/references/generic-tells.md +83 -32
  23. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +5 -5
  24. package/methods/cyc-design/frontend-design/references/patterns.md +108 -0
  25. package/methods/cyc-design/frontend-design/references/reference-standards.md +118 -22
  26. package/methods/cyc-design/frontend-design/references/typography.md +59 -44
  27. package/methods/cyc-design/frontend-design/references/ux-foundations.md +2 -1
  28. package/methods/cyc-design/frontend-design/references/visual-material.md +43 -8
  29. package/methods/cyc-design/frontend-design/scripts/contrast.mjs +39 -0
  30. package/methods/cyc-design/frontend-design/scripts/first-screen.mjs +911 -0
  31. package/methods/cyc-design/frontend-design/scripts/photo-text.mjs +230 -0
  32. package/methods/cyc-verify/SKILL.md +1 -1
  33. package/package.json +6 -1
  34. package/plugin.json +1 -1
  35. package/scripts/catalog.mjs +5 -3
  36. package/scripts/context-review.mjs +364 -261
  37. package/scripts/hub-page.mjs +275 -0
  38. package/scripts/hub.mjs +139 -0
  39. package/scripts/project-tools.mjs +14 -6
  40. package/scripts/queue-board.mjs +287 -0
  41. package/scripts/queue.mjs +283 -0
  42. package/scripts/run-gate.mjs +8 -5
  43. package/scripts/runtime.mjs +270 -19
  44. package/scripts/source-snapshot.mjs +20 -2
  45. package/scripts/work-review.mjs +4 -3
  46. package/skills/cyc/SKILL.md +12 -4
  47. package/skills/cyc/references/playbooks/experience.md +2 -0
  48. package/skills/cyc/references/playbooks/plan.md +2 -0
@@ -0,0 +1,275 @@
1
+ // The hub's one page. Self-contained: no font, script, image or request leaves this machine. Its
2
+ // script builds every element with textContent, so what an agent writes is shown, never run.
3
+ // Design decisions: docs/maintainers/hub-design.md.
4
+ export const hubPage = String.raw`<!doctype html>
5
+ <html lang="en">
6
+ <head>
7
+ <meta charset="utf-8">
8
+ <meta name="viewport" content="width=device-width, initial-scale=1">
9
+ <title>CYC hub</title>
10
+ <style>
11
+ :root{--paper:#F4F1EA;--surface:#FFFDF8;--ink:#1C1B18;--soft:#5A554C;--rule:#D9D2C3;--signal:#B4420F;--signal-wash:#FBE9DD;--builder:#0B5C63;--reviewer:#5A3E9B;--done:#1E6B41;
12
+ --display:"Bahnschrift","DIN Alternate","Avenir Next Condensed","Franklin Gothic Medium","Arial Narrow",sans-serif;--body:"Segoe UI Variable Text","Segoe UI",system-ui,-apple-system,"Helvetica Neue",sans-serif;--mono:ui-monospace,"Cascadia Mono",Consolas,Menlo,monospace}
13
+ @media (prefers-color-scheme:dark){:root{--paper:#151410;--surface:#1F1D18;--ink:#F1EDE3;--soft:#B3AC9D;--rule:#3A362D;--signal:#F59E5B;--signal-wash:#3A2415;--builder:#62CDD3;--reviewer:#BDA8F2;--done:#74DDA6}}
14
+ *{box-sizing:border-box}
15
+ html{background:var(--paper);color:var(--ink);font:16px/1.55 var(--body);-webkit-text-size-adjust:100%}
16
+ body{margin:0}
17
+ h1,h2,h3,p,ol{margin:0;padding:0}
18
+ ol{list-style:none}
19
+ a{color:inherit}
20
+ :focus-visible{outline:3px solid var(--signal);outline-offset:2px;border-radius:2px}
21
+ .skip{position:absolute;left:-999px;top:8px;background:var(--surface);padding:8px 12px;border:1px solid var(--rule)}
22
+ .skip:focus{left:8px;z-index:5}
23
+ .vh{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
24
+ .top{display:flex;flex-wrap:wrap;gap:8px 24px;align-items:center;justify-content:space-between;padding:14px clamp(16px,4vw,40px);border-bottom:1px solid var(--rule)}
25
+ .brand{display:flex;align-items:baseline;gap:12px;min-width:0}
26
+ .name{font:600 15px/1 var(--display);letter-spacing:.12em;text-transform:uppercase}
27
+ .project{color:var(--soft);font:14px var(--mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
28
+ .tools{display:flex;flex-wrap:wrap;gap:8px 16px;align-items:center}
29
+ .tools label{font-size:14px;color:var(--soft)}
30
+ select{font:14px var(--body);color:var(--ink);background:var(--surface);border:1px solid var(--rule);border-radius:4px;padding:6px 8px;max-width:min(60vw,320px)}
31
+ .live{display:flex;align-items:center;gap:8px;font-size:14px;color:var(--soft)}
32
+ .dot{width:9px;height:9px;border-radius:50%;background:var(--done)}
33
+ .live.lost{color:var(--signal)}
34
+ .live.lost .dot{background:var(--signal)}
35
+ main{padding:clamp(20px,4vw,40px);max-width:1280px;margin:0 auto}
36
+ .line{margin-bottom:clamp(24px,4vw,40px)}
37
+ #goal{font:600 clamp(26px,4.2vw,44px)/1.08 var(--display);letter-spacing:-.01em;max-width:22ch;text-wrap:balance;overflow-wrap:anywhere}
38
+ #line-state{margin-top:10px;color:var(--soft);font-size:15px}
39
+ #line-state b{color:var(--ink);font-weight:600}
40
+ .track{display:flex;margin-top:28px;overflow-x:auto;padding:6px 2px 10px}
41
+ .stop{flex:1 0 150px;position:relative;padding:34px 16px 0 0;min-width:0}
42
+ .stop::before{content:"";position:absolute;left:0;right:0;top:12px;height:2px;background:var(--rule)}
43
+ .stop:last-child::before{right:auto;width:26px}
44
+ .pin{position:absolute;left:0;top:0;width:26px;height:26px;border-radius:50%;background:var(--paper);border:2px solid var(--rule);display:grid;place-items:center;font:600 13px/1 var(--display);color:var(--soft)}
45
+ .stop.done .pin{background:var(--done);border-color:var(--done);color:var(--paper)}
46
+ .stop.done::before{background:var(--done)}
47
+ .stop.now .pin{background:var(--ink);border-color:var(--ink);color:var(--paper)}
48
+ .stop.now .pin::after{content:"";position:absolute;inset:-7px;border-radius:50%;border:2px solid var(--ink);opacity:.35;animation:pulse 1.8s ease-out infinite}
49
+ .stop.halt .pin{background:var(--signal);border-color:var(--signal);color:var(--paper)}
50
+ .stop.still .pin::after{display:none}
51
+ @keyframes pulse{from{transform:scale(.8);opacity:.5}to{transform:scale(1.25);opacity:0}}
52
+ .stop h3{font:600 17px/1.2 var(--display);letter-spacing:.01em;overflow-wrap:anywhere}
53
+ .stop .what{font-size:14px;color:var(--soft);margin-top:2px}
54
+ .stop.now .what,.stop.halt .what{color:var(--ink)}
55
+ .stop .more{font-size:13px;color:var(--soft);margin-top:2px}
56
+ .stop.halt .more{color:var(--signal)}
57
+ .floor{display:grid;grid-template-columns:minmax(0,1fr) minmax(260px,340px);grid-template-areas:"talk you" "talk log";grid-template-rows:auto 1fr;gap:32px clamp(24px,4vw,48px);align-items:start}
58
+ .talk{grid-area:talk}.you{grid-area:you}.log{grid-area:log}
59
+ h2{font:600 13px/1 var(--display);letter-spacing:.14em;text-transform:uppercase;color:var(--soft);padding-bottom:10px;border-bottom:1px solid var(--rule);margin-bottom:6px}
60
+ .talk{outline:none}
61
+ .msg{padding:16px 0 16px 16px;border-bottom:1px solid var(--rule);border-left:3px solid var(--rule);margin-left:1px;transition:background-color 1.6s}
62
+ .msg.builder{border-left-color:var(--builder)}
63
+ .msg.reviewer{border-left-color:var(--reviewer)}
64
+ .msg.person{border-left-color:var(--signal)}
65
+ .msg.fresh{background:var(--signal-wash)}
66
+ .who{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;font-size:14px;color:var(--soft)}
67
+ .who strong{font:600 14px/1.2 var(--display);letter-spacing:.08em;text-transform:uppercase}
68
+ .builder .who strong{color:var(--builder)}
69
+ .reviewer .who strong{color:var(--reviewer)}
70
+ .person .who strong{color:var(--signal)}
71
+ .who time,.who .num{font:13px var(--mono);color:var(--soft)}
72
+ .who .num{margin-left:auto}
73
+ .re{margin-top:6px;font-size:14px;color:var(--soft);border-left:2px solid var(--rule);padding-left:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
74
+ .text{margin-top:8px;max-width:72ch;overflow-wrap:anywhere;white-space:pre-wrap}
75
+ .text code,.card code{font:.9em var(--mono);background:var(--surface);border:1px solid var(--rule);border-radius:3px;padding:0 4px}
76
+ .foot{display:flex;flex-wrap:wrap;gap:8px 12px;align-items:center;margin-top:10px}
77
+ .chip{font:600 12px/1 var(--display);letter-spacing:.08em;text-transform:uppercase;padding:5px 8px;border-radius:3px;border:1px solid var(--rule);color:var(--soft)}
78
+ .chip.open{border-color:var(--signal);color:var(--signal);background:var(--signal-wash)}
79
+ .chip.ok{border-color:var(--done);color:var(--done)}
80
+ .closed{font-size:14px;color:var(--soft)}
81
+ button{font:14px var(--body);color:var(--ink);background:none;border:1px solid var(--rule);border-radius:4px;padding:6px 10px;min-height:32px;cursor:pointer}
82
+ button:hover{border-color:var(--soft)}
83
+ .empty{padding:20px 0;color:var(--soft);max-width:52ch}
84
+ .card{padding:14px 0;border-bottom:1px solid var(--rule)}
85
+ .card .ask{font-weight:600}
86
+ .card .by{font-size:14px;color:var(--soft);margin-top:4px}
87
+ .card .by a{display:inline-block;min-width:24px;padding:3px 6px;margin:-3px 0;text-align:center}
88
+ .you.has h2{color:var(--signal);border-bottom-color:var(--signal)}
89
+ .how{font-size:14px;color:var(--soft);margin-top:12px}
90
+ #activity li{display:grid;grid-template-columns:auto minmax(0,1fr);gap:2px 12px;padding:9px 0;border-bottom:1px solid var(--rule);font-size:14px}
91
+ #activity time{font:13px var(--mono);color:var(--soft);padding-top:1px}
92
+ #activity b{font:600 13px/1.2 var(--display);letter-spacing:.06em;text-transform:uppercase}
93
+ .jump{position:sticky;bottom:16px;margin:16px auto 0;display:none;background:var(--ink);color:var(--paper);border-color:var(--ink)}
94
+ .jump.show{display:block}
95
+ .problem{margin-top:16px;padding:14px 16px;border:1px solid var(--signal);border-radius:4px;color:var(--signal);background:var(--signal-wash);max-width:72ch}
96
+ @media (max-width:860px){.floor{grid-template-columns:minmax(0,1fr);grid-template-areas:"you" "talk" "log";grid-template-rows:auto}.stop{flex-basis:132px}}
97
+ @media (prefers-reduced-motion:reduce){.stop.now .pin::after{animation:none}.msg{transition:none}}
98
+ </style>
99
+ </head>
100
+ <body>
101
+ <a class="skip" href="#talk">Skip to the conversation</a>
102
+ <header class="top">
103
+ <div class="brand"><span class="name">CYC hub</span><span class="project" id="project"></span></div>
104
+ <div class="tools">
105
+ <span id="picker" hidden><label for="queue">Queue</label> <select id="queue"></select></span>
106
+ <div class="live" id="live" role="status"><span class="dot" aria-hidden="true"></span><span id="live-text">Connecting</span></div>
107
+ </div>
108
+ </header>
109
+ <main>
110
+ <section class="line" aria-labelledby="goal">
111
+ <h1 id="goal">Opening the hub</h1>
112
+ <p id="line-state"></p>
113
+ <div id="problem" class="problem" hidden></div>
114
+ <ol id="units" class="track" aria-label="The line: each unit of work in order"></ol>
115
+ </section>
116
+ <div class="floor" id="floor" hidden>
117
+ <section class="you" id="you-box" aria-labelledby="you-h"><h2 id="you-h">Waiting on you</h2><div id="you"></div><p id="say" class="vh" role="status"></p></section>
118
+ <section id="talk" class="talk" aria-labelledby="talk-h" tabindex="-1">
119
+ <h2 id="talk-h">Conversation</h2>
120
+ <div id="messages" aria-live="polite" aria-relevant="additions"></div>
121
+ <button class="jump" id="jump" type="button">New messages below</button>
122
+ </section>
123
+ <section class="log" aria-labelledby="log-h"><h2 id="log-h">Activity</h2><ol id="activity"></ol></section>
124
+ </div>
125
+ </main>
126
+ <script>
127
+ (function () {
128
+ var byId = function (id) { return document.getElementById(id); };
129
+ // Characters that reverse or re-order the text around them are dropped: what is shown reads as written.
130
+ var plain = function (text) { return String(text).replace(/[\u202A-\u202E\u2066-\u2069]/g, ''); };
131
+ var el = function (tag, cls, text) { var node = document.createElement(tag); if (cls) node.className = cls; if (text !== undefined) node.textContent = plain(text); return node; };
132
+ var clock = function (iso) { var d = new Date(iso); return isNaN(d) ? '' : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); };
133
+ // Words between a pair of backticks are shown as code, and one left without a partner is shown
134
+ // as it is. Everything is set as text, never as markup.
135
+ var mark = String.fromCharCode(96);
136
+ var prose = function (node, text) {
137
+ var parts = plain(text).split(mark); if (parts.length % 2 === 0) parts.push(parts.splice(-2).join(mark));
138
+ parts.forEach(function (part, i) { if (!part) return; node.appendChild(i % 2 ? el('code', '', part) : document.createTextNode(part)); }); return node;
139
+ };
140
+ var speaker = function (who) { return who.role === 'person' ? 'You' : who.role === 'reviewer' ? 'Reviewer' : 'Builder'; };
141
+ var listener = function (to) { return to.role === 'person' ? 'you' : to.role === 'all' ? 'everyone' : to.role === 'reviewer' ? 'the reviewer' : 'the builder of ' + to.unit; };
142
+ var said = function (m) {
143
+ var s = m.from.role === 'person' ? '' : 's';
144
+ if (m.kind === 'question') return 'ask' + s + ' ' + listener(m.to);
145
+ if (m.kind === 'finding') return 'found a problem, for ' + listener(m.to);
146
+ if (m.kind === 'notice') return m.topic === 'ready-for-review' ? 'asks for a review' : m.topic === 'review-done' ? 'signs off the review' : 'tell' + s + ' ' + listener(m.to);
147
+ return { fixed: 'fixed it', declined: 'declined it', assumed: 'went on with an assumption', withdrawn: 'took it back' }[m.disposition] || 'answer' + s + ' ' + listener(m.to);
148
+ };
149
+ var how = { fixed: 'Fixed', declined: 'Declined', assumed: 'Went on with an assumption', withdrawn: 'Taken back' };
150
+ var words = { done: 'Done', 'in-progress': 'In progress', ready: 'Next up', waiting: 'Waiting', halted: 'Halted: needs you', skipped: 'Skipped', cancelled: 'Cancelled' };
151
+ var lines = { ready: 'Ready for the next unit', 'in-progress': 'Work in progress', halted: 'Halted: a unit needs your decision', complete: 'Complete', ended: 'Nothing more can start', cancelled: 'Cancelled' };
152
+ var drawn = {}, shown = {}, keys = {}, first = true, lastSeen = 0, current = null, waited = 0, tag = '';
153
+ // A section is redrawn only when what it shows changed, so focus and a selection in it are kept.
154
+ var changed = function (name, data) { var key = JSON.stringify(data); if (keys[name] === key) return false; keys[name] = key; return true; };
155
+
156
+ function unitsOf(state) {
157
+ if (!changed('units', state.units)) return;
158
+ var list = byId('units'); list.textContent = '';
159
+ state.units.forEach(function (unit, index) {
160
+ var cls = unit.status === 'done' ? 'done' : unit.status === 'in-progress' ? (unit.paused ? 'now still' : 'now') : unit.status === 'halted' ? 'halt' : '';
161
+ var item = el('li', 'stop ' + cls);
162
+ var pin = el('span', 'pin', unit.status === 'done' ? '✓' : unit.status === 'halted' ? '!' : String(index + 1)); pin.setAttribute('aria-hidden', 'true');
163
+ item.appendChild(pin); item.appendChild(el('h3', '', unit.id));
164
+ item.appendChild(el('p', 'what', unit.paused ? 'Paused' + (unit.doing ? ' while ' + unit.doing : '') : unit.status === 'in-progress' && unit.doing ? 'In progress: ' + unit.doing : words[unit.status] || unit.status));
165
+ var more = unit.reason || (unit.waitsOn ? 'After ' + unit.waitsOn.join(', ') : unit.reviewer ? 'Reviewer ' + unit.reviewer : unit.attempts > 1 ? 'Attempt ' + unit.attempts : '');
166
+ if (more) item.appendChild(el('p', 'more', more));
167
+ if (unit.outcome) item.title = unit.outcome;
168
+ list.appendChild(item);
169
+ });
170
+ }
171
+ function footOf(m, node, waits) {
172
+ var foot = node.querySelector('.foot') || node.appendChild(el('div', 'foot'));
173
+ var long = node.querySelector('button'); foot.textContent = '';
174
+ if (m.open !== undefined) foot.appendChild(el('span', 'chip ' + (m.open ? 'open' : 'ok'), m.open ? (waits ? 'Open: waits on you' : 'Open') : (m.closed && how[m.closed.disposition]) || 'Answered'));
175
+ if (m.closed) foot.appendChild(el('span', 'closed', 'by ' + m.closed.by));
176
+ if (m.answeredLater) foot.appendChild(el('span', 'closed', 'Answered later by ' + m.answeredLater.by + ': ' + m.answeredLater.text));
177
+ if (long) foot.appendChild(long);
178
+ if (!foot.childNodes.length) foot.remove();
179
+ }
180
+ function messageOf(m, all) {
181
+ var node = el('article', 'msg ' + m.from.role); node.id = 'm' + m.id;
182
+ var who = el('p', 'who'); who.appendChild(el('strong', '', speaker(m.from) + (m.from.unit ? ' · ' + m.from.unit : '')));
183
+ who.appendChild(el('span', '', said(m) + (m.from.relayedBy ? ' (relayed by ' + m.from.relayedBy + ')' : '')));
184
+ var time = el('time', '', clock(m.at)); time.dateTime = m.at; who.appendChild(time); who.appendChild(el('span', 'num', '#' + m.id));
185
+ node.appendChild(who);
186
+ if (m.replyTo) { var about = all.filter(function (x) { return x.id === m.replyTo; })[0]; if (about) node.appendChild(el('p', 're', 'On #' + about.id + ': ' + about.text)); }
187
+ // Cut by whole characters, so a character stored as a pair is never split.
188
+ var limit = 420, chars = Array.from(m.text), long = chars.length > limit, open = false, text = el('p', 'text');
189
+ var draw = function () { text.textContent = ''; prose(text, long && !open ? chars.slice(0, limit).join('').replace(/\s+\S*$/, '') + ' …' : m.text); };
190
+ draw(); node.appendChild(text);
191
+ var foot = el('div', 'foot'); node.appendChild(foot);
192
+ if (long) { var more = el('button', '', 'Show all'); more.type = 'button'; more.setAttribute('aria-expanded', 'false'); more.addEventListener('click', function () { open = !open; draw(); more.textContent = open ? 'Show less' : 'Show all'; more.setAttribute('aria-expanded', String(open)); }); foot.appendChild(more); }
193
+ return node;
194
+ }
195
+ function talkOf(state) {
196
+ var box = byId('messages'), near = window.innerHeight + window.scrollY > document.body.scrollHeight - 240, added = 0;
197
+ if (!state.messages.length) { if (!box.querySelector('.empty')) { box.textContent = ''; drawn = {}; box.appendChild(el('p', 'empty', 'No messages yet. Agents post here when they ask something, find a problem or answer one.')); } return; }
198
+ var none = box.querySelector('.empty'); if (none) none.remove();
199
+ state.messages.forEach(function (m) {
200
+ var waits = state.waitingOnYou.indexOf(m.id) >= 0, key = JSON.stringify([m.open, m.closed, m.answeredLater, waits]);
201
+ if (!drawn[m.id]) { var node = messageOf(m, state.messages); box.appendChild(node); drawn[m.id] = node; added++; if (!first) { node.classList.add('fresh'); setTimeout(function () { node.classList.remove('fresh'); }, 2400); } }
202
+ if (shown[m.id] !== key) { footOf(m, drawn[m.id], waits); shown[m.id] = key; }
203
+ });
204
+ if (added && !first) { if (near) drawn[state.messages[state.messages.length - 1].id].scrollIntoView({ block: 'end', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); else byId('jump').classList.add('show'); }
205
+ }
206
+ function youOf(state) {
207
+ var waiting = state.messages.filter(function (m) { return state.waitingOnYou.indexOf(m.id) >= 0; });
208
+ if (!changed('you', waiting)) return;
209
+ var box = byId('you'); box.textContent = '';
210
+ if (!first && waiting.length > waited) byId('say').textContent = waiting.length === 1 ? 'One item now waits on you.' : waiting.length + ' items now wait on you.';
211
+ waited = waiting.length;
212
+ byId('you-box').classList.toggle('has', waiting.length > 0);
213
+ if (!waiting.length) { box.appendChild(el('p', 'empty', 'Nothing is waiting on you.')); return; }
214
+ waiting.forEach(function (m) {
215
+ var card = el('div', 'card'); prose(card.appendChild(el('p', 'ask')), m.text);
216
+ var by = el('p', 'by'); var link = el('a', '', '#' + m.id); link.href = '#m' + m.id; by.appendChild(document.createTextNode((m.kind === 'finding' ? 'A problem found by ' : 'Asked by ') + speaker(m.from).toLowerCase() + (m.from.unit ? ' of ' + m.from.unit : '') + ', ')); by.appendChild(link);
217
+ card.appendChild(by); box.appendChild(card);
218
+ });
219
+ box.appendChild(el('p', 'how', 'To answer, tell your agent what you decided. It posts your answer here.'));
220
+ }
221
+ function logOf(state) {
222
+ var recent = state.activity.slice(0, 14);
223
+ if (!changed('log', recent)) return;
224
+ var list = byId('activity'); list.textContent = '';
225
+ if (!recent.length) { list.appendChild(el('li', 'empty', 'No run has started yet.')); return; }
226
+ recent.forEach(function (a) { var item = el('li'); var time = el('time', '', clock(a.at)); time.dateTime = a.at; item.appendChild(time); var what = el('span'); what.appendChild(el('b', '', a.unit)); what.appendChild(document.createTextNode(' ' + a.text)); item.appendChild(what); list.appendChild(item); });
227
+ }
228
+ function pickerOf(state) {
229
+ var picker = byId('picker'), select = byId('queue');
230
+ picker.hidden = state.queues.length < 2;
231
+ if (changed('queues', state.queues)) { select.textContent = ''; state.queues.slice().reverse().forEach(function (q) { var option = el('option', '', q.goal + (q.cancelled ? ' (cancelled)' : '')); option.value = q.id; select.appendChild(option); }); }
232
+ if (state.queue) select.value = state.queue.id;
233
+ }
234
+ function show(state) {
235
+ byId('project').textContent = state.project;
236
+ pickerOf(state);
237
+ var problem = byId('problem'), queue = state.queue;
238
+ problem.hidden = true;
239
+ if ((queue ? queue.id : null) !== current) { current = queue ? queue.id : null; byId('messages').textContent = ''; drawn = {}; shown = {}; keys = {}; first = true; waited = 0; byId('jump').classList.remove('show'); }
240
+ if (!queue) { byId('goal').textContent = 'No work queue yet'; byId('line-state').textContent = 'When your agent plans work as a queue, each unit and everything the agents say to each other appears here.'; byId('units').textContent = ''; byId('floor').hidden = true; return; }
241
+ byId('goal').textContent = plain(queue.goal || 'Work queue');
242
+ if (queue.error) { byId('line-state').textContent = ''; problem.hidden = false; problem.textContent = 'This queue cannot be read: ' + queue.error; byId('units').textContent = ''; byId('floor').hidden = true; return; }
243
+ var status = byId('line-state'); status.textContent = ''; status.appendChild(el('b', '', lines[queue.line] || queue.line)); status.appendChild(document.createTextNode(' · ' + queue.done + ' of ' + queue.total + ' units done'));
244
+ if (queue.boardError) { problem.hidden = false; problem.textContent = 'The conversation cannot be read: ' + queue.boardError; }
245
+ byId('floor').hidden = false;
246
+ unitsOf(state); talkOf(state); youOf(state); logOf(state);
247
+ document.title = (state.waitingOnYou.length ? '(' + state.waitingOnYou.length + ') ' : '') + 'CYC hub · ' + state.project;
248
+ first = false;
249
+ }
250
+ function live(ok, text) { var box = byId('live'); box.classList.toggle('lost', !ok); if (byId('live-text').textContent !== text) byId('live-text').textContent = text; }
251
+ function tick() {
252
+ // The hub answers "unchanged" to the tag of what is already shown, so a quiet queue costs nothing to watch.
253
+ var options = { cache: 'no-store', headers: tag ? { 'If-None-Match': tag } : {} };
254
+ if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) options.signal = AbortSignal.timeout(8000);
255
+ fetch('/api/state' + location.search, options).then(function (reply) {
256
+ if (reply.status === 304) return null;
257
+ return reply.json().then(function (state) { if (!reply.ok) { var fault = new Error(state.error || 'The hub could not read the project.'); fault.served = true; throw fault; } tag = reply.headers.get('ETag') || ''; return state; });
258
+ }).then(function (state) { lastSeen = Date.now(); live(true, 'Live'); if (state) show(state); })
259
+ .catch(function (error) {
260
+ tag = '';
261
+ // The hub answered and named a fault: it is running, and the project is what it cannot read.
262
+ if (error && error.served) { live(false, 'The hub is running but cannot read this project'); byId('problem').hidden = false; byId('problem').textContent = plain(error.message); return; }
263
+ live(false, Date.now() - lastSeen > 4000 || !lastSeen ? 'Lost contact with the hub. Is cyc hub still running?' : 'Reconnecting');
264
+ })
265
+ .then(function () { setTimeout(tick, document.hidden ? 5000 : 1500); });
266
+ }
267
+ byId('queue').addEventListener('change', function () { location.search = '?queue=' + encodeURIComponent(byId('queue').value); });
268
+ byId('jump').addEventListener('click', function () { byId('jump').classList.remove('show'); var last = byId('messages').lastElementChild; if (last) last.scrollIntoView({ block: 'end' }); });
269
+ window.addEventListener('scroll', function () { if (window.innerHeight + window.scrollY > document.body.scrollHeight - 240) byId('jump').classList.remove('show'); }, { passive: true });
270
+ tick();
271
+ })();
272
+ </script>
273
+ </body>
274
+ </html>
275
+ `;
@@ -0,0 +1,139 @@
1
+ import { createServer } from 'node:http';
2
+ import { connect } from 'node:net';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { basename, resolve } from 'node:path';
6
+ import { queueCommand, readRun } from './runtime.mjs';
7
+ import { hubPage } from './hub-page.mjs';
8
+
9
+ // The hub: a page on this machine where a person watches a work queue being worked. It reads what
10
+ // the controller already records (queue status, the board, run histories) each time it is asked,
11
+ // through commands that take no lock, and writes nothing. Reasoning and limits:
12
+ // docs/context/work-queue.md.
13
+
14
+ // A run's history in words a person follows. Events with no entry here are bookkeeping.
15
+ const events = {
16
+ started: () => 'started work',
17
+ handoff: event => event.status === 'passed' ? `finished ${{ scout: 'planning', build: 'building', verify: 'checking', deliver: 'the handoff' }[event.stage] ?? event.stage}` : `stopped at ${event.stage}: ${event.status}`,
18
+ 'test-proof': event => event.passed ? 'proved its new tests fail on the old code' : 'could not prove its new tests',
19
+ verification: event => `ran the project's checks: ${event.passed ? 'passed' : 'failed'}`,
20
+ 'review-recorded': event => `recorded a ${event.reviewer === 'peer' ? 'review by another agent' : 'review'}`,
21
+ 'guard-halt': event => `halted: files outside its area changed${event.outOfScope?.length ? ` (${event.outOfScope.slice(0, 3).join(', ')})` : ''}`,
22
+ 'attempt-failed': event => `an attempt failed${event.stage ? ` at ${event.stage}` : ''}`,
23
+ exhausted: () => 'ran out of attempts',
24
+ blocked: () => 'is blocked and needs a person',
25
+ retry: event => `went back to ${event.stage}`,
26
+ pause: () => 'was paused', resume: () => 'was resumed', stop: () => 'was stopped',
27
+ complete: () => 'completed'
28
+ };
29
+ const stages = { scout: 'planning', build: 'building', verify: 'checking', deliver: 'handing off' };
30
+ const queueId = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/, runId = /\brun [a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}\b/g;
31
+
32
+ // The queues this project holds: a folder named by a queue ID whose record carries the same ID.
33
+ function queuesIn(root) {
34
+ const folder = resolve(root, '.cyc/queues');
35
+ if (!existsSync(folder)) return [];
36
+ return readdirSync(folder, { withFileTypes: true }).filter(entry => entry.isDirectory() && queueId.test(entry.name)).flatMap(entry => {
37
+ try {
38
+ const queue = JSON.parse(readFileSync(resolve(folder, entry.name, 'queue.json'), 'utf8'));
39
+ return queue.id === entry.name ? [{ id: queue.id, goal: String(queue.definition.goal), createdAt: String(queue.createdAt), cancelled: queue.status === 'cancelled' }] : [];
40
+ } catch { return []; }
41
+ }).sort((a, b) => a.createdAt < b.createdAt ? -1 : 1);
42
+ }
43
+ // With no queue named: the open one. When several are open or one cannot be read, the one being
44
+ // worked, then a halted one, then a ready one; otherwise the last one created.
45
+ function chosen(root, queues) {
46
+ try { return queueCommand(root, 'status', {}).queueId; } catch { /* none open, several open, or one unreadable */ }
47
+ const lines = queues.filter(queue => !queue.cancelled).map(queue => { try { return [queue.id, queueCommand(root, 'status', { queue: queue.id }).line]; } catch { return [queue.id, null]; } });
48
+ for (const line of ['in-progress', 'halted', 'ready']) { const hit = lines.findLast(item => item[1] === line); if (hit) return hit[0]; }
49
+ return (queues.findLast(queue => !queue.cancelled) ?? queues.at(-1)).id;
50
+ }
51
+ // Who a board label names. The board prints these labels; the hub turns them back into a speaker.
52
+ function speaker(label) {
53
+ const reviewer = /^reviewer of (\S+)/.exec(label), unit = /^unit (\S+)/.exec(label), relayed = /relayed by (.+)$/.exec(label);
54
+ return reviewer ? { role: 'reviewer', unit: reviewer[1] } : unit ? { role: 'builder', unit: unit[1] } : { role: 'person', ...(relayed ? { relayedBy: relayed[1] } : {}) };
55
+ }
56
+
57
+ // Everything the page shows, read fresh. `wanted` picks a queue.
58
+ export function hubState(root, wanted) {
59
+ root = realpathSync(root);
60
+ const queues = queuesIn(root), base = { project: basename(root), at: new Date().toISOString(), queues };
61
+ if (!queues.length) return { ...base, queue: null };
62
+ const id = wanted ?? chosen(root, queues), known = queues.find(queue => queue.id === id);
63
+ let status;
64
+ try { status = queueCommand(root, 'status', { queue: id }); } catch (error) { return { ...base, queue: { id, goal: known?.goal ?? null, error: error.message } }; }
65
+ let board = { messages: [], seats: [] }, boardError = status.board?.error ?? null;
66
+ if (!boardError) try { board = queueCommand(root, 'board', { queue: id }); } catch (error) { boardError = error.message; }
67
+ const seats = board.seats.filter(seat => ['active', 'done'].includes(seat.state));
68
+ const addressee = to => to === 'person' ? { role: 'person' } : to === 'all' ? { role: 'all' } : to.startsWith('seat:') ? { role: 'reviewer', unit: board.seats.find(seat => seat.seat === to.slice(5))?.unit ?? null } : { role: 'builder', unit: to };
69
+ const activity = [];
70
+ const units = status.units.map(unit => {
71
+ // The run that decides the unit: one that has not ended, whichever attempt it is.
72
+ const run = unit.runs.find(attempt => attempt.runId === unit.latest) ?? unit.runs.at(-1), seat = seats.find(entry => entry.unit === unit.id), working = unit.status === 'in-progress';
73
+ for (const attempt of unit.runs) {
74
+ try { for (const event of readRun(root, attempt.runId).history ?? []) if (events[event.type]) activity.push({ at: event.time, unit: unit.id, text: events[event.type](event) }); }
75
+ catch { /* a run whose record cannot be read shows as missing in its unit's status */ }
76
+ }
77
+ return { id: unit.id, outcome: unit.outcome, status: unit.status, ...(unit.reason ? { reason: unit.reason.replace(runId, 'its run') } : {}), ...(unit.waitsOn ? { waitsOn: unit.waitsOn } : {}),
78
+ ...(working && run?.stage ? { doing: stages[run.stage] ?? run.stage } : {}), ...(working && run?.status === 'paused' ? { paused: true } : {}), attempts: unit.runs.length, ...(seat ? { reviewer: seat.state === 'done' ? 'signed off' : 'reviewing' } : {}) };
79
+ });
80
+ const messages = board.messages.map(message => ({ id: message.id, at: message.at, from: speaker(message.from), to: addressee(message.to), kind: message.kind, text: message.text,
81
+ ...Object.fromEntries(['replyTo', 'disposition', 'topic', 'about', 'closed', 'answeredLater'].filter(key => message[key] !== undefined).map(key => [key, message[key]])),
82
+ ...(message.open !== undefined ? { open: message.open, ...(message.for ? { for: message.for } : {}) } : {}) }));
83
+ // What agents wait on the person for. The person's own question, left open because its unit is
84
+ // gone, is not theirs to answer; nothing waits in a cancelled queue.
85
+ const own = new Set(messages.filter(message => message.from.role === 'person').map(message => message.id));
86
+ return { ...base,
87
+ queue: { id, goal: status.goal, line: status.line, done: status.done, total: status.total, ...(boardError ? { boardError } : {}) },
88
+ units, messages,
89
+ waitingOnYou: status.line === 'cancelled' ? [] : (status.board?.forPerson ?? []).map(message => message.id).filter(item => !own.has(item)),
90
+ activity: activity.sort((a, b) => a.at < b.at ? 1 : -1).slice(0, 40) };
91
+ }
92
+
93
+ const headers = type => ({ 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
94
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" });
95
+ // Whether something on this machine already answers on the port under a local address. On Windows
96
+ // a listener on every address does not stop a second one on 127.0.0.1, which would then take the
97
+ // first one's local traffic. A closed port can take seconds to refuse there, so silence is free.
98
+ const answers = (port, host) => new Promise(done => {
99
+ const socket = connect({ port, host }), end = taken => { socket.destroy(); done(taken); };
100
+ socket.setTimeout(250, () => end(false)); socket.once('connect', () => end(true)); socket.once('error', () => end(false));
101
+ });
102
+
103
+ // Serves the page and its state on this machine only. Without a port it takes the first free one
104
+ // from 4780 to 4799; a port that was asked for and is taken is an error.
105
+ export function startHub(root, { port } = {}) {
106
+ root = realpathSync(root);
107
+ if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error('--port is a whole number from 0 to 65535.');
108
+ const text = 'text/plain; charset=utf-8', json = 'application/json; charset=utf-8';
109
+ const server = createServer((request, response) => {
110
+ const send = (code, type, body, more = {}) => { response.writeHead(code, { ...headers(type), ...more }); response.end(body); };
111
+ try {
112
+ // Only this machine's own address: a page elsewhere cannot point a browser's name lookup at the hub.
113
+ const local = [`127.0.0.1:${server.address().port}`, `localhost:${server.address().port}`];
114
+ if (!local.includes(request.headers.host ?? '')) return send(403, text, 'The hub answers only on this machine.');
115
+ if (request.method !== 'GET' && request.method !== 'HEAD') return send(405, text, 'The hub is read-only.', { Allow: 'GET, HEAD' });
116
+ // The address is compared as it was sent and never parsed as a URL: anything else is not found.
117
+ const mark = request.url.indexOf('?'), path = mark < 0 ? request.url : request.url.slice(0, mark);
118
+ if (path === '/') return send(200, 'text/html; charset=utf-8', hubPage);
119
+ if (path !== '/api/state') return send(404, text, 'Not found.');
120
+ const { at, ...state } = hubState(root, (mark < 0 ? null : new URLSearchParams(request.url.slice(mark + 1)).get('queue')) ?? undefined);
121
+ // The tag names what is shown, not when it was read, so a page that already has it is told so.
122
+ const body = JSON.stringify(state), tag = `"${createHash('sha256').update(body).digest('base64url').slice(0, 27)}"`;
123
+ if (request.headers['if-none-match'] === tag) return send(304, json, '', { ETag: tag });
124
+ return send(200, json, `{"at":${JSON.stringify(at)},${body.slice(1)}`, { ETag: tag });
125
+ } catch (error) {
126
+ if (response.headersSent) return response.destroy();
127
+ return send(500, json, JSON.stringify({ error: error.message }));
128
+ }
129
+ });
130
+ return new Promise((done, fail) => {
131
+ const listen = async (candidate, last) => {
132
+ const next = () => candidate < last ? listen(candidate + 1, last) : fail(new Error(port === undefined ? 'Ports 4780 to 4799 are all in use on this machine. Pass a free one with --port.' : `Port ${candidate} is in use. Pass another --port, or leave it out to take a free one.`));
133
+ if (candidate && (await Promise.all(['127.0.0.1', '::1'].map(host => answers(candidate, host)))).some(Boolean)) return next();
134
+ server.once('error', error => error.code === 'EADDRINUSE' ? next() : fail(error));
135
+ server.listen(candidate, '127.0.0.1', () => { server.removeAllListeners('error'); const { address, port: bound } = server.address(); done({ url: `http://127.0.0.1:${bound}/`, host: address, port: bound, project: root, close: () => new Promise(closed => server.close(closed)) }); });
136
+ };
137
+ port === undefined ? listen(4780, 4799) : listen(port, port);
138
+ });
139
+ }
@@ -5,7 +5,7 @@ import { createHash, randomUUID } from 'node:crypto';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { atomicJSON, configuration, readRun, runCommands, sourceSnapshot } from './runtime.mjs';
7
7
  import { runBrowserAudit, validateBrowserPlan } from './browser-audit.mjs';
8
- import { canonicalPattern, matches, contextLocation, parseDoc } from './context-review.mjs';
8
+ import { canonicalPattern, matches, contextLocation, parseDoc, readChanges } from './context-review.mjs';
9
9
 
10
10
  const registryName = 'docs/context/recipes.json';
11
11
  const indexName = 'docs/context/INDEX.md';
@@ -118,7 +118,9 @@ export function contextLinks(cell) {
118
118
  }).filter(Boolean);
119
119
  }
120
120
 
121
- function recordFreshness(root,record,limit) {
121
+ // The bytes a doc was last verified against: each covered file's hash from the newest change entry
122
+ // naming the doc, or the newest History entry of the earlier layout. Queried paths are checked first.
123
+ function recordFreshness(root,record,limit,queried,changes) {
122
124
  const base={coverage:'selected-files-only',gitFreshness:'not-inspected',semanticCorrectness:'unverified'};
123
125
  if(!record.exists)return {...base,status:'missing'};
124
126
  try {
@@ -126,11 +128,15 @@ function recordFreshness(root,record,limit) {
126
128
  if(!lstatSync(path).isFile())return {...base,status:'invalid',reason:'Context link is not a regular file.'};
127
129
  const parsed=parseDoc(readFileSync(path,'utf8'),path.split(/[\\/]/).at(-1));
128
130
  if(parsed.issues.length)return {...base,status:'unverified',reason:'No valid canonical source binding; inspect this reference against current code.'};
129
- const selected=parsed.history[0]?.files??[];
131
+ const named=changes().filter(entry=>entry.components.some(c=>c.doc===record.path)),bound=new Map();
132
+ for(const entry of named)for(const file of entry.files)if(!bound.has(file.path)&&parsed.covers.some(pattern=>matches(pattern,file.path)))bound.set(file.path,file.hash);
133
+ const asked=item=>queried.includes(item.path)?0:1,legacy=parsed.history[0];
134
+ // An earlier-layout doc is read from its History unless a change record is newer.
135
+ const selected=(legacy&&!(named[0]?.date>=legacy.date)?legacy.files:[...bound].map(([path,hash])=>({path,hash}))).sort((a,b)=>asked(a)-asked(b));
130
136
  if(!selected.length)return {...base,status:'unverified',checkedFiles:0};
131
137
  const files=selected.slice(0,limit).map(item=>{
132
- if(!/^sha256:[a-f0-9]{64}$/i.test(item.hash)||item.path.startsWith('.cyc/')||item.path===record.path||!parsed.covers.some(pattern=>matches(pattern,item.path)))return {path:item.path,status:'unverified'};
133
- try { const source=local(root,item.path);return {path:item.path,status:!existsSync(source)?'missing':lstatSync(source).isFile()&&hash(readFileSync(source))===item.hash.slice(7)?'matches':'changed'}; }
138
+ if(!/^(?:sha256:[a-f0-9]{64}|deleted)$/i.test(item.hash)||item.path.startsWith('.cyc/')||item.path===record.path||!parsed.covers.some(pattern=>matches(pattern,item.path)))return {path:item.path,status:'unverified'};
139
+ try { const source=local(root,item.path);const gone=!existsSync(source);return {path:item.path,status:item.hash==='deleted'?gone?'matches':'changed':gone?'missing':lstatSync(source).isFile()&&hash(readFileSync(source))===item.hash.slice(7)?'matches':'changed'}; }
134
140
  catch {return {path:item.path,status:'unverified'};}
135
141
  });
136
142
  return {...base,status:files.some(f=>['changed','missing'].includes(f.status))?'drifted':selected.length>limit||files.some(f=>f.status==='unverified')?'unverified':'matches',checkedFiles:files.length,totalBindings:selected.length,truncated:selected.length>limit,files};
@@ -167,7 +173,9 @@ export function investigateProject(target, options = {}) {
167
173
  }
168
174
  }
169
175
  const evidenceChecks = new Map(), recordChecks=new Map();
170
- const contexts = found.slice(0, limit).map(entry => ({ ...entry, recordEvidence:entry.records.map(record=>{if(!recordChecks.has(record.path))recordChecks.set(record.path,recordFreshness(root,record,limit));return {path:record.path,...recordChecks.get(record.path)};}), evidence: entry.evidence.map(e => {
176
+ let entries;
177
+ const changes=()=>entries??=readChanges(root).entries;
178
+ const contexts = found.slice(0, limit).map(entry => ({ ...entry, recordEvidence:entry.records.map(record=>{if(!recordChecks.has(record.path))recordChecks.set(record.path,recordFreshness(root,record,limit,selected.paths,changes));return {path:record.path,...recordChecks.get(record.path)};}), evidence: entry.evidence.map(e => {
171
179
  if (!e.exists || !e.path.endsWith('.json')) return e;
172
180
  if (!evidenceChecks.has(e.path)) {
173
181
  const checked = spawnSync(process.execPath, [helper, 'check', '--project', root, '--manifest', e.path], { encoding: 'utf8', windowsHide: true, timeout: 10000, maxBuffer: 1024 * 1024 });