SLOPSHOPPER

agentic-session

Agentic Development companion for Claude Code: a context band above the prompt, shown only past your threshold, with a one-press /ad-handoff and an opt-in…

panebandcommandtoastprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agentic-session
│ ┃ Briefing ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ No briefing: the kit script is not ⏺ Read(src/auth.ts) │ ┃ installed or did not run. ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /agentic-briefing │ ⎿ agentic-session: Briefing pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Briefing
No briefing: the kit script is not installed or did not run.
README

Agentic Development

@alexandrealvaro/agentic installs a disciplined engineering skill kit for Claude Code and Codex. It helps an agent research, plan, build, review, ship, and hand work off without losing the project context between sessions.

It is not an agent runtime, a framework, or a product-management tool. It installs local skills and documentation; the host agent still does the work, and you retain every consequential decision.

Start here

From a project root, install the complete skill set for both hosts:

npx --yes @alexandrealvaro/agentic@latest init --yes

Then open the project in Claude Code or Codex and invoke:

/ad-next

/ad-next reads the repository and recommends the next useful action. When a project keeps active work in GitHub instead of local planning files, an optional machine or project configuration lets it include bounded issue and pull-request metadata through /ad-project-state. With no configuration, behavior stays repository-only. See the project-source contract. All skills are installed; you do not need to choose a maturity level or remember a catalog before starting.

Requires Node.js 22.13 or newer. Claude Code skills install under .claude/skills/; Codex skills install under .agents/skills/.

Essential commands

NeedCommand
Install the personal defaultnpx --yes @alexandrealvaro/agentic@latest init --yes
Install personal Claude Code skills onlynpx --yes @alexandrealvaro/agentic@latest init --agent claude-code --yes
Install personal Codex skills onlynpx --yes @alexandrealvaro/agentic@latest init --agent codex --yes
Update the personal kitnpx --yes @alexandrealvaro/agentic@latest update --yes
Preview an updatenpx --yes @alexandrealvaro/agentic@latest update --dry-run --yes
Install into a project deliberatelynpx --yes @alexandrealvaro/agentic@latest init --scope project --yes
Remove a project installationnpx --yes @alexandrealvaro/agentic@latest uninstall --scope project --yes
Install the agentic command globallynpm install --global @alexandrealvaro/agentic
Remove the global commandnpm uninstall --global @alexandrealvaro/agentic

After a global CLI install, agentic init --yes and agentic update --yes maintain the personal, machine-global kit from any directory. Add --scope project only for a deliberate shared project install. A global CLI install and a user-level skill install are different things; the installation guide explains both, including safe project removal.

Everyday workflow

Start every unfamiliar repository or fuzzy request with /ad-next.

SituationUseful path
New product/ad-grill-me → /ad-prd → /ad-bootstrap → /ad-spec → /ad-task
Existing feature/ad-ground → /ad-spec when scope needs a contract → /ad-tdd → /ad-review
Bug or regression/ad-diagnose → regression test → /ad-review
Finish and ship/ad-commit → /ad-pr → /ad-merge; package maintainers use /ad-release

These are routes, not gates. A one-off change should not produce artifacts that do not change the work; a durable or high-risk change should use the documentation and quality checks it needs.

Optional: Claude Code companion plugin

On Claude Code (2.1.287+ in the terminal, 2.1.286+ in the desktop app) you can add agentic-session, an opt-in plugin that draws a context band above the prompt once the session reaches your threshold of the auto-compact point (80% by default, set in /config), with an AD handoff button that runs /ad-handoff and an opt-in clear and continue box that then clears the session and resumes from the handoff in the same window:

claude plugin marketplace add alexandremendoncaalvaro/agentic-development
claude plugin install agentic-session@agentic-development

It is separate from the installer above and carries no skills; skills always come from agentic init. Codex has no equivalent surface.

Find the right detail

The installer keeps project files in sync with a state-aware three-way diff: it updates kit changes, preserves user-edited skills by default, and never silently overwrites a conflict. Report issues on GitHub; releases are listed on GitHub Releases.

Source 3 files
hooks/register.mjs 401 lines
1// agentic-session: a context band above the prompt with a one-press
2// /ad-handoff, drawn only at or above the user's threshold (ADR-0088,
3// task-0104), and /agentic-briefing, which opens the work-in-progress briefing
4// in a pane (ADR-0090, task-0111). Shaped on Anthropic's token-weather sample:
5// read on session start, after each main-loop turn and after a compaction,
6// never on every draw. The briefing is the kit script's output, drawn as
7// printed; the plugin establishes no fact. The engine reads on(...) and
8// $.noun.method(...) from source, so they are spelled literally, and helpers
9// that take $ are top-level functions. A threshold changed in /config reloads
10// the module with the new options.
11
12import {
13  CLEAR_KEY,
14  HANDOFF_LABEL,
15  bandLabel,
16  clearLabel,
17  fillReading,
18  handoffDirs,
19  handoffsSince,
20  normalizeThreshold,
21  resumePrompt,
22  shouldShow,
23} from './band.mjs';
24import {
25  detailsMarkdown,
26  paneModel,
27  progressSvg,
28  progressText,
29  readBriefing,
30  scriptCandidates,
31} from './briefing-view.mjs';
32
33const PANE = 'agentic-briefing';
34const PANE_TITLE = 'Briefing';
35// A run that outlives this is dropped: the band shows nothing rather than wait.
36const SCRIPT_TIMEOUT_MS = 10_000;
37
38export function register(on, options) {
39  const threshold = normalizeThreshold(options?.threshold);
40  const state = { fill: null, briefing: null, briefingRun: 0, clearAfter: false, pending: null };
41
42  on('session.start', async ($, e, next) => {
43    const result = await next(e);
44    await registerCommand($);
45    state.clearAfter = (await $.store.get(CLEAR_KEY).catch(() => false)) === true;
46    await refresh($, state);
47    return result;
48  });
49
50  // The first main-loop turn to start after the press is the handoff's own:
51  // the command queues until the session is idle (task-0115). Its start time
52  // tells the handoff's file from older ones.
53  on('turn.start', async ($, e, next) => {
54    const result = await next(e);
55    if (state.pending && !state.pending.turnId) {
56      state.pending = { turnId: e.turnId, since: Date.now() };
57    }
58    return result;
59  });
60
61  on('turn.complete', async ($, e, next) => {
62    const result = await next(e);
63    if (e.agentId) return result;
64    await refresh($, state);
65    const pending = state.pending;
66    if (pending?.turnId && pending.turnId === e.turnId) {
67      state.pending = null;
68      // Run after this hook returns: the clear ends the session.
69      void clearAndResume($, pending, e.reason).catch((error) =>
70        logFailure($, 'clear and resume failed', error)
71      );
72    }
73    return result;
74  });
75
76  on('session.compact', async ($, e, next) => {
77    const result = await next(e);
78    await refresh($, state);
79    return result;
80  });
81
82  // /clear ends the session with no session.start after it: drop the readings.
83  on('session.end', async ($, e, next) => {
84    const result = await next(e);
85    state.pending = null;
86    clearReadings($, state);
87    return result;
88  });
89
90  on('command.run', { command: PANE }, async ($) => {
91    await $.ui.open({ id: PANE, title: PANE_TITLE });
92    return { text: 'Briefing pane opened.' };
93  });
94
95  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
96    if (e.hasSurvey || !shouldShow(state.fill, threshold)) return next(e);
97    const { Box, Text, Button } = $.ui.resolve(e);
98    return Box({
99      flexDirection: 'row',
100      justifyContent: 'space-between',
101      paddingX: 1,
102      children: [
103        Text({ dimColor: true, children: bandLabel(state.fill) }),
104        Box({
105          flexDirection: 'row',
106          gap: 1,
107          children: [
108            Button({
109              key: 'handoff',
110              label: HANDOFF_LABEL,
111              onPress: () => submitHandoff($, state),
112            }),
113            Button({
114              key: 'clear-after',
115              label: clearLabel(state.clearAfter),
116              plain: true,
117              dimColor: !state.clearAfter,
118              onPress: () => toggleClearAfter($, state),
119            }),
120          ],
121        }),
122      ],
123    });
124  });
125
126  on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => drawPane($, e, state.briefing));
127}
128
129const LEVEL_COLOR = { ok: 'green', warn: 'yellow', unknown: 'gray', active: '#d97757' };
130const ACCENT = '#d97757';
131const BAR_PX = 160;
132const BAR_CELLS = 16;
133
134function drawPane($, e, briefing) {
135  const el = $.ui.resolve(e);
136  const { Box, Text } = el;
137  if (!briefing) {
138    return Box({
139      padding: 1,
140      children: [
141        Text({
142          dimColor: true,
143          children: 'No briefing: the kit script is not installed or did not run.',
144        }),
145      ],
146    });
147  }
148  const model = paneModel(briefing);
149  const details = detailsMarkdown(briefing);
150  return Box({
151    flexDirection: 'column',
152    gap: 1,
153    paddingX: 1,
154    children: [
155      headerCard(el, model),
156      ...(model.next ? [nextCard(el, model.next)] : []),
157      ...(model.progress.length
158        ? [
159            section(
160              el,
161              'Progress',
162              model.progress.map((p) => progressRow(el, e, p))
163            ),
164          ]
165        : []),
166      section(
167        el,
168        'Health',
169        model.health.map((h) => healthRow(el, h))
170      ),
171      ...(details && el.Markdown ? [el.Markdown({ text: details })] : []),
172    ],
173  });
174}
175
176function headerCard({ Box, Text }, model) {
177  if (!model.header) {
178    return Box({
179      borderStyle: 'round',
180      paddingX: 1,
181      children: [Text({ bold: true, children: 'No single active task' })],
182    });
183  }
184  const { number, title, status, statusLevel, chosenBy } = model.header;
185  return Box({
186    flexDirection: 'column',
187    borderStyle: 'round',
188    paddingX: 1,
189    children: [
190      Box({
191        flexDirection: 'row',
192        gap: 1,
193        children: [
194          Text({ bold: true, color: ACCENT, children: `Task ${number}` }),
195          Text({
196            backgroundColor: LEVEL_COLOR[statusLevel],
197            color: 'black',
198            children: ` ${status} `,
199          }),
200        ],
201      }),
202      Text({ bold: true, children: title }),
203      Text({ dimColor: true, children: `Active because: ${chosenBy}` }),
204    ],
205  });
206}
207
208function nextCard({ Box, Text }, next) {
209  return Box({
210    flexDirection: 'column',
211    borderStyle: 'round',
212    borderColor: ACCENT,
213    paddingX: 1,
214    children: [
215      Text({ dimColor: true, bold: true, children: 'NEXT STEP' }),
216      Text({ bold: true, children: next.step }),
217      ...(next.detail ? [Text({ dimColor: true, children: next.detail })] : []),
218    ],
219  });
220}
221
222function section({ Box, Text }, title, rows) {
223  return Box({
224    flexDirection: 'column',
225    children: [Text({ dimColor: true, bold: true, children: title.toUpperCase() }), ...rows],
226  });
227}
228
229function progressRow({ Box, Text, Svg }, e, item) {
230  const bar =
231    e.surface === 'desktop' && Svg
232      ? [
233          Svg({
234            source: progressSvg(item, BAR_PX),
235            alt: `${item.done} of ${item.total}`,
236            width: BAR_PX,
237            height: 8,
238          }),
239          Text({ children: `${item.done}/${item.total}` }),
240        ]
241      : [Text({ children: progressText(item, BAR_CELLS) })];
242  return Box({
243    flexDirection: 'row',
244    gap: 1,
245    alignItems: 'center',
246    children: [Box({ width: 20, children: [Text({ children: item.label })] }), ...bar],
247  });
248}
249
250function healthRow({ Box, Text }, item) {
251  return Box({
252    flexDirection: 'row',
253    gap: 1,
254    children: [
255      Text({ color: LEVEL_COLOR[item.level], children: '●' }),
256      Box({ width: 18, children: [Text({ bold: true, children: item.label })] }),
257      Text({ children: item.value }),
258    ],
259  });
260}
261
262async function registerCommand($) {
263  try {
264    await $.command.register({
265      name: PANE,
266      description: 'Show the work-in-progress briefing in a pane',
267    });
268  } catch (error) {
269    logFailure($, 'briefing command not registered', error);
270  }
271}
272
273async function refresh($, state) {
274  await takeReading($, state);
275  await takeBriefing($, state);
276  $.ui.invalidate('ui.render');
277}
278
279async function takeReading($, state) {
280  try {
281    const { context } = await $.session.usage({ breakdown: 'summary' });
282    state.fill = fillReading(context);
283  } catch (error) {
284    // Fail closed (ADR-0088): with no fresh reading the context part is not
285    // drawn; the reason goes to the debug log, never on screen.
286    state.fill = null;
287    logFailure($, 'no context reading', error);
288  }
289}
290
291// Fail closed (ADR-0090): no installed script, a failed run or output that is
292// not a briefing leaves the pane without a briefing.
293async function takeBriefing($, state) {
294  // A run that finishes after a newer one started is dropped, never drawn.
295  const run = ++state.briefingRun;
296  const settle = (briefing) => {
297    if (run === state.briefingRun) state.briefing = briefing;
298  };
299  try {
300    const root = await $.session.root();
301    const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'));
302    const script = await firstInstalled($, scriptCandidates(root, home));
303    if (!script) {
304      settle(null);
305      return;
306    }
307    const sessionId = await $.session.id();
308    const result = await $.process.run(['node', script, '--session', sessionId], {
309      cwd: root,
310      timeoutMs: SCRIPT_TIMEOUT_MS,
311    });
312    const briefing = readBriefing(result);
313    settle(briefing);
314    if (!briefing) logFailure($, 'briefing unreadable', `exit ${result.exitCode}`);
315  } catch (error) {
316    settle(null);
317    logFailure($, 'no briefing', error);
318  }
319}
320
321async function firstInstalled($, paths) {
322  for (const path of paths) {
323    const found = await $.fs.stat(path).catch(() => undefined);
324    if (found) return path;
325  }
326  return null;
327}
328
329function clearReadings($, state) {
330  state.fill = null;
331  state.briefing = null;
332  state.briefingRun += 1;
333  $.ui.invalidate('ui.render');
334}
335
336// Runs /ad-handoff as if typed: a plugin's prompt.submit of the same text did
337// nothing in the desktop app (task-0116). With the box on, the handoff's own
338// turn is followed by a clear and a resume (task-0115).
339function submitHandoff($, state) {
340  state.pending = state.clearAfter ? { turnId: null } : null;
341  $.command.run({ command: 'ad-handoff' }).catch((error) => {
342    state.pending = null;
343    $.ui.toast('AD handoff could not start: run /ad-handoff yourself.');
344    logFailure($, 'handoff not run', error);
345  });
346}
347
348function toggleClearAfter($, state) {
349  state.clearAfter = !state.clearAfter;
350  // The latest choice wins, even over a handoff already running.
351  if (!state.clearAfter) state.pending = null;
352  $.store
353    .set(CLEAR_KEY, state.clearAfter)
354    .catch((error) => logFailure($, 'clear-and-continue not saved', error));
355  $.ui.invalidate('ui.render');
356}
357
358// Runs once, after the handoff's own turn: clears only when that turn ended
359// normally and wrote exactly one handoff file, so a session is never cleared
360// with nothing, or someone else's work, to resume from.
361async function clearAndResume($, pending, reason) {
362  if (reason !== 'answer') {
363    $.ui.toast('AD handoff: the handoff did not finish, so the session was not cleared.');
364    return;
365  }
366  const tmpdir = await $.env.get('TMPDIR').catch(() => undefined);
367  const found = [];
368  for (const dir of handoffDirs(tmpdir)) {
369    const entries = await $.fs.list(dir).catch(() => []);
370    for (const name of handoffsSince(entries, pending.since)) found.push(`${dir}/${name}`);
371  }
372  if (found.length === 0) {
373    $.ui.toast('AD handoff: no handoff file was written, so the session was not cleared.');
374    return;
375  }
376  if (found.length > 1) {
377    $.ui.toast('AD handoff: more than one new handoff file, so the session was not cleared.');
378    return;
379  }
380  const [path] = found;
381  try {
382    await $.command.run({ command: 'clear' });
383  } catch (error) {
384    $.ui.toast(`AD handoff: the session was not cleared; the handoff is at ${path}.`);
385    logFailure($, 'clear failed', error);
386    return;
387  }
388  try {
389    await $.prompt.submit({ text: resumePrompt(path), asUser: true });
390  } catch (error) {
391    $.ui.toast(
392      `AD handoff: the session was cleared, but the resume prompt was not sent; resume from ${path}.`
393    );
394    logFailure($, 'resume prompt not submitted', error);
395  }
396}
397
398function logFailure($, what, error) {
399  $.ui.log(`agentic-session: ${what} (${error?.message ?? error})`, { to: 'debug' });
400}
401
hooks/band.mjs 75 lines
1// The band's rule, kept free of the engine interface so node:test covers it
2// (ADR-0088, task-0104). register.mjs feeds it what $.session.usage() returns.
3
4export const DEFAULT_THRESHOLD = 80;
5
6// Names the kit's skill, so the press is recognisably Agentic Development's handoff.
7export const HANDOFF_LABEL = 'AD handoff';
8
9// A reading as { percent, basis }, measured toward the auto-compact point when
10// auto-compaction is on (GROUND-0035 E3, RESEARCH-0036 E3), else toward the
11// model's window; null before the first response of the live window.
12export function fillReading(context) {
13  if (!context || typeof context.tokens !== 'number') return null;
14  const breakdown = context.breakdown;
15  if (breakdown?.isAutoCompactEnabled && breakdown.autoCompactThreshold > 0) {
16    return reading(context.tokens, breakdown.autoCompactThreshold, 'auto-compact');
17  }
18  if (context.window > 0) return reading(context.tokens, context.window, 'window');
19  return null;
20}
21
22function reading(tokens, limit, basis) {
23  return { percent: Math.min(100, Math.round((tokens / limit) * 100)), basis };
24}
25
26export function normalizeThreshold(value) {
27  const number = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
28  return Number.isInteger(number) && number >= 1 && number <= 99 ? number : DEFAULT_THRESHOLD;
29}
30
31export function shouldShow(fill, threshold) {
32  return fill !== null && fill.percent >= threshold;
33}
34
35export function bandLabel(fill) {
36  const against = fill.basis === 'auto-compact' ? 'the auto-compact point' : 'the window';
37  return `Context ${fill.percent}% of ${against}`;
38}
39
40// The opt-in box that clears the session after a handoff (task-0115).
41export const CLEAR_KEY = 'clearAfterHandoff';
42
43export function clearLabel(on) {
44  return `${on ? '[x]' : '[ ]'} clear and continue`;
45}
46
47// Where ad-handoff writes: ${TMPDIR:-/tmp}/agentic-handoffs.
48export function handoffDirs(tmpdir) {
49  const base = (tmpdir || '/tmp').replace(/\/+$/, '');
50  return [...new Set([`${base}/agentic-handoffs`, '/tmp/agentic-handoffs'])];
51}
52
53// ad-handoff names its file <UTC stamp>-<slug>.md, the slug free text. The
54// directory may be the shared /tmp and the name reaches the model as the
55// person's own words in the resume prompt, so a name off that shape, or with
56// a double quote, a control or invisible format character or a line break,
57// is not taken.
58const HANDOFF_NAME = /^\d{8}T\d{6}Z-[^/"\p{Cc}\p{Cf}\u2028\u2029]+\.md$/u;
59
60// The handoff files written at or after `sinceMs`, newest first, by name. The
61// caller clears only when exactly one is found: none means the handoff wrote
62// nothing, several mean another session wrote one in the same window.
63export function handoffsSince(entries, sinceMs) {
64  return entries
65    .filter((e) => e.kind === 'file' && HANDOFF_NAME.test(e.name) && e.mtimeMs >= sinceMs)
66    .sort((a, b) => b.mtimeMs - a.mtimeMs)
67    .map((e) => e.name);
68}
69
70// The prompt that resumes the cleared session, as ad-handoff's own resume
71// chip words it.
72export function resumePrompt(path) {
73  return `Read "${path}" first and follow its Resume protocol before any work, then continue with its recommended first action.`;
74}
75
hooks/briefing-view.mjs 194 lines
1// The briefing pane's model, kept free of the engine interface so node:test
2// covers it (ADR-0090, task-0111). register.mjs feeds it the JSON that the
3// kit's ad-next/scripts/briefing.mjs prints and draws what it returns; nothing
4// here establishes a fact the script did not report.
5
6// The task's number from its slug, `0111-show-...` -> `0111`.
7function taskNumber(slug) {
8  return slug.split('-')[0];
9}
10
11// The script's briefing from a $.process.run result, or null when the run
12// failed, was cut, or printed anything but a JSON object: the pane then shows
13// no briefing rather than a guess.
14export function readBriefing(result) {
15  if (!result || result.exitCode !== 0 || result.isStdoutTruncated) return null;
16  try {
17    const value = JSON.parse(result.stdout);
18    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
19  } catch {
20    return null;
21  }
22}
23
24const SCRIPT = '.claude/skills/ad-next/scripts/briefing.mjs';
25
26// Where the kit installs the script: a project install pins the repository's
27// own kit version, so it wins over the user install.
28export function scriptCandidates(root, home) {
29  return [`${root}/${SCRIPT}`, ...(home ? [`${home}/${SCRIPT}`] : [])];
30}
31
32const RULES = {
33  'single-in-progress': 'the only in-progress task',
34  'newest-commit-ahead': 'newest commit ahead of the base branch',
35};
36
37const STATUS_LEVEL = { 'in-progress': 'active', done: 'ok', blocked: 'warn' };
38
39// A task title from its slug: `0111-show-the-work-in-progress-...` ->
40// `Show the work in progress ...`.
41function taskTitle(slug) {
42  const words = slug.split('-').slice(1).join(' ');
43  return words.charAt(0).toUpperCase() + words.slice(1);
44}
45
46function nextStep(plan) {
47  if (!plan.open.length) return null;
48  const item = plan.open[0];
49  const cut = item.indexOf(':');
50  return cut === -1
51    ? { step: item.trim(), detail: '' }
52    : { step: item.slice(0, cut).trim(), detail: item.slice(cut + 1).trim() };
53}
54
55function approvalHealth(approval, cannotTell = []) {
56  if (cannotTell.includes('approval')) {
57    const value = cannotTell.includes('git')
58      ? 'cannot tell: commits ahead of the base branch not listed'
59      : 'cannot tell: approval not committed yet';
60    return { value, level: 'unknown' };
61  }
62  const order = approval.precedesFirstImplementingCommit;
63  if (order === true) return { value: 'before the first code', level: 'ok' };
64  if (order === false) {
65    const value = approval.entry ? 'after code was committed' : 'missing, and code is committed';
66    return { value, level: 'warn' };
67  }
68  return approval.entry
69    ? { value: 'order unknown', level: 'unknown' }
70    : { value: 'not approved yet', level: 'ok' };
71}
72
73function gateHealth(gate) {
74  if (!gate) return { value: 'no evidence for this session', level: 'unknown' };
75  if (!gate.wouldBlock) return { value: `none of ${gate.lines} checks would block`, level: 'ok' };
76  const latest = gate.lastWouldBlock
77    ? `; latest: ${gate.lastWouldBlock.check} before ${gate.lastWouldBlock.action}`
78    : '';
79  return {
80    value: `${gate.wouldBlock} of ${gate.lines} checks would block${latest}`,
81    level: 'warn',
82  };
83}
84
85// The pane's model: what the pane draws, derived only from the briefing.
86export function paneModel(b) {
87  const progress = [];
88  if (b.task) {
89    progress.push(
90      { label: 'Plan', done: b.plan.done.length, total: b.plan.done.length + b.plan.open.length },
91      {
92        label: 'Criteria',
93        done: b.acceptance.done,
94        total: b.acceptance.done + b.acceptance.open.length,
95      },
96      {
97        label: 'Definition of Done',
98        done: b.definitionOfDone.done,
99        total: b.definitionOfDone.done + b.definitionOfDone.open.length,
100      }
101    );
102  }
103  if (b.roadmap) {
104    progress.push({
105      label: 'Roadmap tasks',
106      done: b.roadmap.tasksDone,
107      total: b.roadmap.tasksTotal,
108    });
109  }
110  const health = [];
111  if (b.task) {
112    health.push({ label: 'Plan approval', ...approvalHealth(b.approval, b.cannotTell) });
113    health.push(
114      b.deviations.length
115        ? { label: 'Deviations', value: `${b.deviations.length} recorded`, level: 'warn' }
116        : { label: 'Deviations', value: 'none recorded', level: 'ok' }
117    );
118  }
119  if (!b.roadmap) {
120    health.push({
121      label: 'Roadmap',
122      value: 'cannot tell: no doc/product/PRD.md',
123      level: 'unknown',
124    });
125  }
126  health.push({ label: 'Gate (shadow)', ...gateHealth(b.gate) });
127  return {
128    header: b.task
129      ? {
130          number: taskNumber(b.task.slug),
131          title: taskTitle(b.task.slug),
132          status: b.task.status,
133          statusLevel: STATUS_LEVEL[b.task.status] ?? 'unknown',
134          chosenBy: RULES[b.task.rule] ?? b.task.rule,
135        }
136      : null,
137    next: b.task ? nextStep(b.plan) : null,
138    progress,
139    health,
140  };
141}
142
143const checklist = (items, done) => items.map((item) => `- [${done ? 'x' : ' '}] ${item}`);
144
145// The pane's detail block, as Markdown: checklists the surface draws as such.
146const CUT_NOTE = '\n\n_Cut to fit the pane; the task file has the rest._';
147
148// The Markdown element takes at most 10000 characters.
149export function detailsMarkdown(b, limit = 10_000) {
150  const full = fullDetails(b);
151  if (full.length <= limit) return full;
152  const room = full.slice(0, Math.max(0, limit - CUT_NOTE.length));
153  const lineEnd = room.lastIndexOf('\n');
154  return `${lineEnd === -1 ? room : room.slice(0, lineEnd)}${CUT_NOTE}`;
155}
156
157function fullDetails(b) {
158  const blocks = [];
159  if (b.task) {
160    blocks.push(['#### Plan', ...checklist(b.plan.done, true), ...checklist(b.plan.open, false)]);
161    if (b.acceptance.open.length) {
162      blocks.push(['#### Open criteria', ...checklist(b.acceptance.open, false)]);
163    }
164    if (b.definitionOfDone.open.length) {
165      blocks.push(['#### Definition of Done', ...checklist(b.definitionOfDone.open, false)]);
166    }
167    if (b.deviations.length) {
168      blocks.push(['#### Deviations', ...b.deviations.map((d) => `- **${d.heading}**: ${d.text}`)]);
169    }
170  }
171  if (b.unreadable.length) {
172    blocks.push(['#### Unreadable', ...b.unreadable.map((u) => `- \`${u.path}\` (${u.code})`)]);
173  }
174  return blocks.map((lines) => `${lines.join('\n')}\n`).join('\n');
175}
176
177const share = ({ done, total }) => (total > 0 ? Math.min(1, done / total) : 0);
178
179export function progressText(item, cells) {
180  const filled = Math.round(share(item) * cells);
181  return `${'█'.repeat(filled)}${'░'.repeat(cells - filled)} ${item.done}/${item.total}`;
182}
183
184// A rounded bar: the track in a muted tone, the fill in the accent.
185export function progressSvg(item, width) {
186  const filled = Math.round(share(item) * width);
187  return (
188    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="8" viewBox="0 0 ${width} 8">` +
189    `<rect class="track" x="0" y="0" width="${width}" height="8" rx="4" fill="#8884"/>` +
190    `<rect class="fill" x="0" y="0" width="${filled}" height="8" rx="4" fill="#d97757"/>` +
191    '</svg>'
192  );
193}
194