SLOPSHOPPER

ase

Agentic Software Engineering (ASE)

bandrowspromptmodeltimer
★ 60v2.0.5Apache-2.0updated 2026-10-25rse/ase/plugin
A shopper browsing a rack in a slop shop
README

ASE

ASE

github (author stars) github (author followers) github (project license) github (project release) github (project stars)

About


Agentic Software Engineering (ASE) is the opinionated Open Source companion toolkit of *Dr. Ralf S. Engelschall* for fusing the concept of Agentic AI Coding and traditional Software Engineering in the software development tool Anthropic Claude Code — and with reduced support also in the alternative tool GitHub Copilot CLI or OpenAI Codex CLI.

ASE ships with 57 agent skills, agent hooks, agent sub-agents, an underlying Model-Context-Protocol (MCP) service and a Command-Line Interface (CLI) with a task store, task boards, and autonomous agents, incorporating reasonable methodology and automation aspects, to support the recurring tasks of a Software Developer and Software Architect.

ASE is primarily motivated by the following statement of its primary author, *Dr. Ralf S. Engelschall*:

"Software developers in the industrial Software Engineering context, in their recurring tasks, should leverage pre-manufactured agentic AI skills to boost their daily productivity. Those skills incorporate reasonable methodology and automation aspects while keeping the developers in the driver's seat to ensure stable result quality."

Notices


[!NOTE] TERMINOLOGY: The discipline of *Agentic Software Engineering* in general is Software Engineering, supported by autonomous AI Agents to perform tasks across the software development lifecycle. This ASE product in particular is also agentic, but not strictly based on autonomous agents. Instead, ASE focuses on supporting the role of a Software Engineer with Agentic AI Coding Tools towards multi-step operations and a plan/task-driven approach, but still strongly focuses on Human-in-the-Loop. Its autonomous agents, which drive tasks headless, are an optional addition only.

[!NOTE] TOOL SUPPORT FOCUS: The primary focus of ASE is on the Agentic AI Coding tool *Claude Code*. The secondary focus is on the support for *GitHub Copilot CLI* (just set environment variable ASE_TOOL=copilot) and *OpenAI Codex CLI* (just set environment variable ASE_TOOL=codex). In the future, additional support could be provided also for alternative tools — if their agent harness features (especially hooks, interactive user dialog tool, etc.) realistically allow it.

Highlights


Check out the following scenarios and corresponding ASE examples to see whether ASE is right for you:

<table> <tr> <td width="50%" valign="top">

  • Boosted Sessions: You want to speed up your interactive sessions and at the same time reduce costs by reducing the number of produced LLM output tokens? &rarr; /ase-meta-config set agent.persona engineer or even /ase-meta-config set agent.persona caveman
  • Alternative Approach Funnel: You prefer a plan-driven approach, but the agent harness's Plan Mode is too unstructured and too direct because you want to leverage a funnel of alternative approaches first? &rarr; /ase-task-edit -a hello: "ase hello" CLI command which prints a nice "Hello World" in red
  • Named and Persisted Plans: You prefer a plan-driven approach, but the agent harness's Plan Mode is regularly too weak, because you want named, persisted, cross-session reachable, and strictly structured plans? &rarr; /ase-task-edit hello
  • Plan Stress-Testing: You have a task plan, but want to be relentlessly grilled about every essential aspect of it until you and the agent reach a shared understanding and no open decisions remain? &rarr; /ase-task-grill hello
  • Implementation Drafts: You prefer a plan-driven approach, but want to draft and review the implementation without later having to rewind artifacts via the version control system or the agent harness's session history? &rarr; /ase-task-implement --draft hello &rarr; /ase-task-integrate --draft hello
  • Project Insights: You want to get a quick insight into a project by determining the author, the source files with the most churn, and the module structure? &rarr; /ase-code-insight @tool
  • Code Comprehension: You want to better comprehend code by finding focused information on What, Why, Analogy, Diagram, Cruxes, and Gotchas? &rarr; /ase-code-explain @tool/src/*.ts
  • Lexical Code Analysis: You want to analyze code for potential problems related to a standard set of code quality aspects? &rarr; /ase-code-lint @tool/src/*.ts
  • Document Shortening: You want a document cut down to a hard length budget -- sentences tightened first, low-value content dropped next, the rest compressed last -- with every cut reviewed as a whole block before it is applied? &rarr; /ase-docs-shorten --chars 4000 @README.md
  • Document Refinement: You want the wording of a document refined -- long sentences shortened, nominal constructions turned into verbs, enumerations made parallel, filler words struck -- while content, numbers, and technical terms stay exactly as they are? &rarr; /ase-docs-refine @README.md
  • Document Proofreading: You want your text documents checked and corrected for spelling, punctuation, and grammar errors? &rarr; /ase-docs-proofread @README.md
  • Research Quorum: You want to research a fact by asking multiple (potentially available) foreign LLMs and methodologically derive a quorum answer? &rarr; /ase-meta-quorum What is Agentic Software Engineering?
  • Logical Code Analysis: You want to analyze code for potential problems in its logic, semantics, and control flow? &rarr; /ase-code-analyze @tool/src/*.ts
  • Automated Change Logs: You want to get your CHANGELOG.md entries automatically derived from your recent Git commits? &rarr; /ase-repo-changelog
  • Plan Implementation: You have a named, persisted task plan and now want it implemented as a single, complete change set across your project artifacts? &rarr; /ase-task-implement hello
  • Change Set Integration: You have implemented a task plan into a change set and now want it delivered into its target branch, with merge conflicts resolved semantically and the task closed afterwards? &rarr; /ase-task-integrate hello
  • Epic Plan Dissection: You have one large task plan, but want it split domain-wise and logically into cohesive parts, each materialized as its own sub-task plan you can implement separately? &rarr; /ase-task-dissect hello
  • Specification Activation: You want the SpecBook know-how -- format contract, schema, and artifact set -- activated in your session, so you can query and ad-hoc edit your specification in plain conversation? &rarr; /ase-spec-activate which personas does the specification define?
  • Specification Editing: You want your SpecBook-based specification changed straight from a plain description, in one shot and kept conformant to its format contract? &rarr; /ase-spec-edit -g -v add a Reviewer persona
  • Specification Linting: You want your SpecBook-based specification checked for syntax and formatting problems, weak statements, logical gaps in its model, and open ends which would force an implementer to guess? &rarr; /ase-spec-lint -i S09,S10
  • Artifact Reconciliation: You want one set of artifacts (e.g. CODE, DOCS) automatically aligned to reflect the current state of another set (e.g. SPEC), one-way or bidirectionally? &rarr; /ase-sync-reconcile -s SPEC -t DOCS
  • Foreign Source Import: You want external files, URLs, or pasted text ingested and turned into structured SPEC, CODE, DOCS, or TASK artifacts? &rarr; /ase-sync-import -t SPEC @requirements.txt
  • Specification Export: You want your SpecBook-based specification rendered into ready-to-consume files, like a self-contained HTML document or a paginated PDF document? &rarr; /ase-sync-export -o docs/spec.html,docs/spec.pdf
  • Task Plan Research: You want a topic of a task plan researched in depth, combining Web research with a grounding in your project artifacts, and the plan optionally refined by the recommendations of the research report? &rarr; /ase-task-research --refine hello: colored terminal output
  • Effort Estimation: You want the effort of your task plans estimated as T-shirt sizes of expected human time, and the estimation calibrated against the actual human time of your finished tasks? &rarr; /ase-task-estimate --all
  • Live Task Boards: You want all your tasks shown and manipulated live, as Kanban-style lanes, as a dependency graph, or as statistics, in the terminal or in the browser? &rarr; ase task board or ase task board --web
  • Direct Skill Usage Help: You want usage help for skills directly within your agent tool sessions? &rarr; /ase-xxx-xxx --help or /ase-help-skill root cause
  • Intent-Based Skill Matching: You know what you want, but not which skill and which options realize it, and want the fitting /ase-xxx-xxx commands generated for you? &rarr; /ase-help-intent split my huge change set into separate commits

</td> <td width="50%" valign="top">

  • Diff Summary: You want a raw Git diff turned into a concise, human-readable narrative of what changed and why, grouped by intent, and with optional intent-coherence check, risk grading and blast radius? &rarr; /ase-repo-diff -c -r -b
  • Change Review: You want the staged Git changes, a branch, or a commit reviewed the way a human reviewer would on a pull request, with an approve/reject verdict and prioritized, severity-tagged, line-cited findings? &rarr; /ase-repo-review
  • Change Set Dissection: You have one large, mixed change set, but want it split into cohesive parts, each landing in its own Git WorkTree so it can be reviewed and committed atomically? &rarr; /ase-repo-dissect -m 4
  • Branch Merging: You want a branch, including its still uncommitted changes, merged into a target branch, with merge conflicts resolved semantically and an explicit merged/conflict verdict? &rarr; /ase-repo-merge -t develop -c feature-x
  • Conflict Resolution: You ran into merge conflicts and want them resolved semantically, without losing any change, and with the unresolvable hunks kept as-is and escalated to you? &rarr; /ase-repo-resolve --interactive src/
  • Guided Bug Fixing: You want a problem or bug resolved through a structured, plan-driven funnel of candidate root causes and fix approaches instead of a direct, unstructured patch? &rarr; /ase-task-edit -a -m resolve the CLI crashes on an empty config file
  • Guided Refactoring: You want the code base refactored through a structured funnel of alternative refactoring approaches, optionally captured as a named, persisted task plan? &rarr; /ase-task-edit -a -m refactor extract the config loading into a dedicated module
  • Plan-less Code Editing: You want the code base edited directly from a query in one shot, without any task plan ceremony, but optionally grilled, verified, and isolated in a Git WorkTree? &rarr; /ase-code-edit -g -v add a --verbose option to the CLI
  • Autonomous Agent Pipeline: You want a fleet of autonomous agents to drive your tasks headless from planning over implementation and qualification to integration, supervised live on the task board? &rarr; ase agent fleet init and ase agent fleet start
  • Architecture Analysis: You want your software architecture reviewed for package cohesion and inter-package coupling to spot structural weak spots? &rarr; /ase-arch-analyze @tool/src
  • Collaborative Brainstorming: You want to figure out what to build before how, by diverging on a broad space of ideas and then converging through clustering and scoring into a recommended direction? &rarr; /ase-meta-brainstorm an offline-first sync layer for the mobile app
  • Root-Cause Analysis: You want to understand the reason for a fact with the help of the "Five-Whys" root-cause determination method? &rarr; /ase-meta-why is the Decibel (dB) unit a logarithmic one?
  • Devil's Advocate Challenge: You want a thesis or statement relentlessly challenged and criticised, and finally resolved into a balanced Hegelian synthesis? &rarr; /ase-meta-diaboli The Decibel (dB) is an intuitive unit.
  • Steelman Argument: You want a thesis or statement charitably strengthened with the strongest possible case, and finally consolidated into a fortification argument? &rarr; /ase-meta-steelman ASE is one of the best Anthropic Claude Code CLI add-ons.
  • Key Point Distillation: You want a document distilled into a flat, importance-ranked list of its key points, each with a salience rank, a rationale, and a verbatim line-cited evidence snippet? &rarr; /ase-docs-distill doc/architecture.md
  • Search Engine Consolidation: You want to query multiple (potentially available) search engines and derive a consolidated result? &rarr; /ase-meta-search What is Agentic Software Engineering?
  • ELI5 Topic Explanation: You want a topic explained in a very simple, child-friendly "Explain Like I'm 5" (ELI5) way, optionally grounded in Web facts? &rarr; /ase-meta-eli5 Fourier transform
  • Topic Quote Finding: You want quotes on a topic, sorted into a 2x2 matrix of attributed vs. anonymous and literal vs. thematic ones? &rarr; /ase-meta-quotes software architecture
  • Foreign LLM Query: You want to directly query a (potentially available) foreign LLM? &rarr; /ase-meta-chat gemini What is Agentic Software Engineering?
  • Package Discovery: You want to be supported in the discovery of suitable packages for the establishment of your technology stack? &rarr; /ase-arch-discover reactive UI DOM rendering
  • Multi-Criteria Decision Matrices: You want to be supported in the evaluation of alternatives with the methodological help of a weighted multi-criteria decision matrix? &rarr; /ase-meta-evaluate Vue vs. React vs. Angular, focus on TypeScript support and extensibility
  • Workflow Skill Generation: You want a recurring multi-step procedure -- sequential steps, parallel actions, sub-agent and skill calls -- turned into its own reusable skill? &rarr; /ase-meta-workflow optimizer analyze the code, then resolve each finding in a parallel sub-agent
  • Commit Message Crafting: You want a concise commit message crafted from the currently staged Git changes instead of writing it by hand? &rarr; /ase-repo-commit
  • Conceptual Topic Neighborhood: You want to explore the parent, sibling, and child topics of a concept, optionally grounded in Web facts and navigable in an interactive loop? &rarr; /ase-meta-proximity software architecture
  • Identifier and Name Minting: You want a UUID, a SHA-1 digest, a constant, variable, function, or class identifier, a path component, or a catchy product name minted from a short description? &rarr; /ase-meta-mint -t name a background service bridged into the agent tool
  • Harness Compatibility Self-Test: You want to check how faithfully your current LLM and its agent harness execute the core interpreter primitives the ASE skills rely on? &rarr; /ase-meta-compat
  • Convenient Foreign MCP Server Setup: You have API keys for popular AI chat services and/or Web search services which ASE could optionally leverage in various skills? &rarr; ase setup mcp activate

</td> </tr> </table>

User Setup


Prerequisites

Installation

#   install ASE tool into PATH (bootstrapping only)
npm install -g @rse/ase

#   install ASE plugin into agent tool
ase setup install [--tool claude|copilot|codex] [--scope user|project|local]

Updating

#   update ASE tool in PATH and ASE plugin in agent tool
ase setup update [--tool claude|copilot|codex] [--scope user|project|local] [--force]

Uninstallation

#   uninstall ASE tool from PATH and ASE plugin from agent tool
ase setup uninstall [--tool claude|copilot|codex] [--scope user|project|local]

Enabling/Disabling

#   enable/disable ASE plugin in agent tool (without uninstalling it)
ase setup enable    [--tool claude|copilot|codex] [--scope user|project|local]
ase setup disable   [--tool claude|copilot|codex] [--scope user|project|local]

Status

#   report ASE plugin, MCP server, output style, statusline, and telemetry registrations in agent tool
ase setup status    [--tool claude|copilot|codex]

The report lists, across all scopes at once, the registration scope and enabled/disabled state of the ASE plugin, the registration scope of each currently registered MCP server, the settings files carrying a selected (*ASE*-owned) or foreign (hand-selected) outputStyle entry, the settings files carrying an activated (*ASE*-owned) or foreign (hand-crafted) statusLine entry, and the configuration files carrying an activated (towards ASE) or foreign telemetry export. It is read-only, takes no --scope (reporting every scope is the point), and exits with status 0 in all regular cases, i.e., unless the agent tool CLI is missing or an option is invalid.

Output Style

The ASE plugin ships the output style ase:ase-terse, which lets the agent respond tersely, leading with the result and skipping preamble, narration, and closing recaps. For --tool claude, ase setup install (and ase setup update) selects it by writing "outputStyle": "ase:ase-terse" into the settings.json of the given --scope, ase setup uninstall removes this selection again, and a hand-selected foreign outputStyle is always preserved. You can switch it at any time via /config. For --tool copilot and --tool codex, which have no output style concept, the identical style instructions are injected into the session context by the ASE session-start hook instead.

Statusline

#   activate/deactivate ASE statusline in agent tool
ase setup statusline activate   [--tool claude|copilot] [--scope user|project|local]
                                [--width <n>] [--margin <n>] [--padding <n>] [--no-icons] [--no-labels]
                                [<line> ...]
ase setup statusline deactivate [--tool claude|copilot] [--scope user|project|local]

The statusline is only supported for --tool claude and --tool copilot; codex has no statusline concept. Each optional <line> argument is a format template of literal text, %-prefixed placeholders, and <color>...</color> markup (e.g. "%u %p %T"); without any, the three default lines "<blue>%u</blue> <red>%p</red> <black>%T</black> %s" (user, project, task, and session), "%m %e %t" (model, effort, a

Source 9 files
mods/ase-mods.ts 253 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Hooking infrastructure, registering the function hooks and dispatching
9    them into the grill table ("ase-mods-grill.ts"), the decision matrix
10    ("ase-mods-evaluate.ts"), the intent help ("ase-mods-help-find.ts"),
11    the synopsis form ("ase-mods-help-compose.ts"),
12    the manual band ("ase-mods-help-show.ts"), the manpage browser
13    ("ase-mods-help-browse.ts"), and the hint band ("ase-mods-help-hint.ts").
14    As the engine loads only a module spelling "on", "$", and "next" literally,
15    this is the only module touching the engine, and it binds the engine
16    services needed by the other modules as plain functions.  */
17
18import type { Register, PromptBox, Timer } from "claude-code"
19import { type Band, TRIGGER } from "./ase-mods-common.ts"
20import { modGrill }           from "./ase-mods-grill.ts"
21import { modEvaluate }        from "./ase-mods-evaluate.ts"
22import { modHelpFind }        from "./ase-mods-help-find.ts"
23import { modHelpCompose }     from "./ase-mods-help-compose.ts"
24import { modHelpShow }        from "./ase-mods-help-show.ts"
25import { modHelpBrowse }      from "./ase-mods-help-browse.ts"
26import { modHelpHint }        from "./ase-mods-help-hint.ts"
27
28/*  function hook registration entry point  */
29export const register: Register = (on, options) => {
30    /*  allow the rendering to be disabled without disabling the plugin  */
31    if (options.enabled === false)
32        return
33
34    /*  the grill table, the decision matrix, the intent help, the synopsis form,
35        the manual band, the manpage browser, and the hint band  */
36    const grill    = modGrill()
37    const evaluate = modEvaluate()
38    const intent   = modHelpFind()
39    const skill    = modHelpCompose()
40    const manual   = modHelpShow()
41    const browse   = modHelpBrowse()
42    const hint     = modHelpHint()
43
44    /*  the bands above the prompt (the synopsis form, the intent band, and the
45        manpage browser, opened in this order), the shown one (as at most one is
46        shown at a time), and closing all of them resp. the shown one on a failure
47        (determining the prompt to restore)  */
48    const bands: Band[] = [ skill, intent, browse ]
49    const shown         = () => bands.find((band) => band.active())
50    const reset         = () => bands.forEach((band) => band.reset())
51    const cancel        = () => shown()?.cancel()
52
53    /*  the generation of the latest submission (ending any older refilling of the prompt)  */
54    let submissions = 0
55
56    /*  the partial slash command inside the prompt, and the poller of the prompt
57        for the hint band while one is typed (as a completion of the typeahead
58        raises no edit)  */
59    const partial = /^\/\S*$/
60    let poller: Timer | undefined
61
62    /*  handle the still unsubmitted prompt of the user: while the intent band,
63        the synopsis form, or the manpage browser is shown, every edit is a key of
64        it, else act on the typed trigger suffix at the end of the prompt only
65        (toggling the manual band for a skill command with "//", resp. showing the
66        synopsis form for a skill command with a manual page with "!!", else arming
67        the matching of the prompt as an intent with "!!", resp. showing the manpage
68        browser for any other prompt with "//"), close the manual band once the
69        prompt left its skill command or another band opened, track the skill
70        command of the hint band, and track the picks of the grill table inside
71        the edited prompt while no band is shown  */
72    on("prompt.edit", async ($, e, next) => {
73        const band  = shown()
74        const paged = manual.active()
75        const read  = (file: string) => $.fs.read(`${$.plugin.root}/${file}`)
76        const dirs  = async (dir: string) => (await $.fs.list(`${$.plugin.root}/${dir}`))
77            .filter((entry) => entry.kind === "dir" || entry.isLink).map((entry) => entry.name)
78        const open  = async (box: PromptBox) =>
79            await manual.toggle(box, { read }) ?? await skill.open(box, { read }) ?? intent.open(box, {
80                read,
81                invalidate: () => $.ui.invalidate("ui.render"),
82                fork:       (prompt) => $.model.fork({ prompt }),
83                complete:   (request) => $.model.complete(request),
84                sleep:      (ms) => $.clock.sleep(ms)
85            }) ?? await browse.open(box, { read, dirs }) ?? box
86        let box: PromptBox
87        if (band !== undefined) {
88            const result = band.edit(e)
89            box = typeof result !== "string" ? result :
90                await next({ ...e, text: result, cursor: result.length, start: result.length, end: result.length })
91
92            /*  switch over from a closed band to another one by the trigger it left in the prompt  */
93            if (shown() === undefined && TRIGGER.test(box.text))
94                box = await open(box)
95        }
96        else {
97            box = await next(e)
98            if (/[!/]$/.test(e.inputText) && box.cursor === box.text.length && TRIGGER.test(box.text))
99                box = await open(box)
100        }
101        manual.track(box.text)
102        if (shown() !== undefined)
103            manual.reset()
104        const hinted = await hint.track(box.text, { read })
105        if (poller === undefined && partial.test(box.text)) {
106            const stop  = () => {
107                timer.cancel()
108                poller = undefined
109            }
110            const timer = $.clock.every(100, () => {
111                $.prompt.read().then(async ({ text }) => {
112                    if (!partial.test(text))
113                        stop()
114                    if (shown() === undefined && await hint.track(text, { read }))
115                        $.ui.invalidate("ui.render")
116                }).catch(stop)
117            })
118            poller = timer
119        }
120        if (shown() !== undefined || grill.track(box.text) || band !== undefined || paged || manual.active() || hinted)
121            $.ui.invalidate("ui.render")
122        return box
123    }).catch(($, e, next) => {
124        /*  close a failed intent band resp. synopsis form and restore the prompt
125            resp. the command as typed (instead of the held prompt), else let the
126            edit pass  */
127        const text = cancel()
128        $.ui.invalidate("ui.render")
129        return text !== undefined ? { text, cursor: text.length } : next(e)
130    })
131
132    /*  operate the synopsis form resp. the intent band, else scroll the manual
133        page in the band, by the wheel, and never let the engine move the window
134        over our (overflowing) band, even while it takes no scrolling  */
135    on("ui.scroll", { component: "AbovePrompt" }, ($, e, next) => {
136        if (!bands.some((band) => band.scroll(e)) && !manual.scroll(e))
137            return shown() === undefined && !manual.active() ? next(e) : {}
138        $.ui.invalidate("ui.render")
139        return {}
140    }).catch(($, e, next) =>
141        /*  let a failed scrolling of the synopsis form, the intent band, resp. the manual page pass  */
142        next(e))
143
144    /*  operate the intent band and the synopsis form by RETURN, resp. freeze the
145        picks in the latest table and close the intent band and the synopsis form
146        once the prompt is submitted  */
147    on("prompt.submit", ($, e, next) => {
148        /*  while the intent band or the synopsis form is shown, RETURN at the prompt
149            (which usually arrives as an edit of the held prompt instead, so this is
150            the fallback only) is a key of it, entering nothing and refilling the
151            prompt (immediately, and again whenever the submission cleared it or
152            restored the submitted prompt, as a duplicate of or next to the refilled
153            one, within a grace period)  */
154        const band = shown()
155        if (band !== undefined && e.origin.kind === "composer") {
156            const text = band.submit()
157            const generation = ++submissions
158            $.ui.invalidate("ui.render")
159            const fill = async () => {
160                const box = await $.prompt.fill({ text })
161                if (shown() === undefined) {
162                    grill.refresh(box.text)
163                    $.ui.invalidate("ui.render")
164                }
165            }
166            const refill = async () => {
167                await fill()
168                const prompt    = text.trim()
169                const submitted = e.text.trim()
170                for (const ms of [ 25, 50, 100, 200, 400 ]) {
171                    await $.clock.sleep(ms)
172                    const box = (await $.prompt.read()).text
173                    if (generation !== submissions)
174                        return
175                    if (box === "" || box.indexOf(prompt) !== box.lastIndexOf(prompt)
176                        || (submitted !== prompt && box.includes(submitted)))
177                        await fill()
178                }
179            }
180            refill().catch(() => {
181                /*  ignore a prompt which is no longer accessible  */
182            })
183            return { text: e.text }
184        }
185
186        /*  let any other submission (like a task notification) pass while the
187            intent band or the synopsis form is shown, as it leaves the held
188            prompt in place  */
189        if (band !== undefined)
190            return next(e)
191
192        submissions++
193        grill.submit(e.text)
194        reset()
195        manual.reset()
196        hint.reset()
197        $.ui.invalidate("ui.render")
198        return next(e)
199    }).catch(($, e, next) =>
200        /*  never let a failed RETURN of the intent band or synopsis form enter the prompt  */
201        next.called || shown() === undefined ? next(e) :
202            { drop: "intent band or synopsis form failed" })
203
204    /*  redraw the replies which contain a grilling table or a decision matrix
205        (terminal only), where the chain beneath runs, although its drawing is
206        replaced by us (but this at least silences a warning in the debug output
207        of Claude Code)  */
208    on("ui.render", { component: "AssistantMessage", surface: "terminal" }, async ($, e, next) => {
209        const drawn      = await next(e)
210        const ui         = $.ui.resolve(e)
211        const invalidate = () => $.ui.invalidate("ui.render")
212        return grill.render(e, ui, {
213            invalidate,
214            prompt:     () => $.prompt.read(),
215            fill:       (text) => $.prompt.fill({ text })
216        }) ?? evaluate.render(e, ui, { invalidate }) ?? drawn
217    })
218
219    /*  draw the intent band resp. the synopsis form, else the manual page,
220        else the argument hint, into the band above the prompt (terminal only)  */
221    on("ui.render", { component: "AbovePrompt", surface: "terminal" }, async ($, e, next) => {
222        const drawn = await next(e)
223        const ui    = $.ui.resolve(e)
224        return shown()?.render(e, ui) ?? manual.render(e, ui) ?? hint.render(e, ui) ?? drawn
225    }).catch(($, e, next) => {
226        /*  close a failed intent band resp. synopsis form, restore the prompt
227            resp. the command as typed (instead of the held prompt), resp. close
228            a failed manual band and hint band, and keep the drawing beneath  */
229        const text = cancel()
230        if (text === undefined) {
231            manual.reset()
232            hint.reset()
233        }
234        if (text !== undefined)
235            $.prompt.fill({ text }).catch(() => {
236                /*  ignore a prompt which is no longer accessible  */
237            })
238        return next(e)
239    })
240
241    /*  drop the one-line (and hence usually truncated) argument hint of the
242        skills from the typeahead and "/help", as the hint band shows it entirely  */
243    on("command.describe", async ($, e, next) => {
244        const result  = await next(e)
245        const command = /^(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+)$/.exec(e.command)
246        const read    = (file: string) => $.fs.read(`${$.plugin.root}/${file}`)
247        if (command === null || await hint.synopsis(command[1]!, { read }) === undefined)
248            return result
249        return { description: result.description, isHidden: result.isHidden }
250    })
251}
252
253
mods/ase-mods-common.ts 475 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Common parts, shared by the grill table, the decision matrix, the intent
9    help, the synopsis form, the manual band, the manpage browser, and the hint
10    band: the rows of the Markdown tables, the styled characters of the terminal
11    drawing, their Markdown conversion, wrapping, and framing, and the contract,
12    keys, geometry, and drawing of the master/detail view in the band above the
13    prompt.  */
14
15import type { Elements, Frozen, MatchedEvent, ModelCompleteRequest, ModelForkResult,
16    PromptBox, PromptEditInput, PromptFilled, RenderElement } from "claude-code"
17
18/*  the services of the engine, bound by the hooking infrastructure for the
19    modules (as the engine refuses to load a module passing "$" itself): the
20    redrawing, the reading of a plugin file and of the names of the directories
21    in a plugin directory, the forked and the plain model completion, the
22    waiting, and the reading and filling of the prompt  */
23export type Engine = {
24    invalidate: () => void,
25    read:       (file: string) => Promise<string>,
26    dirs:       (dir: string) => Promise<string[]>,
27    fork:       (prompt: string) => Promise<ModelForkResult | null>,
28    complete:   (request: ModelCompleteRequest) => Promise<string>,
29    sleep:      (ms: number) => Promise<void>,
30    prompt:     () => Promise<PromptBox>,
31    fill:       (text: string) => Promise<PromptFilled>
32}
33
34/*  the colors of a picked (resp. selected or focused) item, of a code span,
35    and of a skill command (the theme color of a command inside the prompt)  */
36export const PICKED  = "red"
37export const CODE    = "blue"
38export const COMMAND = "suggestion"
39
40/*  the trigger suffix of a synopsis form or an intent ("!!"), resp. of a manual band
41    or a manpage browser ("//") inside the prompt (each further constrained by the
42    pattern of the synopsis form, the intent, the manual band, resp. the browser)  */
43export const TRIGGER = /(?:!!|\/\/)$/
44
45/*  the share of the terminal height taken by the band above the prompt  */
46const BAND = 0.25
47
48/*  the self-drawn rounded frame around the content of the band above the
49    prompt: the columns taken by its borders and its left padding, the
50    columns before its content, and the rows taken by its edges, and the
51    style of its lines (the dimmed default color, which renders as a darker
52    grey than the "gray" color)  */
53const FRAME  = { cols: 3, lead: 2, rows: 2 } as const
54const BORDER = { dimColor: true } as const
55
56/*  the events of drawing resp. scrolling the band above the prompt  */
57export type BandRender = Frozen<MatchedEvent<"ui.render", { component: "AbovePrompt", surface: "terminal" }>>
58export type BandScroll = Frozen<MatchedEvent<"ui.scroll", { component: "AbovePrompt" }>>
59
60/*  a band above the prompt (the synopsis form, the intent band, or the manpage
61    browser, of which at most one is shown at a time), as dispatched by the
62    hooking infrastructure: whether it is shown, closing it, closing it on a
63    failure (determining the prompt to restore), operating it by a key
64    (determining the prompt to hold, resp. the text onto whose end the edit is
65    still to be applied), by the wheel, and by RETURN at the prompt
66    (determining the prompt to refill), and drawing it  */
67export type Band = {
68    active: () => boolean,
69    reset:  () => void,
70    cancel: () => string | undefined,
71    edit:   (e: Frozen<PromptEditInput>) => PromptBox | string,
72    scroll: (e: BandScroll) => boolean,
73    submit: () => string,
74    render: (e: BandRender, ui: Elements["terminal"]) => RenderElement | undefined
75}
76
77/*  hold the prompt while the band above the prompt is shown: the text with a
78    trailing space and backslash before the cursor and another space after it
79    (so, as a move or deletion at either end of the prompt raises no edit, moves
80    and deletions in both directions stay possible, and, as RETURN after a
81    backslash inserts a newline instead of submitting the prompt, RETURN
82    arrives as an edit, too, which keeps the cursor inside the prompt)  */
83export const held = (text: string): PromptBox =>
84    ({ text: `${text} \\ `, cursor: text.length + 2 })
85
86/*  a key pressed in the band above the prompt: its name, its typed text, its
87    cursor step (-1 left, +1 right), and its deletion (-1 backward, +1 forward)  */
88export type Key = { name: string, text: string, step: number, erase: number }
89
90/*  decode an edit of the held prompt into a key, where RETURN arrives as a
91    typed newline, and cursor moves and deletions are told by their splice  */
92export const decode = (e: Frozen<PromptEditInput>): Key => {
93    const name   = e.inputText === "\n" ? "return" : e.key?.key ?? ""
94    const erased = e.inputText === "" && e.end > e.start
95    return {
96        name,
97        text:  e.inputText === "\n" ? "" : e.inputText,
98        step:  name === "left" ? -1 : name === "right" ? 1 :
99            e.inputText === "" && !erased ? Math.sign(e.start - e.cursor) : 0,
100        erase: erased ? (e.start < e.cursor ? -1 : 1) : 0
101    }
102}
103
104/*  a row and the delimiter row of a Markdown table  */
105export const ROW  = /^ *\|.*\| *$/
106export const RULE = /^ *\|(?: *:?-+:? *\|)+ *$/
107
108/*  split a Markdown table row into its cells  */
109export const cells = (line: string): string[] => {
110    const result: string[] = []
111    const body = line.trim().replace(/^\|/, "").replace(/\|$/, "")
112    let cell = ""
113    let code = false
114    for (let i = 0; i < body.length; i++) {
115        const ch = body[i]!
116        if (ch === "`")
117            code = !code
118        if (!code && ch === "\\" && body[i + 1] === "|") {
119            cell += "|"
120            i++
121        }
122        else if (!code && ch === "|") {
123            result.push(cell.trim())
124            cell = ""
125        }
126        else
127            cell += ch
128    }
129    result.push(cell.trim())
130    return result
131}
132
133/*  a single styled character of the terminal drawing  */
134export type Char = { ch: string, bold: boolean, color: string | undefined }
135
136/*  extract a section of a manual page (without its heading)  */
137export const section = (manual: string, name: string): string =>
138    manual.split(/^(?=## {2})/m).find((text) => text.startsWith(`##  ${name}`))?.replace(/^.*\n/, "") ?? ""
139
140/*  convert inline Markdown (bold and code spans) into styled characters  */
141export const style = (text: string, color: string | undefined): Char[] => {
142    const chars: Char[] = []
143    let bold = false
144    let code = false
145    for (let i = 0; i < text.length; i++) {
146        if (!code && text.startsWith("**", i)) {
147            bold = !bold
148            i++
149        }
150        else if (text[i] === "`")
151            code = !code
152        else {
153            const ch = String.fromCodePoint(text.codePointAt(i)!)
154            chars.push({ ch, bold, color: color ?? (code ? CODE : undefined) })
155            i += ch.length - 1
156        }
157    }
158    return chars
159}
160
161/*  the width of styled characters in terminal cells  */
162export const width = (chars: Char[]): number => {
163    let n = 0
164    for (const { ch } of chars) {
165        const c = ch.codePointAt(0)!
166        if ((c >= 0x200B && c <= 0x200D) || c === 0x2060 || c === 0xFEFF ||
167            (c >= 0x0300 && c <= 0x036F) || (c >= 0xFE00 && c <= 0xFE0F))
168            continue
169        const wide =
170            (c >= 0x1100  && c <= 0x115F) || (c >= 0x2E80  && c <= 0xA4CF) ||
171            (c >= 0xAC00  && c <= 0xD7A3) || (c >= 0xF900  && c <= 0xFAFF) ||
172            (c >= 0xFF00  && c <= 0xFF60) || (c >= 0x1F300 && c <= 0x1FAFF) ||
173            (c >= 0x20000 && c <= 0x3FFFD)
174        n += wide ? 2 : 1
175    }
176    return n
177}
178
179/*  hard-wrap styled characters at word boundaries to the given columns,
180    indenting the first line by "lead" and all further lines by "indent"
181    (and chopping overlong words)  */
182export const wrap = (chars: Char[], columns: number, indent: number, lead = 0): Char[][] => {
183    const space: Char = { ch: " ", bold: false, color: undefined }
184    const words: Char[][] = [ [] ]
185    for (const char of chars) {
186        if (char.ch === " ")
187            words.push([])
188        else
189            words.at(-1)!.push(char)
190    }
191    const lines: Char[][] = []
192    let line: Char[] = Array.from({ length: lead }, () => space)
193    let start = lead
194    let size  = lead
195    const flush = () => {
196        lines.push(line)
197        line  = Array.from({ length: indent }, () => space)
198        start = indent
199        size  = indent
200    }
201    for (let word of words.filter((word) => word.length > 0)) {
202        while (word.length > 0) {
203            const w = width(word)
204            if (size > start && size + 1 + w <= columns) {
205                line.push(space, ...word)
206                size += 1 + w
207                word = []
208            }
209            else if (size > start)
210                flush()
211            else {
212                let n = 1
213                while (n < word.length && width(word.slice(0, n + 1)) <= columns - start)
214                    n++
215                line.push(...word.slice(0, n))
216                size += width(word.slice(0, n))
217                word = word.slice(n)
218                if (word.length > 0)
219                    flush()
220            }
221        }
222    }
223    lines.push(line)
224    return lines
225}
226
227/*  a run of equally styled characters  */
228type Run = { text: string, bold: boolean, color: string | undefined }
229
230/*  split a line of styled characters into runs of equally styled characters  */
231export const split = (chars: Char[]): Run[] => {
232    const runs: Run[] = []
233    for (let i = 0, j = 0; i < chars.length; i = j) {
234        const { bold, color } = chars[i]!
235        while (j < chars.length && chars[j]!.bold === bold && chars[j]!.color === color)
236            j++
237        runs.push({ text: chars.slice(i, j).map((char) => char.ch).join(""), bold, color })
238    }
239    return runs
240}
241
242/*  convert plain text (without any Markdown) into equally styled characters  */
243export const uniform = (text: string, bold: boolean, color: string | undefined): Char[] =>
244    Array.from(text, (ch) => ({ ch, bold, color }))
245
246/*  strip the single-asterisk emphasis outside the code spans of inline Markdown  */
247export const strip = (text: string): string =>
248    text.split("`").map((part, i) => i % 2 === 0 ? part.replace(/(?<!\*)\*(?!\*)/g, "") : part).join("`")
249
250/*  convert the Markdown blocks of a manual page section (paragraphs, list items,
251    and code fences) into lines of styled characters, hard-wrapped to the given
252    columns (except for the code lines), with a blank line between the blocks,
253    where "nested" keeps the indentation of the blocks and of the list item texts  */
254export const flow = (text: string, columns: number, nested = false): Char[][] => {
255    const result: Char[][] = []
256    let block: string[] = []
257    let fence = false
258    const flush = () => {
259        if (block.length === 0)
260            return
261        if (result.length > 0)
262            result.push([])
263        const pad  = nested ? /^ */.exec(block[0]!)![0].length : 0
264        const body = strip(block.map((line) => line.trim()).join(" "))
265        const item = /^(-|\d+\.)\s+/.exec(body)
266        if (item !== null) {
267            const mark  = (item[1] === "-" ? "•" : item[1]!).padEnd(nested ? item[0].length : item[1]!.length + 1)
268            const lines = wrap(style(body.slice(item[0].length), undefined), columns, pad + mark.length, pad + mark.length)
269            lines[0]!.splice(pad, mark.length, ...uniform(mark, false, undefined))
270            result.push(...lines)
271        }
272        else
273            result.push(...wrap(style(body, undefined), columns, pad, pad))
274        block = []
275    }
276    for (const line of text.replace(/^\s*\n|\s+$/g, "").split("\n")) {
277        if (line.startsWith("```")) {
278            flush()
279            if (!fence && result.length > 0)
280                result.push([])
281            fence = !fence
282        }
283        else if (fence)
284            result.push(uniform(line, false, CODE))
285        else if (line.trim() === "")
286            flush()
287        else {
288            if (/^(?:-|\d+\.)\s/.test(line))
289                flush()
290            block.push(line)
291        }
292    }
293    flush()
294    return result
295}
296
297/*  surround lines of styled characters with a rounded box of the given total
298    columns and border color (padding the lines to the inner columns)  */
299export const frame = (lines: Char[][], columns: number, color: string | undefined): Char[][] => {
300    const rim = (text: string) => uniform(text, false, color)
301    return [
302        rim(`╭${"─".repeat(columns - 2)}╮`),
303        ...lines.map((line) => [ ...rim("│ "), ...line,
304            ...uniform(" ".repeat(Math.max(0, columns - 4 - width(line))), false, undefined), ...rim(" │") ]),
305        rim(`╰${"─".repeat(columns - 2)}╯`)
306    ]
307}
308
309/*  split a horizontal edge of a frame into runs with a title placed after its
310    first and another one before its last two characters (each if it fits, the
311    one at the end with precedence), flagged whether they are a title  */
312const titled = (line: string, head: string, tail: string): [ string, boolean ][] => {
313    const end   = tail !== "" && line.length >= tail.length + 4 ? tail : ""
314    const start = head !== "" && line.length >= head.length + (end !== "" ? end.length + 6 : 4) ? head : ""
315    const k     = end !== "" ? line.length - 2 - end.length : line.length
316    return [
317        ...(start !== "" ? [ [ line.slice(0, 2), false ], [ start, true ] ] as [ string, boolean ][] : []),
318        [ line.slice(start !== "" ? 2 + start.length : 0, k), false ],
319        ...(end !== "" ? [ [ end, true ], [ line.slice(k + end.length), false ] ] as [ string, boolean ][] : [])
320    ]
321}
322
323/*  the scroll position of a view with the given rows over the given lines
324    at the given scroll position, as placed into the bottom edge of a frame  */
325const position = (rows: number, lines: number, scroll: number): string =>
326    lines === 0 ? "" : `[ lines ${scroll + 1}-${Math.min(scroll + rows, lines)}/${lines} ]`
327
328/*  the mark of a scrollbar row: the thumb, the track, or nothing  */
329type Mark = "thumb" | "track" | "none"
330
331/*  determine the scrollbar of a view with the given rows over the given lines at
332    the given scroll position: for each row the thumb, the track, or nothing  */
333const scrollbar = (rows: number, lines: number, scroll: number): Mark[] => {
334    if (lines <= rows)
335        return Array.from({ length: rows }, () => "none")
336    const thumb  = Math.max(1, Math.round(rows * rows / lines))
337    const offset = Math.round(scroll / (lines - rows) * (rows - thumb))
338    return Array.from({ length: rows }, (_, i) => i >= offset && i < offset + thumb ? "thumb" : "track")
339}
340
341/*  determine the rows a scroll event moves a view by: a page of the given size
342    for the scroll keys (PAGEUP/PAGEDOWN), resp. its rows for the wheel  */
343const paging = (e: { pointer?: unknown, by: number }, size: number): number =>
344    e.pointer === undefined && Math.abs(e.by) > 1 ? Math.sign(e.by) * size : e.by
345
346/*  the text element of the terminal surface  */
347export type Text = Elements["terminal"]["Text"]
348
349/*  draw a line of styled characters: its styled runs  */
350export const paint = (Text: Text, chars: Char[]): (string | RenderElement)[] =>
351    split(chars).map(({ text, bold, color }) =>
352        bold || color !== undefined ? Text({ bold, color, children: text }) : text)
353
354/*  draw a horizontal edge of the self-drawn frame (dimmed), with titles at its
355    start and its end (with their brackets dimmed, an "ASE" prefix before a colon
356    in bold, and the rest dimmed)  */
357const edge = (Text: Text, line: string, head = "", tail = ""): RenderElement =>
358    Text({ children: titled(line, head, tail).flatMap(([ text, label ]) => {
359        const m = /^(\[ )?([^:]*)(:.*?)( \])?$/.exec(text)
360        if (!label || m === null)
361            return [ Text({ ...BORDER, children: text }) ]
362        return [
363            ...(m[1] !== undefined ? [ Text({ ...BORDER, children: m[1] }) ] : []),
364            Text({ bold: true, children: m[2]! }),
365            Text({ dimColor: true, children: m[3]! }),
366            ...(m[4] !== undefined ? [ Text({ ...BORDER, children: m[4] }) ] : [])
367        ]
368    }) })
369
370/*  draw a row of a scrollbar: the thumb, the (dimmed) track, or nothing  */
371const bar = (Text: Text, mark: Mark | undefined): RenderElement =>
372    mark === "thumb" ? Text({ children: "█" }) :
373        mark === "track" ? Text({ dimColor: true, children: "░" }) : Text({ children: " " })
374
375/*  the geometry of the band above the prompt: the inner columns of the self-drawn
376    frame, the rows of its views, the columns of its master and detail view, and
377    whether the band overflows (to receive the scrolling)  */
378export type Layout = { span: number, body: number, master: number, detail: number, overflow: boolean }
379
380/*  determine the geometry of the band above the prompt: the inner columns (both
381    borders and the left padding subtracted), the rows (with the frame and the footer
382    subtracted) out of a share of the terminal height (but never more than the rows of
383    the band), resp., in fullscreen (where the engine raises the scrolling by the wheel
384    and, once focused, by the keys only for a tree taller than the band), all rows of
385    the band but the one of the engine's "n more" row (as the band then takes them
386    anyway), and the columns of the master view (by the given share) and of the
387    detail view (with a separator column between them, and a gap of two columns and
388    a scrollbar column right of the detail view)  */
389export const layout = (e: BandRender, share: number, band = BAND): Layout => {
390    const span     = Math.max(20, e.props.bodyColumns - FRAME.cols)
391    const overflow = e.viewport?.isFullscreen === true
392    const height   = overflow ? Math.max(FRAME.rows + 2, e.props.maxRows - 1) : Math.min(e.props.maxRows,
393        Math.max(FRAME.rows + 2, Math.floor((e.viewport?.rows ?? e.props.maxRows) * band)))
394    const master   = Math.floor((span - 3 - 3) * share)
395    return { span, body: Math.max(1, height - FRAME.rows - 1), master, detail: span - master - 3 - 3, overflow }
396}
397
398/*  the scroll state of the band above the prompt: the first shown row of the
399    master view, the first shown line and the lines of a page of the detail
400    view, and the first band column right of the master view  */
401export type View = { top: number, scroll: number, page: number, split: number }
402
403/*  operate a view by the wheel: over the master view step it (if steppable),
404    else scroll the detail view, resp. scroll it by a page with the scroll keys
405    (PAGEUP/PAGEDOWN) while the band is focused  */
406export const wheel = (e: BandScroll, view: View, step?: (by: number) => void): void => {
407    if (step !== undefined && e.pointer !== undefined && e.pointer.column < view.split)
408        step(Math.sign(e.by))
409    else
410        view.scroll = Math.max(0, view.scroll + paging(e, view.page))
411}
412
413/*  draw the band above the prompt: inside the self-drawn frame (with the title
414    in its top edge) either a single view of the given rows, a single view of the
415    given lines with its scrollbar, or a master view of the given rows (where the
416    given rule rows are horizontal lines joining the borders) and, joined by a
417    separator, a detail view of the given lines (optionally dimmed) with its
418    scrollbar, into the bottom edge the given status (if any) at its start and
419    the scroll position of the lines (unless they always fit) at its end, and below
420    the frame the key hints (followed by blank rows for an overflowing band),
421    where the scroll position is clamped, and the page size (for the scroll keys)
422    and the end of the master view (for the wheel) are remembered in the view  */
423export const panel = (ui: Elements["terminal"], { span, body, master, detail, overflow }: Layout, view: View, spec: {
424    title:   string,
425    status?: string,
426    hints:   string,
427    rows?:   (i: number) => RenderElement | undefined,
428    rule?:   (i: number) => boolean,
429    lines?:  Char[][],
430    dim?:    boolean,
431    fit?:    boolean
432}): RenderElement => {
433    const { Box, Text } = ui
434    const lines = spec.lines ?? []
435    const solo  = spec.rows === undefined
436    view.page   = Math.max(1, body - 1)
437    view.split  = solo ? 0 : FRAME.lead + master
438    view.scroll = Math.max(0, Math.min(view.scroll, lines.length - body))
439    const marks  = scrollbar(body, lines.length, view.scroll)
440    const blank  = Text({ children: " " })
441    const border = (left: string, joint: string, right: string) =>
442        left + (spec.lines === undefined || solo ? "─".repeat(span + 1) :
443            "─".repeat(master + 2) + joint + "─".repeat(detail + 4)) + right
444    const scrolled = (i: number, width: number) => [
445        Box({ width, flexShrink: 0, children:
446            Text({ wrap: "truncate-end", dimColor: spec.dim ?? false,
447                children: paint(Text, lines[view.scroll + i] ?? []) }) }),
448        Text({ children: "  " }),
449        bar(Text, marks[i])
450    ]
451    const rows: RenderElement[] = [ edge(Text, border("╭", "┬", "╮"), spec.title) ]
452    for (let i = 0; i < body; i++) {
453        const rule = !solo && spec.lines !== undefined && spec.rule?.(i) === true
454        rows.push(Box({ flexDirection: "row", children: [
455            Text({ ...BORDER, children: rule ? "├─" : "│ " }),
456            ...(solo ? scrolled(i, span - 3) : spec.lines === undefined ? [
457                Box({ width: span, flexShrink: 0, children: spec.rows!(i) ?? blank })
458            ] : [
459                rule ? Text({ ...BORDER, children: `${"─".repeat(master + 1)}┤ ` }) :
460                    Box({ width: master, flexShrink: 0, children: spec.rows!(i) ?? blank }),
461                ...(rule ? [] : [ Text({ ...BORDER, children: " │ " }) ]),
462                ...scrolled(i, detail)
463            ]),
464            Text({ ...BORDER, children: "│" })
465        ] }))
466    }
467    rows.push(edge(Text, border("╰", "┴", "╯"), spec.status,
468        spec.fit === true ? "" : position(body, lines.length, view.scroll)))
469    rows.push(Box({ paddingLeft: 1, children: Text({ dimColor: true, wrap: "truncate-end", children: spec.hints }) }))
470    if (overflow)
471        rows.push(blank, blank)
472    return Box({ flexDirection: "column", width: "100%", children: rows })
473}
474
475
mods/ase-mods-grill.ts 284 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Grill table, redrawing the grilling tables of ASE with one answer
9    alternative per line (wrapped lines indented) and rendering in red
10    the answers picked in the prompt via "nX" short responses and the
11    question selected in the prompt via the last standalone "n". In the
12    latest table, questions and answers are clickable and insert their
13    "n" or "nX" into the prompt.  */
14
15import type { Elements, Frozen, MatchedEvent, RenderElement } from "claude-code"
16import { type Engine, type Char, PICKED, ROW, RULE, cells, style, width, wrap, split, paint } from "./ase-mods-common.ts"
17
18/*  the marker line above a grilling table (single-round and multi-round,
19    optionally labeled with the perspective and/or grounding)  */
20const MARKER = /⧉ \*{0,2}ASE\*{0,2}: GRILLING(?: ROUND \d+\/\d+)?(?: \([^)]*\))?:/
21
22/*  the separator between two answers, the letter of
23    an answer, and the number of a question  */
24const ANSWER = /,\s+(?=\*{0,2}[A-Z]\*{0,2}\s+▶)/
25const LETTER = /^\*{0,2}([A-Z])\*{0,2}\s+▶/
26const NUMBER = /^\*{0,2}(\d+)\*{0,2}\s+▶/
27
28/*  a short response "nX" inside the prompt  */
29const PICK = /(?<![^\s,])(\d+)([a-zA-Z])(?![^\s,])/g
30
31/*  a standalone question number "n" inside the prompt  */
32const SELECT = /(?<![^\s,])(\d+)(?![^\s,])/g
33
34/*  the indent of the wrapped lines of an answer
35    and the size limit of a single "Markdown" element  */
36const INDENT = 4
37const LIMIT  = 10000
38
39/*  a grilling table with the Markdown text before and after it  */
40type Table = {
41    before: string,
42    after:  string,
43    header: string[],
44    rows:   { number: number, question: string, answers: { letter: string, text: string }[] }[]
45}
46
47/*  parse the grilling table out of the text of a reply  */
48const parse = (text: string): Table | undefined => {
49    const lines = text.split("\n")
50    const m = lines.findIndex((line) => MARKER.test(line))
51    const h = lines.findIndex((line, i) => m !== -1 && i > m && ROW.test(line))
52    if (h === -1 || !RULE.test(lines[h + 1] ?? ""))
53        return undefined
54    const header = cells(lines[h]!).map((cell) => cell.replace(/\*/g, ""))
55    if (header.length !== 2 || header[0] !== "QUESTION" || !/^ANSWERS?$/.test(header[1]!))
56        return undefined
57    let end = h + 2
58    while (end < lines.length && ROW.test(lines[end]!))
59        end++
60    const rows = lines.slice(h + 2, end).map((line) => cells(line))
61    if (rows.length === 0 || rows.some((row) => row.length !== 2))
62        return undefined
63    return {
64        before: lines.slice(0, h).join("\n").trim(),
65        after:  lines.slice(end).join("\n").replace(/^\n+/, "").trimEnd(),
66        header,
67        rows:   rows.map((row, i) => ({
68            number:   Number(NUMBER.exec(row[0]!)?.[1] ?? i + 1),
69            question: row[0]!,
70            answers:  row[1]!.split(ANSWER).map((answer) =>
71                ({ letter: LETTER.exec(answer)?.[1] ?? "", text: answer }))
72        }))
73    }
74}
75
76/*  determine the picked answer letter of each question out of a prompt (last pick wins)  */
77const pick = (text: string): Map<number, string> =>
78    new Map([ ...text.matchAll(PICK) ].map((m) => [ Number(m[1]!), m[2]!.toUpperCase() ]))
79
80/*  determine the selected question number out of a prompt (last standalone number wins)  */
81const select = (text: string): number | undefined => {
82    const m = [ ...text.matchAll(SELECT) ].at(-1)
83    return m !== undefined ? Number(m[1]!) : undefined
84}
85
86/*  the standalone tokens of question "n" inside the prompt: its bare
87    number "n" (letter "") or its short responses "nX" (letter "[a-zA-Z]")  */
88const token = (number: number, letter: string): RegExp =>
89    new RegExp(`(?<![^\\s,])${number}${letter}(?![^\\s,])`, "g")
90
91/*  insert the number "n" of a clicked question or the short response "nX" of a
92    clicked answer into a prompt. Answer: an existing "nY" is replaced in place
93    (and a bare "n" removed), else a bare "n" is replaced in place, else "nX" is
94    appended. Question: an existing bare "n" is kept, else the last bare number
95    of another question (the selected one) is replaced in place, else "n" is
96    appended.  */
97const insert = (text: string, number: number, letter?: string): string => {
98    const bare  = token(number, "")
99    const picks = token(number, "[a-zA-Z]")
100    if (letter !== undefined && text.search(picks) !== -1)
101        return text.replace(picks, `${number}${letter}`)
102            .replace(new RegExp(`\\s*${bare.source}`, "g"), "").trimStart()
103    if (text.search(bare) !== -1)
104        return letter !== undefined ? text.replace(bare, `${number}${letter}`) : text
105    const last = letter === undefined ? [ ...text.matchAll(SELECT) ].at(-1) : undefined
106    if (last !== undefined)
107        return text.slice(0, last.index) + String(number) + text.slice(last.index + last[0].length)
108    const head = text.trimEnd()
109    return `${head}${head !== "" ? " " : ""}${number}${letter ?? ""}`
110}
111
112/*  style the cells of a table and determine its column widths within the available
113    columns, right-aligning the question numbers to the widest one (so the wrapped
114    lines of all questions share the same indent)  */
115const layout = (table: Table, avail: number,
116    chosen: Map<number, string> | undefined, marked: number | undefined) => {
117    const head   = table.header.map((cell) => style(`**${cell}**`, undefined))
118    const digits = Math.max(...table.rows.map((row) => String(row.number).length))
119    const rows   = table.rows.map((row) => {
120        const numbered = NUMBER.test(row.question)
121        return {
122            lead:     numbered ? digits - String(row.number).length : 0,
123            indent:   numbered ? digits + 3 : 0,
124            question: style(row.question, marked === row.number ? PICKED : undefined),
125            answers:  row.answers.map((answer) =>
126                style(answer.text, chosen?.get(row.number) === answer.letter ? PICKED : undefined))
127        }
128    })
129    const w1nat = Math.max(width(head[0]!), ...rows.map((row) => row.lead + width(row.question)))
130    const w2nat = Math.max(width(head[1]!), ...rows.flatMap((row) => row.answers.map((answer) => width(answer))))
131    let   w1    = Math.min(w1nat, Math.floor(avail * 0.4))
132    const w2    = Math.min(w2nat, avail - w1)
133    w1          = Math.min(w1nat, avail - w2)
134    return { head, rows, w1, w2 }
135}
136
137/*  the grill table: its state and its operations  */
138export const modGrill = () => {
139    /*  the last known width of the terminal, the already seen tables, the
140        latest (still unanswered) table, the picks and the selected question of the
141        still unsubmitted prompt, and the frozen picks of the already answered tables  */
142    let columns  = 80
143    const seen   = new Set<string>()
144    let latest: string | undefined
145    let picks    = new Map<number, string>()
146    let selected: number | undefined
147    const frozen = new Map<string, Map<number, string>>()
148
149    /*  refresh the picks and the selection from the prompt  */
150    const refresh = (text: string) => {
151        picks    = pick(text)
152        selected = select(text)
153    }
154
155    /*  track the picks inside the edited prompt (and tell whether they changed)  */
156    const track = (text: string): boolean => {
157        const before = JSON.stringify([ [ ...picks ], selected ])
158        refresh(text)
159        return JSON.stringify([ [ ...picks ], selected ]) !== before
160    }
161
162    /*  freeze the picks in the latest table once the prompt is submitted  */
163    const submit = (text: string) => {
164        if (latest !== undefined)
165            frozen.set(latest, pick(text))
166        latest   = undefined
167        picks    = new Map()
168        selected = undefined
169    }
170
171    /*  insert the number of a clicked question or the short response of a clicked
172        answer into the prompt and refresh the picks and the selection from it  */
173    const press = (engine: Pick<Engine, "invalidate" | "prompt" | "fill">,
174        number: number, letter?: string) => () => {
175        engine.prompt()
176            .then(({ text }) => engine.fill(insert(text, number, letter)))
177            .then((box) => {
178                refresh(box.text)
179                engine.invalidate()
180            })
181            .catch(() => {
182                /*  ignore a prompt which is no longer accessible  */
183            })
184    }
185
186    /*  redraw a reply which contains a grilling table (terminal only),
187        resp. draw nothing for any other reply  */
188    const render = (e: Frozen<MatchedEvent<"ui.render", { component: "AssistantMessage", surface: "terminal" }>>,
189        ui: Elements["terminal"], engine: Pick<Engine, "invalidate" | "prompt" | "fill">): RenderElement | undefined => {
190        /*  act on grilling tables only, which fit into the terminal
191            (gutter, grid lines, cell paddings, and a spare column subtracted)  */
192        columns = e.viewport?.columns ?? columns
193        const table = parse(e.props.text)
194        const avail = columns - 2 - 7 - 1
195        if (table === undefined || avail < 40 || table.before.length > LIMIT || table.after.length > LIMIT)
196            return undefined
197
198        /*  determine the picks: frozen ones or, for the latest table, the live ones  */
199        if (!seen.has(e.requestId)) {
200            seen.add(e.requestId)
201            latest = e.requestId
202        }
203        const chosen = frozen.get(e.requestId) ?? (e.requestId === latest ? picks : undefined)
204        const marked = e.requestId === latest ? selected : undefined
205
206        /*  style the cells and determine the column widths  */
207        const { head, rows, w1, w2 } = layout(table, avail, chosen, marked)
208
209        /*  resolve the UI elements  */
210        const { Box, Text, Button, Markdown } = ui
211
212        /*  draw a line of a cell: its styled runs, padded to the column width  */
213        const padded = (chars: Char[], span: number): (string | RenderElement)[] =>
214            [ ...paint(Text, chars), " ".repeat(Math.max(0, span - width(chars))) ]
215
216        /*  draw a line of a cell: in the latest table as the styled text inside a
217            hover-scoping box, which while any line of its group (all lines of the
218            same question or answer) is hovered reveals a row of clickable plain
219            buttons (one per styled run, inverted in the default colors and carrying
220            the run's bold style, but not its color, as its hover style, because the
221            engine leaves the space cells uncolored) on top of it; otherwise as
222            styled text only  */
223        const draw = (chars: Char[], span: number, group: string, line: number,
224            onPress: (() => void) | undefined): RenderElement[] => {
225            const w = width(chars)
226            if (e.requestId !== latest || w === 0 || onPress === undefined)
227                return [ Text({ children: padded(chars, span) }) ]
228            const buttons = split(chars).map(({ text, bold }, r) =>
229                Button({ key: `${group}/${line}/${r}`, label: text, plain: true, onPress,
230                    hover: { scope: group, inverse: true, bold } }))
231            return [
232                Box({ key: `${group}/${line}`, hover: { scope: group }, children: [
233                    Text({ children: padded(chars, w) }),
234                    Box({ position: "absolute", top: 0, left: 0, display: "none",
235                        hover: { scope: group, display: "flex" }, flexDirection: "row", children: buttons })
236                ] }),
237                Text({ children: " ".repeat(Math.max(0, span - w)) })
238            ]
239        }
240
241        /*  draw the table as a grid: a rule between all rows and one answer per line  */
242        const rule = (l: string, m: string, r: string) =>
243            Text({ wrap: "truncate-end", children: l + "─".repeat(w1 + 2) + m + "─".repeat(w2 + 2) + r })
244        const grid: RenderElement[] = [
245            rule("┌", "┬", "┐"),
246            Text({ wrap: "truncate-end", children:
247                [ "│ ", ...padded(head[0]!, w1), " │ ", ...padded(head[1]!, w2), " │" ] }),
248            rule("├", "┼", "┤")
249        ]
250        rows.forEach((row, k) => {
251            const number = table.rows[k]!.number
252            const q = wrap(row.question, w1, row.indent, row.lead).map((line, i) =>
253                draw(line, w1, `q${number}`, i, press(engine, number)))
254            const a = row.answers.flatMap((answer, j) => {
255                const letter = table.rows[k]!.answers[j]!.letter
256                return wrap(answer, w2, INDENT).map((line, i) =>
257                    draw(line, w2, `a${number}${letter}`, i, letter !== "" ? press(engine, number, letter) : undefined))
258            })
259            for (let i = 0; i < Math.max(q.length, a.length); i++)
260                grid.push(Box({ flexDirection: "row", children: [
261                    Text({ children: "│ " }),
262                    ...(q[i] ?? [ Text({ children: " ".repeat(w1) }) ]),
263                    Text({ children: " │ " }),
264                    ...(a[i] ?? [ Text({ children: " ".repeat(w2) }) ]),
265                    Text({ children: " │" })
266                ] }))
267            grid.push(k < rows.length - 1 ? rule("├", "┼", "┤") : rule("└", "┴", "┘"))
268        })
269
270        /*  mimic the reply row of the engine: blank row above and bullet gutter  */
271        return Box({ flexDirection: "row", marginTop: 1, width: "100%", children: [
272            Box({ flexShrink: 0, minWidth: 2, children: Text({ children: e.props.isFirstOfReply ? "⏺" : " " }) }),
273            Box({ flexDirection: "column", flexGrow: 1, flexShrink: 1, children: [
274                ...(table.before !== "" ? [ Markdown({ text: table.before }) ] : []),
275                Box({ flexDirection: "column", marginTop: table.before !== "" ? 1 : 0, children: grid }),
276                ...(table.after !== "" ? [ Box({ marginTop: 1, children: Markdown({ text: table.after }) }) ] : [])
277            ] })
278        ] })
279    }
280
281    return { refresh, track, submit, render }
282}
283
284
mods/ase-mods-evaluate.ts 228 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Decision matrix, redrawing the weighted decision matrices of the
9    "ase-meta-evaluate" skill as a grid and rendering in blue and bold the
10    column of the best alternative (resp. of all tied best ones). Its
11    header cells are clickable and sort the criteria rows by their column
12    (cycling the primary, the reverse, and the original order), while the
13    rating row stays the last one.  */
14
15import type { Elements, Frozen, MatchedEvent, RenderElement } from "claude-code"
16import { type Engine, type Char, ROW, RULE, cells, strip, style, width, wrap, split, paint } from "./ase-mods-common.ts"
17
18/*  the marker line above a decision matrix  */
19const MARKER = /\*{0,2}EVALUATION\*{0,2}:\s+\*{0,2}Weighted Multi-Criteria Decision Matrix/
20
21/*  the color of the best alternatives, and the rating distance (relative to
22    the best rating) below which alternatives tie (as in "ase-meta-evaluate")  */
23const WINNER = "blue"
24const TIE    = 0.01
25
26/*  the sort marks of the orders (each taking the same columns)  */
27const MARK = { desc: " ▼", asc: " ▲", none: "  " } as const
28
29/*  the indent of the wrapped lines of a criterion, the narrowest criteria
30    column, and the size limit of a single "Markdown" element  */
31const INDENT = 2
32const NARROW = 12
33const LIMIT  = 10000
34
35/*  a decision matrix with the Markdown text before and after it: its header
36    cells, its criteria rows (with the values of their weight and evaluations),
37    its rating row, and the columns of the best alternatives  */
38type Matrix = {
39    before:  string,
40    after:   string,
41    header:  string[],
42    rows:    { cells: string[], values: number[] }[],
43    rating:  string[],
44    winners: Set<number>
45}
46
47/*  the sort of a matrix: the sorted column and its order  */
48type Order = "desc" | "asc"
49type Sort  = { column: number, order: Order }
50
51/*  read the number of a cell (without bold markup and a leading plus sign)  */
52const number = (cell: string): number => {
53    const text = cell.replace(/\*/g, "").trim().replace(/^\+/, "")
54    return text !== "" ? Number(text) : NaN
55}
56
57/*  parse the decision matrix out of the text of a reply  */
58const parse = (text: string): Matrix | undefined => {
59    const lines = text.split("\n")
60    const m = lines.findIndex((line) => MARKER.test(line))
61    const h = lines.findIndex((line, i) => m !== -1 && i > m && ROW.test(line))
62    if (h === -1 || !RULE.test(lines[h + 1] ?? ""))
63        return undefined
64    const header = cells(lines[h]!).map((cell) => cell.replace(/\*/g, ""))
65    if (header.length < 3 || !/Criteria/.test(header[0]!) || !/Weight/.test(header[1]!))
66        return undefined
67    let end = h + 2
68    while (end < lines.length && ROW.test(lines[end]!))
69        end++
70    const rows   = lines.slice(h + 2, end).map((line) => cells(line))
71    const rating = rows.pop() ?? []
72    if (rows.length === 0 || rows.some((row) => row.length !== header.length)
73        || rating.length !== header.length || rating[0]!.replace(/\*/g, "") !== "RATING")
74        return undefined
75    const values  = rows.map((row) => row.slice(1).map(number))
76    const ratings = rating.slice(2).map(number)
77    if ([ ...values.flat(), ...ratings ].some((value) => !Number.isFinite(value)))
78        return undefined
79    const best = Math.max(...ratings)
80    return {
81        before:  lines.slice(0, h).join("\n").trim(),
82        after:   lines.slice(end).join("\n").replace(/^\n+/, "").trimEnd(),
83        header,
84        rows:    rows.map((row, k) => ({ cells: row, values: values[k]! })),
85        rating,
86        winners: new Set(ratings.flatMap((value, j) =>
87            value === best || best - value < TIE * Math.abs(best) ? [ j + 2 ] : []))
88    }
89}
90
91/*  advance the sort by a clicked column: its primary order (ascending for
92    the criteria names, descending for the values), then its reverse order,
93    and then the original order again  */
94const advance = (sort: Sort | undefined, column: number): Sort | undefined => {
95    const primary: Order = column === 0 ? "asc"  : "desc"
96    const reverse: Order = column === 0 ? "desc" : "asc"
97    if (sort?.column !== column)
98        return { column, order: primary }
99    return sort.order === primary ? { column, order: reverse } : undefined
100}
101
102/*  order the criteria rows by the sort (stable, so equal rows keep their original order)  */
103const order = (rows: Matrix["rows"], sort: Sort | undefined): Matrix["rows"] => {
104    if (sort === undefined)
105        return rows
106    const sign = sort.order === "asc" ? 1 : -1
107    return [ ...rows ].sort((a, b) => sign * (sort.column === 0 ?
108        strip(a.cells[0]!).localeCompare(strip(b.cells[0]!)) :
109        a.values[sort.column - 1]! - b.values[sort.column - 1]!))
110}
111
112/*  the decision matrix: its state and its operations  */
113export const modEvaluate = () => {
114    /*  the last known width of the terminal and the sorts of the matrices  */
115    let columns = 80
116    const sorts = new Map<string, Sort>()
117
118    /*  sort the criteria rows of a matrix by a clicked header cell and redraw it  */
119    const press = (engine: Pick<Engine, "invalidate">, request: string, column: number) => () => {
120        const sort = advance(sorts.get(request), column)
121        if (sort !== undefined)
122            sorts.set(request, sort)
123        else
124            sorts.delete(request)
125        engine.invalidate()
126    }
127
128    /*  redraw a reply which contains a decision matrix (terminal only),
129        resp. draw nothing for any other reply  */
130    const render = (e: Frozen<MatchedEvent<"ui.render", { component: "AssistantMessage", surface: "terminal" }>>,
131        ui: Elements["terminal"], engine: Pick<Engine, "invalidate">): RenderElement | undefined => {
132        /*  act on decision matrices only  */
133        columns = e.viewport?.columns ?? columns
134        const matrix = parse(e.props.text)
135        if (matrix === undefined || matrix.before.length > LIMIT || matrix.after.length > LIMIT)
136            return undefined
137
138        /*  style the cells: the header ones in bold, the criteria rows in their sort
139            order, and the columns of the best alternatives in blue and bold  */
140        const sort = sorts.get(e.requestId)
141        const tint = (chars: Char[], column: number): Char[] =>
142            matrix.winners.has(column) ? chars.map((char) => ({ ...char, bold: true, color: WINNER })) : chars
143        const head = matrix.header.map((cell, c) => tint(style(`**${cell}**`, undefined), c))
144        const body = [ ...order(matrix.rows, sort).map((row) => row.cells), matrix.rating ]
145            .map((row) => row.map((cell, c) => tint(style(c === 0 ? strip(cell) : cell, undefined), c)))
146
147        /*  determine the column widths: the value columns at their natural width
148            (the header cells with room for the sort mark), the criteria column
149            within the remaining columns (gutter, grid lines, cell paddings, and a
150            spare column subtracted), else leave the matrix to the engine  */
151        const widths = head.map((cell, c) =>
152            Math.max(width(cell) + MARK.none.length, ...body.map((row) => width(row[c]!))))
153        const avail  = columns - 2 - (3 * head.length + 1) - 1 - widths.slice(1).reduce((sum, w) => sum + w, 0)
154        if (avail < Math.max(NARROW, width(head[0]!) + MARK.none.length))
155            return undefined
156        widths[0] = Math.min(widths[0]!, avail)
157
158        /*  resolve the UI elements  */
159        const { Box, Text, Button, Markdown } = ui
160
161        /*  pad the parts of a cell line of the given width to its column width:
162            left-aligned for the criteria, right-aligned for the values  */
163        const align = <T>(c: number, used: number, parts: T[]): (T | string)[] => {
164            const pad = " ".repeat(Math.max(0, widths[c]! - used))
165            return c === 0 ? [ ...parts, pad ] : [ pad, ...parts ]
166        }
167
168        /*  draw a header cell: its styled text inside a hover-scoping box, which while
169            hovered reveals a row of clickable plain buttons (one per styled run, as in
170            the grill table) on top of it, followed by its sort mark  */
171        const heading = (c: number): RenderElement[] => {
172            const group   = `h${c}`
173            const onPress = press(engine, e.requestId, c)
174            const buttons = split(head[c]!).map(({ text, bold }, r) =>
175                Button({ key: `${group}/${r}`, label: text, plain: true, onPress,
176                    hover: { scope: group, inverse: true, bold } }))
177            return align(c, width(head[c]!) + MARK.none.length, [
178                Box({ key: group, hover: { scope: group }, children: [
179                    Text({ children: paint(Text, head[c]!) }),
180                    Box({ position: "absolute", top: 0, left: 0, display: "none",
181                        hover: { scope: group, display: "flex" }, flexDirection: "row", children: buttons })
182                ] }),
183                Text({ children: sort?.column === c ? MARK[sort.order] : MARK.none })
184            ]).map((part) => typeof part === "string" ? Text({ children: part }) : part)
185        }
186
187        /*  draw a line of the grid out of the parts of its cells, resp. a rule  */
188        const draw = (parts: RenderElement[][]) => Box({ flexDirection: "row", children: [
189            Text({ children: "│ " }),
190            ...parts.flatMap((part, c) => c > 0 ? [ Text({ children: " │ " }), ...part ] : part),
191            Text({ children: " │" })
192        ] })
193        const rule = (l: string, m: string, r: string) =>
194            Text({ wrap: "truncate-end", children: l + widths.map((w) => "─".repeat(w + 2)).join(m) + r })
195
196        /*  draw the matrix as a grid: a rule below the header and above the rating
197            row, and the criteria wrapped within their column  */
198        const grid: RenderElement[] = [
199            rule("┌", "┬", "┐"),
200            draw(head.map((_, c) => heading(c))),
201            rule("├", "┼", "┤")
202        ]
203        body.forEach((row, k) => {
204            if (k === body.length - 1)
205                grid.push(rule("├", "┼", "┤"))
206            wrap(row[0]!, widths[0]!, INDENT).forEach((line, i) =>
207                grid.push(draw(row.map((cell, c) => {
208                    const chars = c === 0 ? line : i === 0 ? cell : []
209                    return [ Text({ children: align(c, width(chars), paint(Text, chars)) }) ]
210                }))))
211        })
212        grid.push(rule("└", "┴", "┘"))
213
214        /*  mimic the reply row of the engine: blank row above and bullet gutter  */
215        return Box({ flexDirection: "row", marginTop: 1, width: "100%", children: [
216            Box({ flexShrink: 0, minWidth: 2, children: Text({ children: e.props.isFirstOfReply ? "⏺" : " " }) }),
217            Box({ flexDirection: "column", flexGrow: 1, flexShrink: 1, children: [
218                ...(matrix.before !== "" ? [ Markdown({ text: matrix.before }) ] : []),
219                Box({ flexDirection: "column", marginTop: matrix.before !== "" ? 1 : 0, children: grid }),
220                ...(matrix.after !== "" ? [ Box({ marginTop: 1, children: Markdown({ text: matrix.after }) }) ] : [])
221            ] })
222        ] })
223    }
224
225    return { render }
226}
227
228
mods/ase-mods-help-find.ts 427 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Intent help, matching the still unsubmitted prompt, once suffixed with
9    a blank and "!!", as an intent against the help of all ASE skills (like
10    the skill "ase-help-intent", but over the session context), and showing
11    the proposed skills in a master/detail view in the band above the
12    prompt, where LEFT/RIGHT (or the wheel over the skills) selects a skill,
13    UP/DOWN and "b"/"f"/SPACE (or the wheel over the details) scroll its
14    details, RETURN picks its command into the prompt, and "!!", BACKSPACE, or
15    any other key restores the prompt as typed without the trigger.  */
16
17import type { Elements, Frozen, PromptBox, PromptEditInput, RenderElement } from "claude-code"
18import { type Engine, type Char, type BandRender, type BandScroll, type View, PICKED, CODE,
19    held, decode, section, wrap, uniform, flow, frame, layout, wheel, panel } from "./ase-mods-common.ts"
20
21/*  the trigger of an intent inside the prompt (suffixed with a blank and "!!",
22    so the doubled exclamation mark of a sentence is no trigger), the skill of
23    a proposed command (with or without its "ase:" plugin prefix), the maximum
24    number of command proposals, the help corpus of all skills (relative to
25    the plugin directory), and the fallback model without any session to fork  */
26const INTENT    = /\s+!!$/
27const SKILL     = /^\/?(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+)(?![\w-])/
28const PROPOSALS = 8
29const CORPUS    = "skills/ase-help-intent/data.md"
30const FALLBACK  = "sonnet"
31
32/*  the color of the box around (and of the rationale inside) the command and
33    rationale of a proposal, the title placed into the top edge of the frame,
34    and the share of the band columns taken by the master view  */
35const BOXED  = "blue"
36const TITLE  = "[ ⧉ ASE: Find Skill Command ]"
37const MASTER = 0.3
38
39/*  the frames of the spinner animating the status message while matching,
40    and the milliseconds between two frames  */
41const SPINNER = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
42const SPIN    = 100
43
44/*  the help of a single skill: its catalog entry and its entire manual page  */
45type Help = { catalog: string, manual: string }
46
47/*  a command proposal for an intent  */
48type Proposal = { skill: string, command: string, rationale: string }
49
50/*  an intent under matching: the scroll state of its band, the original prompt
51    (without the trigger and its blank, resp. without the trigger only), the
52    matching state, the status message,
53    the spinner frame, the command proposals, the selected proposal, and
54    the last key, if a "!" or "/"  */
55type Intent = View & {
56    draft:     string,
57    typed:     string,
58    state:     "busy" | "done" | "fail",
59    message:   string,
60    spin:      number,
61    proposals: Proposal[],
62    select:    number,
63    pending:   string
64}
65
66/*  parse the help corpus into the help of each skill, where
67    the catalog entry is the NAME, SYNOPSIS, DESCRIPTION, and SCENARIOS only  */
68const helps = (text: string): Map<string, Help> => {
69    const result = new Map<string, Help>()
70    for (const m of text.matchAll(/<purpose name="([^"]+)">\n([\s\S]*?)<\/purpose>/g)) {
71        const manual  = m[2]!.trim()
72        const catalog = manual.split(/^(?=## {2})/m)
73            .filter((part) => /^## {2}(?:NAME|SYNOPSIS|DESCRIPTION|SCENARIOS)\b/.test(part))
74            .join("").trim()
75        result.set(m[1]!, { catalog, manual })
76    }
77    return result
78}
79
80/*  extract the text out of a model reply (as the runtime result of a fork
81    or completion may deviate from its declared type, like a string, a result
82    object, an unanswered reply, or a refusal with a reason instead of null)  */
83const reply = (result: unknown): string | undefined => {
84    if (typeof result === "string")
85        return result
86    if (typeof result === "object" && result !== null) {
87        const r = result as { isAnswered?: boolean, text?: unknown }
88        if (r.isAnswered !== false && typeof r.text === "string")
89            return r.text
90    }
91    return undefined
92}
93
94/*  extract the JSON array out of a model reply (trying each opening bracket,
95    as any prose before the array may contain brackets, too)  */
96const array = (text: string | undefined): unknown[] | undefined => {
97    if (text === undefined)
98        return undefined
99    const j = text.lastIndexOf("]")
100    for (let i = text.indexOf("["); i !== -1 && i < j; i = text.indexOf("[", i + 1)) {
101        try {
102            const value: unknown = JSON.parse(text.slice(i, j + 1))
103            if (Array.isArray(value))
104                return value
105        }
106        catch {
107            /*  continue with the next opening bracket  */
108        }
109    }
110    return undefined
111}
112
113/*  the prompt for selecting the fitting skills out of the catalog  */
114const selection = (draft: string, catalog: string) => `
115Do *not* call any tools and do *not* perform the following intent!
116Instead, only *match* the following free-text intent, interpreted in the
117context of this session, against the following catalog of ASE skills:
118
119<intent>
120${draft}
121</intent>
122
123<catalog>
124${catalog}
125</catalog>
126
127Select *every* skill which adequately fits the intent -- judging the
128fit primarily by its SCENARIOS and DESCRIPTION, and secondarily by its
129NAME and SYNOPSIS -- ordered from best-fitting to worst-fitting, and
130keep at most the ${PROPOSALS} best ones. Reply with
131a JSON array of the skill names only (like \`[ "ase-code-lint" ]\`),
132resp. with an empty JSON array if no skill fits, and nothing else.
133`
134
135/*  the prompt for generating the commands out of the manual pages  */
136const generation = (draft: string, manuals: string) => `
137Do *not* call any tools and do *not* perform the following intent!
138Instead, only *generate* commands which realize the following free-text
139intent, interpreted in the context of this session, out of the
140following manual pages of ASE skills:
141
142<intent>
143${draft}
144</intent>
145
146<manuals>
147${manuals}
148</manuals>
149
150For each skill, in the given order, generate a concrete command which
151realizes the intent, with the option flags and positional arguments
152derived from its SYNOPSIS, OPTIONS, and ARGUMENTS, and their concrete
153values taken from the intent and the context of this session. Reply with
154a JSON array of objects \`{ "command": "/ase:<skill> <arguments>",
155"rationale": "<justification>" }\`, where the justification is a *very
156brief*, single-sentence explanation of why the skill and its arguments
157match the intent, and nothing else.
158`
159
160/*  determine the lines of the detail view of a proposal out of the manual page
161    of its skill: the command and rationale of the proposal (inside a box), and
162    the name, title, and description of its skill  */
163const details = (proposal: Proposal, manual: string, columns: number): Char[][] => {
164    const title = section(manual, "NAME").trim().replace(/^`[^`]*`\s+-\s+/, "")
165    const boxed = wrap(uniform(`❯ ${proposal.command}`, true, CODE), columns - 4, 2)
166    if (proposal.rationale !== "")
167        boxed.push(...wrap(uniform(`▷ Rationale: ${proposal.rationale}`, false, BOXED), columns - 4, 2))
168    const lines = frame(boxed, columns, BOXED)
169    lines.push([], ...wrap(uniform(title !== "" ? `${proposal.skill}: ${title}` : proposal.skill,
170        true, undefined), columns, 0))
171    const description = section(manual, "DESCRIPTION")
172    if (description.trim() !== "")
173        lines.push([], ...flow(description, columns))
174    return lines
175}
176
177/*  the intent help: its state and its operations  */
178export const modHelpFind = () => {
179    /*  the help of all skills (loaded on first use) and the currently shown intent  */
180    let corpus: Map<string, Help> | undefined
181    let intent: Intent | undefined
182
183    /*  determine whether the intent band is shown  */
184    const active = () => intent !== undefined
185
186    /*  close the intent band  */
187    const reset = () => {
188        intent = undefined
189    }
190
191    /*  close the intent band (as on a failure) and determine the prompt to
192        restore (the prompt as typed), if the band was shown  */
193    const cancel = (): string | undefined => {
194        const typed = intent?.typed
195        reset()
196        return typed
197    }
198
199    /*  while the intent band is shown, every edit is a key of the band (with the
200        prompt held): LEFT/RIGHT select a proposal, UP/DOWN scroll its details by
201        a line and "b"/"f"/SPACE by a page (as the engine consumes PAGEUP/PAGEDOWN),
202        RETURN (arriving as a typed newline in the held prompt) operates the band
203        as at the prompt, "//" (two "/" in a row) closes the band with the prompt
204        as typed suffixed with the trigger of the manpage browser (to switch over
205        to it), and "!!" (two "!" in a row), a deletion (like BACKSPACE), or any
206        other key closes the band and restores the prompt as typed without the
207        trigger (onto whose end the edit of a typed text is still to be applied)  */
208    const edit = (e: Frozen<PromptEditInput>): PromptBox | string => {
209        const current = intent!
210        const { draft, typed, state, proposals } = current
211        const key       = decode(e)
212        const pending   = current.pending
213        current.pending = /^[!/]$/.test(key.text) && key.text !== pending ? key.text : ""
214        if (current.pending !== "")
215            return held(draft)
216        if (key.text === "//" || (key.text === "/" && pending === "/")) {
217            reset()
218            const text = `${typed}//`
219            return { text, cursor: text.length }
220        }
221        if (key.name === "return") {
222            const text = submit()
223            return intent !== undefined ? held(draft) : { text, cursor: text.length }
224        }
225        const roll = key.name === "up" ? -1 : key.name === "down" ? 1 :
226            key.text === "b" ? -current.page : key.text === "f" || key.text === " " ? current.page : 0
227        const step = roll !== 0 ? 0 : key.step
228        if (state === "done" && (roll !== 0 || step !== 0)) {
229            if (step !== 0) {
230                current.select = Math.max(0, Math.min(proposals.length - 1, current.select + step))
231                current.scroll = 0
232            }
233            else
234                current.scroll = Math.max(0, current.scroll + roll)
235            return held(draft)
236        }
237        reset()
238        if (key.text === "" || key.text === "!!" || (key.text === "!" && pending === "!"))
239            return { text: typed, cursor: typed.length }
240        return typed
241    }
242
243    /*  stash the prompt as the intent, hold the prompt (so the keys of the
244        band arrive as edits), and match the intent in the background  */
245    const open = (box: PromptBox, engine: Pick<Engine, "invalidate" | "read" | "fork" | "complete" | "sleep">): PromptBox | undefined => {
246        const draft = box.text.replace(INTENT, "")
247        if (!INTENT.test(box.text) || draft.trim() === "")
248            return undefined
249        const current: Intent = { draft, typed: box.text.slice(0, -2), state: "busy",
250            message: "matching intent...", spin: 0, proposals: [],
251            select: 0, top: 0, scroll: 0, page: 1, split: 0, pending: "" }
252        intent = current
253
254        /*  update the intent, unless it was closed in the meantime  */
255        const settle = (state: Intent["state"], message: string, proposals: Proposal[] = []) => {
256            if (intent !== current)
257                return
258            Object.assign(current, { state, message, proposals })
259            engine.invalidate()
260        }
261
262        /*  ask the model for a stage over the transcript of the session (sharing its
263            prompt cache), or, as the fork yields no text on a cold snapshot or an API
264            error, without any session context (telling so in the status message)  */
265        const ask = async (prompt: string, stage: string): Promise<string | undefined> => {
266            settle("busy", `${stage}...`)
267            const forked = reply(await engine.fork(prompt))
268            if (forked !== undefined)
269                return forked
270            if (intent !== current)
271                return undefined
272            settle("busy", `${stage} (without session context)...`)
273            return reply(await engine.complete({ model: FALLBACK, prompt, maxTokens: 4096 }))
274        }
275
276        /*  match the intent in two stages: select the fitting skills out of
277            the catalog, then generate the commands out of their manual pages  */
278        const match = async () => {
279            const skills  = corpus ??= helps(await engine.read(CORPUS))
280            const catalog = [ ...skills ].map(([ name, help ]) =>
281                `<skill name="${name}">\n${help.catalog}\n</skill>`).join("\n")
282            const names = (array(await ask(selection(draft, catalog), "matching intent")) ?? [])
283                .filter((name, i, all): name is string =>
284                    typeof name === "string" && skills.has(name) && all.indexOf(name) === i)
285                .slice(0, PROPOSALS)
286            if (intent !== current)
287                return
288            if (names.length === 0) {
289                settle("fail", "no confident match for the intent -- please refine or clarify it")
290                return
291            }
292            const manuals = names.map((name) =>
293                `<skill name="${name}">\n${skills.get(name)!.manual}\n</skill>`).join("\n")
294            const proposals = (array(await ask(generation(draft, manuals), `generating commands for ${names.join(", ")}`)) ?? [])
295                .flatMap((item): Proposal[] => {
296                    const { command, rationale } = (item ?? {}) as { command?: unknown, rationale?: unknown }
297                    const text  = typeof command === "string" ? command.trim() : ""
298                    const skill = SKILL.exec(text)?.[1]
299                    if (skill === undefined || !skills.has(skill))
300                        return []
301                    return [ {
302                        skill,
303                        command:   text.replace(SKILL, "/ase:$1").replace(/\s+/g, " "),
304                        rationale: typeof rationale === "string" ? rationale.trim().replace(/\s+/g, " ") : ""
305                    } ]
306                })
307                .slice(0, PROPOSALS)
308
309            /*  without any generated command, still propose the bare commands of the selected skills  */
310            if (proposals.length === 0)
311                settle("done", "pick a command (without generated arguments)",
312                    names.map((skill) => ({ skill, command: `/ase:${skill}`, rationale: "" })))
313            else
314                settle("done", "pick a command", proposals)
315        }
316        match().catch((err: unknown) => {
317            settle("fail", `matching failed: ${err instanceof Error ? err.message : String(err)}`)
318        })
319
320        /*  animate the spinner while matching, unless the intent was closed in the meantime  */
321        const animate = async () => {
322            while (intent === current && current.state === "busy") {
323                await engine.sleep(SPIN)
324                current.spin = (current.spin + 1) % SPINNER.length
325                engine.invalidate()
326            }
327        }
328        animate().catch(() => {
329            /*  ignore a stopped animation, as the status message stays readable  */
330        })
331        return held(draft)
332    }
333
334    /*  operate the intent band by the wheel: over the master view step the
335        selection, over the detail view scroll it, resp. scroll it by a page
336        with the scroll keys (PAGEUP/PAGEDOWN) while the band is focused
337        (and tell whether the band took the scrolling)  */
338    const scroll = (e: BandScroll): boolean => {
339        if (intent === undefined || intent.state !== "done")
340            return false
341        const current = intent
342        wheel(e, current, (by) => {
343            const select = Math.max(0, Math.min(current.proposals.length - 1, current.select + by))
344            if (select !== current.select) {
345                current.select = select
346                current.scroll = 0
347            }
348        })
349        return true
350    }
351
352    /*  operate the intent band by RETURN at the prompt: pick the selected
353        proposal (closing the band), if any, resp. close a failed band, and
354        determine the prompt to refill (the held prompt while the band stays
355        shown, but without its space after the cursor, as the refill places
356        the cursor at its end)  */
357    const submit = (): string => {
358        const current  = intent!
359        const proposal = current.state === "done" ? current.proposals[current.select] : undefined
360        if (proposal !== undefined || current.state === "fail")
361            reset()
362        return proposal !== undefined ? `${proposal.command} ` :
363            intent !== undefined ? held(current.draft).text.trimEnd() : `${current.draft} `
364    }
365
366    /*  draw the intent into the band above the prompt (terminal only): a master view
367        of the proposed skills and a detail view of the selected one side by side  */
368    const render = (e: BandRender, ui: Elements["terminal"]): RenderElement | undefined => {
369        /*  yield to a survey and draw nothing without an intent  */
370        if (intent === undefined || e.props.hasSurvey)
371            return undefined
372        const current = intent
373        const { proposals } = current
374
375        /*  determine the geometry of the band (with the master view in a fixed ratio)
376            and the lines of the detail view: the command and rationale of the
377            selected proposal (inside a box), and the name, title, and description
378            of its skill  */
379        const { Text } = ui
380        const geometry = layout(e, MASTER)
381        const { span, body, master, detail } = geometry
382        const clip     = (text: string, n: number) =>
383            text.length > n ? `${text.slice(0, n - 1)}…` : text
384        const proposal = current.state === "done" ? proposals[current.select] : undefined
385        const lines    = proposal !== undefined ?
386            details(proposal, corpus?.get(proposal.skill)?.manual ?? "", detail) : undefined
387
388        /*  keep the selected proposal in the master view  */
389        current.top = Math.max(0, current.select - body + 1, Math.min(current.top, current.select))
390
391        /*  determine the rows of the status message (as long as no proposals exist):
392            a box of half the columns, centered vertically and horizontally  */
393        const hint: string[] = []
394        if (proposal === undefined) {
395            const size  = Math.max(12, Math.floor(span / 2))
396            const text  = current.state === "busy" ? `${SPINNER[current.spin]} ${current.message}` : current.message
397            const boxed = frame(wrap(uniform(text, false, undefined), size - 4, 0)
398                .slice(0, Math.max(1, body - 2)), size, undefined)
399            const pad   = " ".repeat(Math.max(0, Math.floor((span - size) / 2)))
400            hint.push(...Array.from({ length: Math.max(0, Math.floor((body - boxed.length) / 2)) }, () => " "),
401                ...boxed.map((line) => pad + line.map((char) => char.ch).join("")))
402        }
403
404        /*  draw the status message resp. both views (the master view with the
405            selected proposal in red, and the detail view), and the key hints
406            (the intent itself stays visible in the prompt)  */
407        return panel(ui, geometry, current, {
408            title: TITLE,
409            hints: current.state === "done" ? "⌫/!!: cancel+close · ⏎: apply+close · ←/→: select · b/f/SPACE: scroll" +
410                (geometry.overflow ? " · wheel: select/scroll" : "") + " · //: Browse Skill Manpages" :
411                "⌫/!!/any key: cancel+close · //: Browse Skill Manpages",
412            rows:  (i) => {
413                if (proposal === undefined)
414                    return Text({ dimColor: true, wrap: "truncate-end", children: hint[i] ?? " " })
415                const k = current.top + i
416                const p = proposals[k]
417                return p !== undefined ? Text({ color: k === current.select ? PICKED : undefined,
418                    children: clip(`${k === current.select ? "▶" : " "} ${p.skill}`, master) }) : undefined
419            },
420            lines
421        })
422    }
423
424    return { active, reset, cancel, edit, open, scroll, submit, render }
425}
426
427
mods/ase-mods-help-compose.ts 562 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Synopsis form, showing for a skill command (bare or with its options and
9    arguments already typed, which prefill the form), once suffixed with
10    "!!", the SYNOPSIS of its manual page as a form in a master/detail view
11    in the band above the prompt, where LEFT/RIGHT steps through its options
12    and arguments (and shows their descriptions, scrolled by "b"/"f"),
13    SPACE toggles them, RETURN edits their values (with a drop-down box for
14    fixed values), RETURN at the end (or "!!" outside a value) takes over
15    the composed command into the prompt, and BACKSPACE cancels.  */
16
17import type { Elements, Frozen, PromptBox, PromptEditInput, RenderElement } from "claude-code"
18import { type Engine, type Text, type Key, type BandRender, type BandScroll, type View, PICKED, COMMAND,
19    held, decode, section, wrap, uniform, flow, frame, paint, layout, wheel, panel } from "./ase-mods-common.ts"
20
21/*  the trigger of a synopsis form inside the prompt (a skill command suffixed
22    with "!!", and with its typed options and arguments, if any, separated by
23    a blank from it), the color of the drop-down box of a field with fixed
24    values, the title placed into the top edge of the frame, and the name of
25    the extra field with the typed words not recognized as of the synopsis  */
26const SYNOPSIS = /^(\/(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+))(?:\s+(\S(?:[^]*\S)?)\s+|\s*)!!$/
27const CHOICES  = "gray"
28const TITLE    = "[ ⧉ ASE: Compose Skill Command ]"
29const UNKNOWN  = "unrecognized"
30
31/*  a field of a synopsis form: an option (a flag or with a value) or an argument,
32    with its short option name, placeholder, fixed values, value suffix,
33    description, and state  */
34type Field = {
35    kind:     "option" | "argument",
36    name:     string,
37    short:    string,
38    label:    string,
39    choices:  string[],
40    list:     boolean,
41    valued:   boolean,
42    suffix:   string,
43    required: boolean,
44    help:     string,
45    enabled:  boolean,
46    value:    string
47}
48
49/*  a synopsis form: the scroll state of its band, the skill command, the prompt
50    to restore on cancel (the command as typed), its fields, the focused field
51    (the apply position after the last field), the state of an edited field,
52    the focus and editing state shown (resetting the scrolling on change) of
53    the detail view, and the last key outside a field, if a "!" or "/"  */
54type Form = View & {
55    command: string,
56    typed:   string,
57    fields:  Field[],
58    pos:     number,
59    edit:    boolean,
60    buffer:  string,
61    caret:   number,
62    choice:  number,
63    picked:  Set<string>,
64    anchor:  string,
65    pending: string
66}
67
68/*  extract the descriptions of the (usually bulleted) items of a manual page
69    section, keyed by every match of a global pattern in the head line of each item  */
70const descriptions = (text: string, key: RegExp): Map<string, string> => {
71    const result = new Map<string, string>()
72    for (const item of text.split(/^(?=(?:- {3})?[`*[])/m).filter((item) => /^(?:- {3})?[`*[]/.test(item))) {
73        const [ head, ...body ] = item.split("\n")
74        const help = `${head!.replace(/^- {3}/, "").replace(/:$/, "")}\n\n` +
75            body.map((line) => line.replace(/^ {4}/, "")).join("\n").trim()
76        for (const m of head!.matchAll(key))
77            if (!result.has(m[1]!))
78                result.set(m[1]!, help)
79    }
80    return result
81}
82
83/*  split an argument line of a synopsis into its top-level units  */
84const units = (line: string): string[] => {
85    const result: string[] = []
86    let unit  = ""
87    let depth = 0
88    for (const ch of line) {
89        if (ch === " " && depth === 0) {
90            if (unit !== "")
91                result.push(unit)
92            unit = ""
93        }
94        else {
95            depth += ch === "[" ? 1 : ch === "]" ? -1 : 0
96            unit  += ch
97        }
98    }
99    if (unit !== "")
100        result.push(unit)
101    return result
102}
103
104/*  parse the SYNOPSIS of a manual page into the fields of a synopsis form, where
105    the fields of all synopsis variants are merged (those of further variants and
106    of alternative groups as optional ones), the "--help" option is skipped, and
107    an option with fixed values initially has its first value  */
108const synopsis = (manual: string): Field[] => {
109    const opthelp = descriptions(section(manual, "OPTIONS"), /`(--[\w-]+)`/g)
110    const arghelp = descriptions(section(manual, "ARGUMENTS"), /\*([^*]+)\*/g)
111    const result: Field[] = []
112    let variants = 0
113    for (const line of section(manual, "SYNOPSIS").split("\n").map((line) => line.trim())) {
114        const heading = /^`ase-[a-z0-9]+-[a-z0-9]+`$/.test(line)
115        variants += heading ? 1 : 0
116        if (line === "" || heading)
117            continue
118        const group = /^\(.*\)$/.test(line)
119        const parts = group ? line.slice(1, -1).split(" | ") : line.includes("`--") ? [ line ] : units(line)
120        for (const part of parts) {
121            const required = !group && variants <= 1 && !part.startsWith("[")
122            const inner    = part.replace(/^\[(.*)\]$/, "$1")
123            const long     = /`(--[\w-]+)/.exec(inner)?.[1]
124            if (long !== undefined) {
125                if (long === "--help" || result.some((field) => field.name === long))
126                    continue
127                const short   = /`(-\w)[`=]/.exec(inner)?.[1] ?? ""
128                const rest    = inner.replace(/`-{1,2}[\w-]+(?:=[^`]*)?`/g, "").replace(/^[\s|]+/, "")
129                const preset  = /`-{1,2}[\w-]+=([^`]+)`/.exec(inner)?.[1]
130                const choices = [ ...rest.matchAll(/`([\w.-]+)`/g) ].map((m) => m[1]!)
131                const label   = choices.length > 0 ? choices.join("|") :
132                    (rest.replace(/[`*]/g, "").replace(/^[\s=]+/, "").trim() || (preset ?? ""))
133                result.push({ kind: "option", name: long, short, label, choices, list: rest.includes("..."),
134                    valued: label !== "", suffix: "", required, help: opthelp.get(long) ?? "",
135                    enabled: required, value: choices[0] ?? "" })
136            }
137            else {
138                const label = inner.replace(/[`*]/g, "")
139                if (result.some((field) => field.name === label))
140                    continue
141                const names = [ ...new Set([ ...inner.matchAll(/\*([^*]+)\*/g) ].map((m) => m[1]!)) ]
142                result.push({ kind: "argument", name: label, short: "", label, choices: [], list: inner.includes("..."),
143                    valued: true, suffix: /^\*[^*]+\*`:`$/.test(inner) ? ":" : "", required,
144                    help: names.flatMap((name) => arghelp.get(name) ?? []).join("\n\n"),
145                    enabled: required, value: "" })
146            }
147        }
148    }
149    return result
150}
151
152/*  a word of a command line: its verbatim range and its unquoted text  */
153type Word = { start: number, end: number, text: string }
154
155/*  split a command line into its words (honoring double quotes with
156    backslash escapes, single quotes, and backslash escapes)  */
157const tokenize = (line: string): Word[] =>
158    [ ...line.matchAll(/(?:"(?:\\[^]|[^"\\])*"?|'[^']*'?|\\[^]|[^\s"'\\])+/g) ].map((m) => ({
159        start: m.index,
160        end:   m.index + m[0].length,
161        text:  m[0].replace(/"((?:\\[^]|[^"\\])*)"?|'([^']*)'?|\\([^])/g,
162            (_: string, double: string | undefined, single: string | undefined, escaped: string | undefined) =>
163                double !== undefined ? double.replace(/\\([^])/g, "$1") : single ?? escaped ?? "")
164    }))
165
166/*  prefill the fields of a synopsis form out of the typed options and arguments
167    of its command, like the option parsing of the skills: the options up to the
168    first non-option word (or "--", kept verbatim), by long name, unambiguous long
169    name prefix, or short name, with their value after "=" or as the next word
170    (fixed values case-insensitively), and the remaining words, starting with the
171    first unrecognized option, if any, distributed over the argument fields (each
172    taking a word, a field with a suffix only a word with it, and the last field
173    the rest verbatim), resp., without any, kept in an extra field  */
174const prefill = (fields: Field[], line: string): void => {
175    const words   = tokenize(line)
176    const options = fields.filter((field) => field.kind === "option")
177    let i = 0
178    for (; i < words.length; i++) {
179        const word = words[i]!.text
180        if (word === "--" || !word.startsWith("-") || word === "-")
181            break
182        const m = /^(--[\w-]+|-\w)(?:=([^]*))?$/.exec(word)
183        if (m === null)
184            break
185        const name    = m[1]!
186        const matches = name.startsWith("--") ? options.filter((field) => field.name.startsWith(name)) : []
187        const field   = options.find((field) => field.name === name || field.short === name) ??
188            (matches.length === 1 ? matches[0] : undefined)
189        if (field === undefined)
190            break
191        const next = field.valued && m[2] === undefined
192        let value  = m[2] ?? (next ? words[i + 1]?.text : undefined)
193        if (field.valued !== (value !== undefined))
194            break
195        if (value !== undefined && field.choices.length > 0) {
196            const values = (field.list ? value.split(",") : [ value ]).map((value) =>
197                field.choices.find((choice) => choice.toLowerCase() === value.toLowerCase()))
198            if (values.some((value) => value === undefined))
199                break
200            value = values.join(",")
201        }
202        i += next ? 1 : 0
203        field.enabled = true
204        field.value   = value ?? ""
205    }
206    const rest   = i < words.length ? line.slice(words[i]!.start) : ""
207    const params = fields.filter((field) => field.kind === "argument")
208    if (rest !== "" && params.length === 0) {
209        fields.push({ kind: "argument", name: UNKNOWN, short: "", label: UNKNOWN, choices: [], list: false,
210            valued: true, suffix: "", required: false, enabled: true, value: rest,
211            help: "Words not recognized as options or arguments of the skill, kept verbatim." })
212        return
213    }
214    const items = tokenize(rest)
215    let k = 0
216    for (const [ j, field ] of params.entries()) {
217        const item = items[k]
218        if (item === undefined)
219            break
220        if (j === params.length - 1)
221            field.value = rest.slice(item.start)
222        else if (item.text.endsWith(field.suffix)) {
223            field.value = rest.slice(item.start, item.end)
224            k++
225        }
226        else
227            continue
228        field.enabled = true
229    }
230}
231
232/*  compose the command of a synopsis form out of its enabled fields
233    (double-quoting option values with whitespace or quotes, and omitting
234    valued options without a value yet)  */
235const compose = (form: Form): string => {
236    const words = [ form.command ]
237    for (const field of form.fields.filter((field) => field.enabled)) {
238        const value = field.value !== "" && !field.value.endsWith(field.suffix) ? field.value + field.suffix : field.value
239        if (field.kind === "option" && (!field.valued || value !== ""))
240            words.push(value === "" ? field.name : `${field.name} ` +
241                (/[\s"'\\]/.test(value) ? `"${value.replace(/(["\\])/g, "\\$1")}"` : value))
242        else if (value !== "")
243            words.push(value)
244    }
245    return words.join(" ")
246}
247
248/*  determine whether a field can be toggled: always, except for enabling
249    a field with a free-text value which has not received a value yet  */
250const togglable = (field: Field): boolean =>
251    field.enabled || !field.valued || field.choices.length > 0 || field.value !== ""
252
253/*  operate a synopsis form by a key: outside a field, step through the fields
254    (LEFT/RIGHT), toggle the focused one (SPACE, if togglable), enter its editing
255    (RETURN, except for a flag), apply the form (RETURN at the end), or cancel the
256    form (BACKSPACE); inside a field, choose a fixed value (LEFT/RIGHT/UP/DOWN or
257    its initial letter) and pick it for a list (SPACE), resp. edit the text,
258    and leave the field with (RETURN) or, for fixed values, without (BACKSPACE)
259    taking over the value  */
260const operate = (form: Form, key: Key): "apply" | "cancel" | undefined => {
261    const field = form.fields[form.pos]
262    if (key.name === "return") {
263        if (field === undefined)
264            return "apply"
265        if (form.edit) {
266            field.value = field.choices.length === 0 ? form.buffer.trim() :
267                field.list && form.picked.size > 0 ? field.choices.filter((choice) => form.picked.has(choice)).join(",") :
268                field.choices[form.choice]!
269            field.enabled = field.required || field.value !== ""
270            form.edit     = false
271        }
272        else if (field.valued) {
273            form.edit   = true
274            form.buffer = field.value
275            form.caret  = field.value.length
276            form.choice = Math.max(0, field.choices.indexOf(field.value))
277            form.picked = new Set(field.value.split(",").filter((value) => field.choices.includes(value)))
278        }
279    }
280    else if (!form.edit || field === undefined) {
281        if (key.step !== 0)
282            form.pos = Math.max(0, Math.min(form.fields.length, form.pos + key.step))
283        else if (key.text === " " && field !== undefined) {
284            if (togglable(field))
285                field.enabled = !field.enabled
286        }
287        else if (key.erase < 0)
288            return "cancel"
289    }
290    else if (field.choices.length > 0) {
291        const n = field.choices.length
292        if (key.step !== 0 || key.name === "up" || key.name === "down")
293            form.choice = (form.choice + n + (key.step < 0 || key.name === "up" ? -1 : 1)) % n
294        else if (key.text === " " && field.list) {
295            const choice = field.choices[form.choice]!
296            if (!form.picked.delete(choice))
297                form.picked.add(choice)
298        }
299        else if (key.erase < 0)
300            form.edit = false
301        else if (key.text.length === 1) {
302            const k = field.choices.findIndex((choice) => choice.toLowerCase().startsWith(key.text.toLowerCase()))
303            if (k !== -1)
304                form.choice = k
305        }
306    }
307    else {
308        const { buffer, caret } = form
309        if (key.step !== 0)
310            form.caret = Math.max(0, Math.min(buffer.length, caret + key.step))
311        else if (key.erase < 0 && caret > 0) {
312            form.buffer = buffer.slice(0, caret - 1) + buffer.slice(caret)
313            form.caret  = caret - 1
314        }
315        else if (key.erase > 0)
316            form.buffer = buffer.slice(0, caret) + buffer.slice(caret + 1)
317        else if (key.text !== "") {
318            const text  = key.text.replace(/\s+/g, " ")
319            form.buffer = buffer.slice(0, caret) + text + buffer.slice(caret)
320            form.caret  = caret + text.length
321        }
322    }
323    return undefined
324}
325
326/*  draw the underlined input box of a field: its text with the (inverted)
327    caret while being edited, its chosen fixed value(s) while being chosen,
328    its value, or its italic placeholder (in the color of the field, i.e.,
329    grey while disabled, bold while enabled, and red while focused)  */
330const input = (Text: Text, form: Form, field: Field,
331    look: { color?: string, dimColor: boolean, bold: boolean }, focus: boolean): RenderElement => {
332    const { buffer, caret, choice, picked } = form
333    const editing = focus && form.edit
334    if (editing && field.choices.length === 0)
335        return Text({ children: [
336            [ buffer.slice(0, caret), false ] as const,
337            [ buffer[caret] ?? " ", true ] as const,
338            [ buffer.slice(caret + 1), false ] as const
339        ].filter(([ text ]) => text !== "").map(([ text, inverse ]) =>
340            Text({ bold: look.bold, inverse, underline: true, children: text })) })
341    const value = !editing ? field.value :
342        field.list && picked.size > 0 ? field.choices.filter((choice) => picked.has(choice)).join(",") :
343        field.choices[choice]!
344    return value !== "" ?
345        Text({ ...look, underline: true, children: value }) :
346        Text({ ...look, underline: true, italic: true, children: field.label })
347}
348
349/*  draw a field of a synopsis form, as in the prompt: grey while disabled,
350    bold while enabled, and red (and marked by "▶") while focused, with options by their name
351    and, if valued, their input box, marked in front as a drop-down box (for
352    fixed values) resp. as a text field (for free-text values)  */
353const draw = (Text: Text, form: Form, field: Field, i: number): RenderElement => {
354    const focus = form.pos === i
355    const look  = { color: focus ? PICKED : undefined, dimColor: !field.enabled && !focus, bold: field.enabled }
356    const children: RenderElement[] = [ Text({ color: look.color, children: focus ? "▶ " : "  " }) ]
357    if (field.kind === "option")
358        children.push(Text({ ...look, children: field.name }))
359    if (field.kind === "option" && field.valued)
360        children.push(Text({ children: " " }))
361    if (field.valued)
362        children.push(Text({ color: look.color, dimColor: look.dimColor, children: field.choices.length > 0 ? "▾ " : "✎ " }),
363            input(Text, form, field, look, focus))
364    return Text({ wrap: "truncate-end", children })
365}
366
367/*  determine the key hints below the frame of a synopsis form (with the scroll
368    keys only while its detail view is scrollable, and the wheel only where the
369    band receives it)  */
370const hints = (form: Form, scrollable: boolean, wheel: boolean): string => {
371    const focused = form.fields[form.pos]
372    if (focused === undefined || !form.edit)
373        return `←/→${wheel ? "/wheel" : ""}: select` +
374            (focused?.valued === true ? " · ⏎: edit value" : "") +
375            ` · ⌫: cancel+close · ${focused === undefined ? "⏎/!!" : "!!"}: apply+close` +
376            " · //: Show Skill Manpage" +
377            (focused !== undefined && togglable(focused) ?
378                ` · SPACE: ${focused.enabled ? "deactivate" : "activate"}` : "") +
379            (scrollable ? ` · b/f${wheel ? "/wheel" : ""}: scroll bwd/fwd` : "")
380    return (focused.choices.length > 0 ? `⌫: abort · ⏎: accept · ←/→: choose${focused.list ? " · SPACE: pick" : ""}` :
381        "⏎: accept · ←/→: move · type the value") + (wheel && scrollable ? " · wheel: scroll" : "")
382}
383
384/*  the synopsis form: its state and its operations  */
385export const modHelpCompose = () => {
386    /*  the synopsis fields of the skills (loaded on first use, undefined
387        for a skill without a manual page) and the currently shown form  */
388    const synopses = new Map<string, Field[] | undefined>()
389    let form: Form | undefined
390
391    /*  determine whether the synopsis form is shown  */
392    const active = () => form !== undefined
393
394    /*  close the synopsis form  */
395    const reset = () => {
396        form = undefined
397    }
398
399    /*  close the synopsis form (as on a failure) and determine the prompt to
400        restore (the command as typed), if the form was shown  */
401    const cancel = (): string | undefined => {
402        const typed = form?.typed
403        reset()
404        return typed
405    }
406
407    /*  hold the prompt with the composed command while the synopsis form is shown  */
408    const hold = (current: Form): PromptBox => held(compose(current))
409
410    /*  while the synopsis form is shown, every edit is a key of the form, where
411        outside a field "b"/"f" scroll the detail view of the form by a page, "!!"
412        (two "!" in a row) applies the form (as RETURN at its end does), and "//"
413        (two "/" in a row) closes the form with the composed command suffixed
414        with the trigger of the manual band (to switch over to it)  */
415    const edit = (e: Frozen<PromptEditInput>): PromptBox => {
416        const current   = form!
417        const key       = decode(e)
418        const pending   = current.pending
419        const repeat    = current.edit ? "" :
420            /^([!/])\1$/.exec(key.text)?.[1] ?? (pending !== "" && key.text === pending ? pending : "")
421        current.pending = !current.edit && repeat === "" && /^[!/]$/.test(key.text) ? key.text : ""
422        if (current.pending !== "")
423            return hold(current)
424        if (!current.edit && (key.text === "b" || key.text === "f")) {
425            current.scroll = Math.max(0, current.scroll + (key.text === "b" ? -1 : 1) * current.page)
426            return hold(current)
427        }
428        if (repeat === "/") {
429            form = undefined
430            const text = `${compose(current)} //`
431            return { text, cursor: text.length }
432        }
433        const result = repeat === "!" ? "apply" : operate(current, key)
434        if (result !== undefined) {
435            form = undefined
436            const text = result === "apply" ? `${compose(current)} ` : current.typed
437            return { text, cursor: text.length }
438        }
439        return hold(current)
440    }
441
442    /*  for a skill command with a manual page, once suffixed with the trigger,
443        show its synopsis form, prefilled with the typed options and arguments
444        (and hold the prompt)  */
445    const open = async (box: PromptBox, engine: Pick<Engine, "read">): Promise<PromptBox | undefined> => {
446        const command = SYNOPSIS.exec(box.text)
447        if (command === null)
448            return undefined
449        const skill = command[2]!
450        if (!synopses.has(skill)) {
451            const manual = await engine.read(`skills/${skill}/help.md`).catch(() => undefined)
452            synopses.set(skill, manual !== undefined ? synopsis(manual) : undefined)
453        }
454        const fields = synopses.get(skill)
455        if (fields === undefined)
456            return undefined
457        const args   = command[3] ?? ""
458        const filled = fields.map((field) => ({ ...field }))
459        prefill(filled, args)
460        form = { command: command[1]!, typed: `${command[1]!} ${args !== "" ? `${args} ` : ""}`, fields: filled,
461            pos: 0, edit: false, buffer: "", caret: 0, choice: 0, picked: new Set(),
462            top: 0, scroll: 0, page: 1, anchor: "", split: 0, pending: "" }
463        return hold(form)
464    }
465
466    /*  operate the synopsis form by the wheel: over the master view step its
467        focused field, over the detail view scroll it, resp. scroll it by a page
468        with the scroll keys (PAGEUP/PAGEDOWN) while the band is focused
469        (and tell whether the form took the scrolling)  */
470    const scroll = (e: BandScroll): boolean => {
471        if (form === undefined)
472            return false
473        const current = form
474        wheel(e, current, current.edit ? undefined : (by) =>
475            operate(current, { name: "", text: "", step: by, erase: 0 }))
476        return true
477    }
478
479    /*  operate the synopsis form by RETURN at the prompt (closing the form
480        once applied or cancelled) and determine the prompt to refill (the held
481        prompt while the form stays shown, but without its space after the
482        cursor, else with a single trailing space only, as the refill places
483        the cursor at its end)  */
484    const submit = (): string => {
485        const current = form!
486        const result  = operate(current, { name: "return", text: "", step: 0, erase: 0 })
487        if (result !== undefined)
488            form = undefined
489        return form !== undefined ? hold(current).text.trimEnd() : `${compose(current)} `
490    }
491
492    /*  draw the synopsis form into the band above the prompt (terminal only)  */
493    const render = (e: BandRender, ui: Elements["terminal"]): RenderElement | undefined => {
494        /*  yield to a survey and draw nothing without a synopsis form  */
495        if (form === undefined || e.props.hasSurvey)
496            return undefined
497        const current = form
498        const focused = current.fields[current.pos]
499        const editing = focused !== undefined && current.edit
500
501        /*  determine the geometry of the band (with master and detail view of equal widths)  */
502        const { Text } = ui
503        const geometry = layout(e, 0.5)
504        const { body, detail } = geometry
505
506        /*  determine the lines of the master view (the command after the prompt
507            marker, colored as in the prompt, and indented below it each field on
508            its own line and the apply position), with the drop-down box of a field
509            with fixed values while being chosen directly below the field (aligned
510            with its input box), and the line of the focused field  */
511        const entries: RenderElement[] = [
512            Text({ wrap: "truncate-end", children: [ "❯ ",
513                Text({ color: COMMAND, children: current.command }) ] }),
514            ...current.fields.map((field, i) => draw(Text, current, field, i)),
515            Text({ bold: true, color: focused === undefined ? PICKED : undefined,
516                children: focused === undefined ? "▶ ⏎" : "  ⏎" })
517        ]
518        const row = current.pos + 1
519        let popup = 0
520        if (editing && focused.choices.length > 0) {
521            const items = focused.choices.map((choice) =>
522                focused.list ? `${current.picked.has(choice) ? "☑" : "☐"} ${choice}` : choice)
523            const indent = 2 + (focused.kind === "option" ? focused.name.length + 1 : 0) + 2
524            const box    = frame(items.map((item, k) => uniform(item, false, k === current.choice ? PICKED : undefined)),
525                Math.max(...items.map((item) => item.length)) + 4, CHOICES)
526            popup = box.length
527            entries.splice(row + 1, 0, ...box.map((line) =>
528                Text({ wrap: "truncate-end", children: [ " ".repeat(indent), ...paint(Text, line) ] })))
529        }
530
531        /*  determine the lines of the detail view: the description of the focused
532            field (resp. the hint of the apply position, dimmed as the key hints)  */
533        const lines = focused === undefined ?
534            wrap(uniform("Take over the composed command into the prompt.", false, undefined), detail, 0) :
535            flow(focused.help !== "" ? focused.help : `*${focused.label}*`, detail)
536
537        /*  reset the scroll position of the detail view once the focused field or its
538            editing changes, and keep the focused field and, if possible, its drop-down
539            box in the master view  */
540        const anchor = `${current.pos}/${current.edit}`
541        if (current.anchor !== anchor) {
542            current.anchor = anchor
543            current.scroll = 0
544        }
545        current.top = Math.max(0, Math.min(row,
546            Math.max(Math.min(current.top, row), row + popup - body + 1)))
547
548        /*  draw both views (the master view with the synopsis, and the detail
549            view), and the key hints  */
550        return panel(ui, geometry, current, {
551            title: TITLE,
552            hints: hints(current, lines.length > body, geometry.overflow),
553            rows:  (i) => entries[current.top + i],
554            lines,
555            dim:   focused === undefined
556        })
557    }
558
559    return { active, reset, cancel, edit, open, scroll, submit, render }
560}
561
562
mods/ase-mods-help-show.ts 143 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Manual band, toggling for a skill command (bare or with its options and
9    arguments already typed), once suffixed with a blank and "//", the entire
10    manual page of the skill in the band above the prompt (scrolled by the
11    wheel), while the "//" is removed again from the prompt, so the command
12    can be typed on, and the band also closes once the prompt no longer starts
13    with the skill command, the synopsis form opens, or the prompt is
14    submitted.  */
15
16import type { Elements, PromptBox, RenderElement } from "claude-code"
17import { type Engine, type Char, type BandRender, type BandScroll, type View,
18    uniform, flow, layout, wheel, panel } from "./ase-mods-common.ts"
19
20/*  the trigger of a manual band inside the prompt (a skill command suffixed
21    with a blank and "//", with its typed options and arguments, if any,
22    separated by a blank from it), the skill command at the start of the prompt,
23    the share of the terminal height taken by the band outside fullscreen, the
24    indentation of the section bodies, and the title placed into the top edge
25    of the band  */
26const MANUAL  = /^\/(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+)(?:\s[^]*)?\s\/\/$/
27const COMMAND = /^\/(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+)(?![\w-])/
28const HEIGHT  = 0.5
29const INDENT  = 2
30const TITLE   = "[ ⧉ ASE: Show Skill Manpage ]"
31
32/*  a manual band: the scroll state of its frame, the skill, its manual page,
33    and the manual page lines with the columns they were wrapped to  */
34type Manual = View & {
35    skill:   string,
36    manual:  string,
37    lines:   Char[][],
38    columns: number
39}
40
41/*  convert a manual page into lines of styled characters, hard-wrapped to the
42    given columns: each section with its heading in bold and its body indented
43    (with the lines of the SYNOPSIS kept apart, as in the manual page)  */
44export const page = (manual: string, columns: number): Char[][] => {
45    const lines: Char[][] = []
46    for (const part of manual.split(/^(?=## {2})/m).filter((part) => part.startsWith("##  "))) {
47        const [ head, ...body ] = part.split("\n")
48        const name = head!.replace(/^## {2}/, "").trim()
49        const text = name === "SYNOPSIS" ?
50            body.filter((line) => line.trim() !== "").flatMap((line) => flow(line, columns - INDENT, true)) :
51            flow(body.join("\n"), columns - INDENT, true)
52        if (lines.length > 0)
53            lines.push([])
54        lines.push(uniform(name, true, undefined),
55            ...text.map((line) => line.length > 0 ? [ ...uniform(" ".repeat(INDENT), false, undefined), ...line ] : line))
56    }
57    return lines
58}
59
60/*  the manual band: its state and its operations  */
61export const modHelpShow = () => {
62    /*  the manual pages of the skills (loaded on first use, undefined
63        for a skill without a manual page) and the currently shown band  */
64    const manuals = new Map<string, string | undefined>()
65    let shown: Manual | undefined
66
67    /*  determine whether the manual band is shown  */
68    const active = () => shown !== undefined
69
70    /*  close the manual band  */
71    const reset = () => {
72        shown = undefined
73    }
74
75    /*  determine the manual page lines of the manual band, wrapped to the given columns  */
76    const wrapped = (current: Manual, columns: number): Char[][] => {
77        if (current.columns !== columns) {
78            current.lines   = page(current.manual, columns)
79            current.columns = columns
80        }
81        return current.lines
82    }
83
84    /*  show the manual band of a skill with a manual page (loaded on first use),
85        and tell whether it is shown  */
86    const show = async (skill: string, engine: Pick<Engine, "read">): Promise<boolean> => {
87        if (!manuals.has(skill))
88            manuals.set(skill, await engine.read(`skills/${skill}/help.md`).catch(() => undefined))
89        const manual = manuals.get(skill)
90        if (manual === undefined)
91            return false
92        shown = { skill, manual, lines: [], columns: 0, top: 0, scroll: 0, page: 1, split: 0 }
93        return true
94    }
95
96    /*  for a skill command with a manual page, once suffixed with the trigger,
97        toggle its manual band (closing it, if already shown for the skill, else
98        showing it) and remove the trigger from the prompt again  */
99    const toggle = async (box: PromptBox, engine: Pick<Engine, "read">): Promise<PromptBox | undefined> => {
100        const command = MANUAL.exec(box.text)
101        if (command === null)
102            return undefined
103        if (shown?.skill === command[1])
104            shown = undefined
105        else if (!await show(command[1]!, engine))
106            return undefined
107        const text = box.text.slice(0, -2)
108        return { text, cursor: text.length }
109    }
110
111    /*  track the prompt and close the manual band once the prompt no longer
112        starts with its skill command  */
113    const track = (text: string): void => {
114        if (shown !== undefined && COMMAND.exec(text)?.[1] !== shown.skill)
115            shown = undefined
116    }
117
118    /*  scroll the manual page in the band by the wheel
119        (and tell whether the band took the scrolling)  */
120    const scroll = (e: BandScroll): boolean => {
121        if (shown === undefined)
122            return false
123        wheel(e, shown)
124        return true
125    }
126
127    /*  draw the manual page into the band above the prompt (terminal only),
128        yielding to a survey  */
129    const render = (e: BandRender, ui: Elements["terminal"]): RenderElement | undefined => {
130        if (shown === undefined || e.props.hasSurvey)
131            return undefined
132        const geometry = layout(e, 0, HEIGHT)
133        return panel(ui, geometry, shown, {
134            title: TITLE,
135            hints: (geometry.overflow ? "wheel or CTRL+x + TAB + ↑/↓/PgUp/PgDn: scroll · " : "") +
136                "//: close · !!: Compose Skill Command · (keep typing the command)",
137            lines: wrapped(shown, geometry.span - 3)
138        })
139    }
140
141    return { active, reset, toggle, track, scroll, render }
142}
143
mods/ase-mods-help-browse.ts 406 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Manpage browser, showing for a prompt of just "//", or of a free text
9    suffixed with a blank and "//", the manual pages of all ASE skills in a
10    master/detail view in the band above the prompt, filtered by a filter
11    field (initially the free text) with a fuzzy search (like "ase man"),
12    where typed text edits the filter, LEFT/RIGHT (or the wheel over the
13    skills) selects a skill, UP/DOWN (or the wheel over the manual page)
14    scroll its manual page (with the matches of the filter marked), RETURN
15    takes over its command into the prompt, "!!" switches over to the
16    intent help for the filter, and "//" leaves the filter in the prompt
17    (which mirrors the filter while the browser is shown).  */
18
19import type { Elements, Frozen, PromptBox, PromptEditInput, RenderElement } from "claude-code"
20import { type Engine, type Char, type BandRender, type BandScroll, type View, PICKED,
21    held, decode, uniform, wrap, layout, wheel, panel } from "./ase-mods-common.ts"
22import { page } from "./ase-mods-help-show.ts"
23
24/*  the trigger of a manpage browser inside the prompt (just "//", or a free text
25    suffixed with a blank and "//"), the skill directories (relative to the plugin
26    directory), the title placed into the top edge of the frame, and the share of
27    the band columns taken by the master view  */
28const BROWSE = /^(?:([^]*\S)\s+)?\/\/$/
29const SKILLS = "skills"
30const TITLE  = "[ ⧉ ASE: Browse Skill Manpages ]"
31const MASTER = 0.3
32
33/*  the manual page of a skill: its name, its Markdown source, and the lower-cased
34    Markdown source and its words (for searching)  */
35type Doc = { skill: string, manual: string, text: string, words: Set<string> }
36
37/*  a manpage browser: the scroll state of its band, the filter, the selected
38    manual page (by its index into the matching ones), the last key, if a "/"
39    or "!", and the selection and filter shown (resetting the scrolling on
40    change) of the detail view  */
41type Browse = View & {
42    filter:  string,
43    select:  number,
44    pending: string,
45    anchor:  string
46}
47
48/*  the minimum length of a word for its fuzzy matching, the Levenshtein edit
49    distance, and the Sorensen-Dice bigram similarity coefficient of two words
50    (copies of "fuzzyMin", "levenshtein", and "diceCoefficient" of
51    "tool/src/ase-task-board-filter.ts", so keep them in sync)  */
52const fuzzyMin = 4
53const levenshtein = (a: string, b: string): number => {
54    let prev = [] as number[]
55    let curr = [] as number[]
56    for (let j = 0; j <= b.length; j++)
57        prev[j] = j
58    for (let i = 1; i <= a.length; i++) {
59        curr[0] = i
60        for (let j = 1; j <= b.length; j++)
61            curr[j] = Math.min(prev[j]! + 1, curr[j - 1]! + 1,
62                prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1))
63        const swap = prev
64        prev = curr
65        curr = swap
66    }
67    return prev[b.length]!
68}
69const diceCoefficient = (a: string, b: string): number => {
70    if (a === b)
71        return 1
72    if (a.length < 2 || b.length < 2)
73        return 0
74    const bigrams = new Map<string, number>()
75    for (let i = 0; i < a.length - 1; i++) {
76        const bigram = a.substring(i, i + 2)
77        bigrams.set(bigram, (bigrams.get(bigram) ?? 0) + 1)
78    }
79    let hits = 0
80    for (let i = 0; i < b.length - 1; i++) {
81        const bigram = b.substring(i, i + 2)
82        const count  = bigrams.get(bigram) ?? 0
83        if (count > 0) {
84            bigrams.set(bigram, count - 1)
85            hits++
86        }
87    }
88    return (2 * hits) / (a.length + b.length - 2)
89}
90
91/*  escape a string for its literal use within a regular expression  */
92const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
93
94/*  the regular expression of the matches of a search in a page: the keywords as
95    plain substrings, plus the fuzzy variants of the page as whole words, with the
96    longest alternative first, so a variant is never cut short by a keyword nested
97    inside it (a copy of "matchRE" of "tool/src/ase-man-catalog.ts", so keep it in sync)  */
98const matchRE = (keywords: string[], variants: string[]): RegExp => {
99    const alts = keywords.map((k) => ({ len: k.length, src: escape(k) }))
100        .concat(variants.map((w) => ({ len: w.length, src: "(?<![a-z0-9])" + escape(w) + "(?![a-z0-9])" })))
101    alts.sort((a, b) => b.len - a.len)
102    return new RegExp(alts.map((a) => a.src).join("|"), "gi")
103}
104
105/*  search all pages for a query (like "ase man"): all whitespace-separated keywords
106    have to occur in a page (AND logic), in up to two passes, the keywords as literal
107    substrings first and, only if this matches no page at all, as fuzzy variants of
108    their words; the result maps the skills of the matching pages onto the regular
109    expressions of their matches, or is null for a query without any keywords (a copy
110    of "searchPages" of "tool/src/ase-man-catalog.ts", so keep it in sync)  */
111const search = (docs: Doc[], vocab: Set<string>, query: string): Map<string, RegExp> | null => {
112    const keywords = query.toLowerCase().split(/\s+/).filter((word) => word !== "")
113    if (keywords.length === 0)
114        return null
115    const hits = new Map<string, RegExp>()
116    for (const doc of docs)
117        if (keywords.every((k) => doc.text.includes(k)))
118            hits.set(doc.skill, matchRE(keywords, []))
119    if (hits.size > 0)
120        return hits
121
122    /*  the fuzzy-equivalent vocabulary words of a keyword, cached per keyword  */
123    const fuzzy = new Map<string, string[]>()
124    const fuzzyWords = (word: string): string[] => {
125        let result = fuzzy.get(word)
126        if (result === undefined) {
127            result = word.length < fuzzyMin ? [] : [ ...vocab ].filter((given) =>
128                Math.abs(word.length - given.length) <= 1
129                && (diceCoefficient(word, given) >= 0.50 || levenshtein(word, given) <= 2))
130            fuzzy.set(word, result)
131        }
132        return result
133    }
134
135    /*  the regular expression of the fuzzy variants of a compound keyword (like
136        "ase-task-edit"), with each of its words literally or fuzzily replaced
137        and its separators kept, cached per keyword (null for a single word)  */
138    const compound = new Map<string, RegExp | null>()
139    const compoundRE = (keyword: string): RegExp | null => {
140        let result = compound.get(keyword)
141        if (result === undefined) {
142            const parts = keyword.split(/([^a-z0-9]+)/)
143            result = parts.length < 2 ? null : new RegExp("(?<![a-z0-9])" + parts.map((part, i) =>
144                i % 2 === 1 ? escape(part) : part === "" ? "" :
145                    "(?:" + [ part, ...fuzzyWords(part) ].map(escape).join("|") + ")").join("") + "(?![a-z0-9])", "g")
146            compound.set(keyword, result)
147        }
148        return result
149    }
150    for (const doc of docs) {
151        const variants = [] as string[]
152        const hit = keywords.every((k) => {
153            if (doc.text.includes(k))
154                return true
155            const re   = compoundRE(k)
156            const near = re !== null ? [ ...new Set([ ...doc.text.matchAll(re) ].map((m) => m[0])) ] :
157                fuzzyWords(k).filter((w) => doc.words.has(w))
158            variants.push(...near)
159            return near.length > 0
160        })
161        if (hit)
162            hits.set(doc.skill, matchRE(keywords, variants))
163    }
164    return hits
165}
166
167/*  mark the matches of a (global) regular expression within a line of styled
168    characters (in bold and the color of a picked item)  */
169const mark = (line: Char[], re: RegExp): Char[] => {
170    const text = line.map((char) => char.ch).join("")
171    const hits = new Set<number>()
172    for (const m of text.matchAll(re))
173        for (let i = m.index; i < m.index + m[0].length; i++)
174            hits.add(i)
175    if (hits.size === 0)
176        return line
177    let pos = 0
178    return line.map((char) => {
179        const hit = hits.has(pos)
180        pos += char.ch.length
181        return hit ? { ...char, bold: true, color: PICKED } : char
182    })
183}
184
185/*  the manpage browser: its state and its operations  */
186export const modHelpBrowse = () => {
187    /*  the manual pages of all skills and their vocabulary (loaded on first use),
188        and the currently shown browser  */
189    let docs:  Doc[] | undefined
190    let vocab: Set<string> = new Set()
191    let browse: Browse | undefined
192
193    /*  determine whether the manpage browser is shown  */
194    const active = () => browse !== undefined
195
196    /*  close the manpage browser  */
197    const reset = () => {
198        browse = undefined
199    }
200
201    /*  determine the prompt to leave on closing the manpage browser: its filter
202        (with a single trailing blank to type on), if any  */
203    const leave = (current: Browse): string =>
204        current.filter.trim() !== "" ? `${current.filter.trimEnd()} ` : ""
205
206    /*  close the manpage browser (as on a failure) and determine the prompt to
207        restore (the filter), if it was shown  */
208    const cancel = (): string | undefined => {
209        const text = browse !== undefined ? leave(browse) : undefined
210        reset()
211        return text
212    }
213
214    /*  determine the matching manual pages of the filter (all of them for an empty
215        filter), with the regular expressions of their matches, cached per filter
216        (and manual pages)  */
217    let cache: { filter: string, docs: Doc[] | undefined, list: { doc: Doc, re: RegExp | undefined }[] } | undefined
218    const matching = (current: Browse): { doc: Doc, re: RegExp | undefined }[] => {
219        if (cache?.filter !== current.filter || cache.docs !== docs) {
220            const hits = search(docs ?? [], vocab, current.filter)
221            cache = { filter: current.filter, docs, list: (docs ?? []).filter((doc) => hits === null || hits.has(doc.skill))
222                .map((doc) => ({ doc, re: hits?.get(doc.skill) })) }
223        }
224        return cache.list
225    }
226
227    /*  hold the prompt as the current filter while the browser is shown  */
228    const hold = (current: Browse): PromptBox => held(current.filter.trimEnd())
229
230    /*  take over the command of the selected manual page into the prompt (closing
231        the browser), if any page matches, and determine the prompt to show  */
232    const take = (current: Browse): PromptBox => {
233        const doc = matching(current)[current.select]?.doc
234        if (doc === undefined)
235            return hold(current)
236        reset()
237        const text = `/${doc.skill} `
238        return { text, cursor: text.length }
239    }
240
241    /*  while the manpage browser is shown, every edit is a key of the browser:
242        LEFT/RIGHT select a manual page, UP/DOWN scroll it by a line, RETURN takes
243        over the command of the selected page, "//" (two "/" in a row) closes the
244        browser and leaves the filter in the prompt, "!!" (two "!"
245        in a row, for a non-empty filter) closes the browser with the filter suffixed
246        with the trigger of the intent help (to switch over to it), a deletion (like
247        BACKSPACE) deletes the last character of the filter, and any other typed
248        text is appended to the filter  */
249    const edit = (e: Frozen<PromptEditInput>): PromptBox => {
250        const current   = browse!
251        const key       = decode(e)
252        const pending   = current.pending
253        current.pending = (key.text === "/" || (key.text === "!" && current.filter.trim() !== "")) &&
254            key.text !== pending ? key.text : ""
255        if (current.pending !== "") {
256            if (pending !== "") {
257                current.filter += pending
258                current.select = 0
259            }
260            return hold(current)
261        }
262        if (key.text === "//" || (key.text === "/" && pending === "/")) {
263            reset()
264            const text = leave(current)
265            return { text, cursor: text.length }
266        }
267        if (current.filter.trim() !== "" && (key.text === "!!" || (key.text === "!" && pending === "!"))) {
268            reset()
269            const text = `${current.filter.trim()} !!`
270            return { text, cursor: text.length }
271        }
272        current.filter += pending
273        if (key.name === "return")
274            return take(current)
275        if (key.name === "up" || key.name === "down")
276            current.scroll = Math.max(0, current.scroll + (key.name === "up" ? -1 : 1))
277        else if (key.step !== 0) {
278            current.select = Math.max(0, Math.min(matching(current).length - 1, current.select + key.step))
279            current.scroll = 0
280        }
281        else if (key.erase < 0)
282            current.filter = current.filter.slice(0, -1)
283        else if (key.text !== "")
284            current.filter += key.text.replace(/\s+/g, " ")
285        if (pending !== "" || key.erase < 0 || key.text !== "")
286            current.select = 0
287        return hold(current)
288    }
289
290    /*  for a prompt of just the trigger, or of a free text suffixed with it, show
291        the manpage browser with the free text as its filter (and hold the prompt)  */
292    const open = async (box: PromptBox, engine: Pick<Engine, "read" | "dirs">): Promise<PromptBox | undefined> => {
293        const m = BROWSE.exec(box.text)
294        if (m === null)
295            return undefined
296        if (docs === undefined) {
297            const skills = (await engine.dirs(SKILLS)).filter((name) => /^ase-[a-z0-9]+-[a-z0-9]+$/.test(name)).sort()
298            const loaded = await Promise.all(skills.map(async (skill) => {
299                const manual = await engine.read(`${SKILLS}/${skill}/help.md`).catch(() => undefined)
300                if (manual === undefined)
301                    return []
302                const text = manual.toLowerCase()
303                return [ { skill, manual, text, words: new Set(text.split(/[^a-z0-9]+/).filter((w) => w !== "")) } ]
304            }))
305            docs  = loaded.flat()
306            vocab = new Set(docs.flatMap((doc) => [ ...doc.words ]))
307        }
308        browse = { filter: m[1] ?? "", select: 0, pending: "", anchor: "",
309            top: 0, scroll: 0, page: 1, split: 0 }
310        return hold(browse)
311    }
312
313    /*  operate the manpage browser by the wheel: over the master view select a
314        manual page, over the detail view scroll it, resp. scroll it by a page with
315        the scroll keys (PAGEUP/PAGEDOWN) while the band is focused (and tell
316        whether the browser took the scrolling)  */
317    const scroll = (e: BandScroll): boolean => {
318        if (browse === undefined)
319            return false
320        const current = browse
321        wheel(e, current, (by) => {
322            const select = Math.max(0, Math.min(matching(current).length - 1, current.select + by))
323            if (select !== current.select) {
324                current.select = select
325                current.scroll = 0
326            }
327        })
328        return true
329    }
330
331    /*  operate the manpage browser by RETURN at the prompt and determine the
332        prompt to refill (the held prompt while the browser stays shown, but
333        without its space after the cursor, else the taken over command)  */
334    const submit = (): string => {
335        const box = take(browse!)
336        return browse !== undefined ? box.text.trimEnd() : box.text
337    }
338
339    /*  draw the manpage browser into the band above the prompt (terminal only)  */
340    const render = (e: BandRender, ui: Elements["terminal"]): RenderElement | undefined => {
341        /*  yield to a survey and draw nothing without a browser  */
342        if (browse === undefined || e.props.hasSurvey)
343            return undefined
344        const current = browse
345        const { Text } = ui
346
347        /*  determine the geometry of the band and the matching manual pages
348            (with the selection clamped onto them)  */
349        const geometry = layout(e, MASTER)
350        const { body, detail } = geometry
351        const list = matching(current)
352        current.select = Math.max(0, Math.min(list.length - 1, current.select))
353        const selected = list[current.select]
354
355        /*  determine the lines of the detail view: the manual page of the selected
356            skill with the matches of the filter marked  */
357        const lines = selected === undefined ?
358            wrap(uniform("No manual page matches the filter.", false, undefined), detail, 0) :
359            page(selected.doc.manual, detail).map((line) => selected.re !== undefined ? mark(line, selected.re) : line)
360
361        /*  reset the scroll position of the detail view once the selection or the
362            filter changes, and keep the selected manual page in the master view
363            (below the filter field and its horizontal line)  */
364        const anchor = `${current.select}/${current.filter}`
365        if (current.anchor !== anchor) {
366            current.anchor = anchor
367            current.scroll = 0
368        }
369        const rows = Math.max(1, body - 2)
370        current.top = Math.max(0, Math.min(current.select, Math.max(current.top, current.select - rows + 1)))
371
372        /*  determine the lines of the master view: the filter field (with its caret,
373            resp. its placeholder), a horizontal line (joining the borders), and the
374            matching manual pages (the selected one in red)  */
375        const field = Text({ wrap: "truncate-start", children: [ "❯ ",
376            ...(current.filter !== "" ? [ Text({ bold: true, children: current.filter }) ] : []),
377            Text({ inverse: true, children: " " }),
378            ...(current.filter === "" ? [ Text({ dimColor: true, italic: true, children: " filter…" }) ] : []) ] })
379        const entry = (k: number) => {
380            const item = list[k]
381            if (item === undefined)
382                return undefined
383            const picked = k === current.select
384            return Text({ wrap: "truncate-end", bold: picked, color: picked ? PICKED : undefined,
385                children: `${picked ? "▶" : " "} ${item.doc.skill}` })
386        }
387
388        /*  draw both views (with the count of the matching manual pages in the
389            bottom edge) and the key hints  */
390        const wheeled = geometry.overflow ? "/wheel" : ""
391        return panel(ui, geometry, current, {
392            title:  TITLE,
393            status: `[ ${list.length}/${docs?.length ?? 0} manpages ]`,
394            hints:  `←/→${wheeled}: select · ` +
395                `${geometry.overflow ? "wheel or CTRL+x + TAB + ↑/↓/PgUp/PgDn" : "↑/↓"}: scroll · ` +
396                "//: cancel+close · ⏎: apply+close" +
397                (current.filter.trim() !== "" ? " · !!: Find Skill Command" : "") + " · (type for filtering)",
398            rows:   (i) => i === 0 ? field : entry(current.top + i - 2),
399            rule:   (i) => i === 1,
400            lines
401        })
402    }
403
404    return { active, reset, cancel, edit, open, scroll, submit, render }
405}
406
mods/ase-mods-help-hint.ts 135 lines
1/*
2**  Agentic Software Engineering (ASE)
3**  Copyright (c) 2025-2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
4**  Licensed under Apache 2.0 <https://spdx.org/licenses/Apache-2.0>
5*/
6
7/*  Claude Code function hooks module ("mod", EARLY ACCESS):
8    Hint band, showing for a skill command (bare or with its options and
9    arguments already typed) the entire argument hint of the skill, wrapped
10    over multiple lines, in the band above the prompt (instead of the one-line
11    and hence usually truncated argument hint of the engine), together with
12    the hint on the manual band and the synopsis form, while the prompt starts
13    with the skill command followed by a blank (so the typeahead of the engine
14    is closed), until the prompt is submitted.  */
15
16import type { Elements, RenderElement } from "claude-code"
17import { type Engine, type Char, type BandRender, type View, COMMAND,
18    wrap, uniform, layout, panel } from "./ase-mods-common.ts"
19
20/*  the skill command (followed by a blank) at the start of the prompt, the
21    argument hint in the frontmatter of a skill, its groups (the bracketed
22    resp. parenthesized options and arguments, with one level of nesting, and
23    the other words), the non-breaking space keeping a group on a single line,
24    the colors of its syntax characters and of its references, the indentation
25    of the continuation lines, and the title placed into the top edge of the band  */
26const SKILL  = /^\/(?:ase:)?(ase-[a-z0-9]+-[a-z0-9]+)(?=\s)/
27const HINT   = /^argument-hint:\s*"(.*)"\s*$/m
28const GROUP  = /\[(?:[^[\]]|\[[^\]]*\])*\]|\((?:[^()]|\([^)]*\))*\)|\S+/g
29const NBSP   = String.fromCodePoint(0xA0)
30const SYNTAX = "gray"
31const REFER  = "red"
32const INDENT = 4
33const TITLE  = "[ ⧉ ASE: Show Skill Synopsis ]"
34
35/*  a hint band: the scroll state of its frame, the skill command as typed,
36    the argument hint of its skill, and the lines with the columns they were
37    wrapped to  */
38type Hint = View & {
39    command: string,
40    hint:    string,
41    lines:   Char[][],
42    columns: number
43}
44
45/*  convert an argument hint into styled characters: the syntax characters
46    of its optional groups, plain groups, and alternatives in grey and its "<...>" references in red  */
47const tint = (text: string): Char[] => {
48    const chars: Char[] = []
49    let reference = false
50    for (const ch of text) {
51        if (ch === "<")
52            reference = true
53        chars.push({ ch, bold: false, color: reference ? REFER : "[()|]".includes(ch) ? SYNTAX : undefined })
54        if (ch === ">")
55            reference = false
56    }
57    return chars
58}
59
60/*  the hint band: its state and its operations  */
61export const modHelpHint = () => {
62    /*  the argument hints of the skills (loaded on first use, undefined
63        for an unknown skill), the currently shown band, and the generation
64        of the latest tracking resp. closing (discarding any older tracking)  */
65    const hints = new Map<string, string | undefined>()
66    let shown: Hint | undefined
67    let generation = 0
68
69    /*  close the hint band  */
70    const reset = () => {
71        generation++
72        shown = undefined
73    }
74
75    /*  determine the argument hint of a skill (loaded on first use)  */
76    const synopsis = async (skill: string, engine: Pick<Engine, "read">): Promise<string | undefined> => {
77        if (!hints.has(skill))
78            hints.set(skill, await engine.read(`skills/${skill}/SKILL.md`)
79                .then((text) => HINT.exec(text)?.[1]).catch(() => undefined))
80        return hints.get(skill)
81    }
82
83    /*  determine the lines of the hint band, wrapped to the given columns: the
84        skill command after the prompt marker and in the prompt color, followed by the tinted groups of the
85        argument hint, each kept on a single line (if it fits)  */
86    const wrapped = (current: Hint, columns: number): Char[][] => {
87        if (current.columns !== columns) {
88            const groups = (current.hint.match(GROUP) ?? []).map((group) =>
89                group.length <= columns - INDENT ? group.replaceAll(" ", NBSP) : group)
90            current.lines   = wrap([ ...uniform("❯ ", false, undefined), ...uniform(current.command, false, COMMAND),
91                ...tint(` ${groups.join(" ")}`) ], columns, INDENT)
92            current.columns = columns
93        }
94        return current.lines
95    }
96
97    /*  track the prompt and show the hint band while the prompt starts with the
98        command of a skill with an argument hint and a blank, else close it
99        (and tell whether the band changed)  */
100    const track = async (text: string, engine: Pick<Engine, "read">): Promise<boolean> => {
101        const prior   = shown
102        const current = ++generation
103        const command = SKILL.exec(text)
104        if (command === null)
105            shown = undefined
106        else if (shown?.command !== command[0]) {
107            const hint = await synopsis(command[1]!, engine)
108            if (current !== generation)
109                return false
110            shown = hint !== undefined ? { command: command[0], hint, lines: [], columns: 0,
111                top: 0, scroll: 0, page: 1, split: 0 } : undefined
112        }
113        return shown !== prior
114    }
115
116    /*  draw the argument hint into the band above the prompt (terminal only),
117        with the band exactly as tall as the hint (as it always fits, without
118        a scroll position), yielding to a survey  */
119    const render = (e: BandRender, ui: Elements["terminal"]): RenderElement | undefined => {
120        if (shown === undefined || e.props.hasSurvey)
121            return undefined
122        const geometry = layout(e, 0)
123        const lines    = wrapped(shown, geometry.span - 3)
124        return panel(ui, { ...geometry, body: lines.length, overflow: false }, shown, {
125            title: TITLE,
126            hints: "//: Show Skill Manpage · !!: Compose Skill Command · (keep typing the command)",
127            lines,
128            fit:   true
129        })
130    }
131
132    return { reset, synopsis, track, render }
133}
134
135