SLOPSHOPPER

kodflow-ktn

ktn-linter's findings beside the prompt, as a mod (function hooks, Claude Code 2.1.299 or later). It completes the hooks ktn-linter installs and replaces none…

panebandcommandtoaststatusprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · kodflow-ktn
│ ┃ ktn-view ✕ › fix the failing auth test and add an audit log call │ ┃ ktn · inactif │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ kodflow-ktn: Claude Code 2.1.299 ou plus requis

Draws

Pane · ktn-view
ktn · inactif
README

kodflow-ktn

ktn-linter, seen from inside Claude Code: a mod (function hooks) that tells whether the session is in a Go project and, from there, shows what the ktn-linter daemon knows about it.

It completes ktn-linter's hooks and replaces none. The command hooks that ktn-linter installs keep delivering the findings to the model through the daemon's socket, everywhere — Kepler, claude -p and the Agent SDK included. This mod registers no tool hook: it can neither block nor rewrite a call, and if it does not load, nothing the model receives changes.

It needs Claude Code 2.1.299 or later (the oldest version measured by the spike of kodflow/ktn-linter#774; CI pins 2.1.301). Below that it shows one status line and does nothing else.

Install

/plugin install kodflow-ktn@kodflow

claude plugin disable kodflow-ktn@kodflow turns it off without touching the rest; the hooks go on as before.

Where it is active

Only where something draws — the terminal. In a -p run, under the Agent SDK and in Kepler's launch mode $.session.surfaces() is empty: the mod is inert there, with no probe and no daemon call.

Only in a Go project, decided by the same predicate as ktn-linter's own resolver (daemonaddr.ResolveProject): walking up from the session's root to the nearest .git (a folder, or a file in a linked worktree), a regular go.mod or go.work on the way makes it Go; crossing a vendor/ folder discards what was found below it; a go.mod above the repository does not count. A repository whose modules all sit in subfolders is not Go from its root — open the session in the module, or set activation: always.

The probe is bounded by what the spike measured: at most three listings and 250 ms, upward only (nothing below the root is read, so no link is ever followed). A walk cut short says undetermined, which is drawn as inactive, never guessed.

activationEffect
auto (default)active in a Go project only
alwaysactive everywhere — the net for an undetermined probe
offnever active

The verdict is reconciled at one point only: the end of each main-loop turn, and the SessionStart hook after a /clear, /resume or fork. That catches a /cd, a worktree switch, a go mod init, and a $.state that came back empty.

Command

/ktn-view — /ktn belongs to kodflow-devops. It answers from what the mod already holds and never waits on the daemon (a command that waits holds the prompt for up to 30 s); it sends a refresh in the background.

/ktn-view filtre error,warning shows those severities only (sent as severity=, the daemon filters and counts); /ktn-view filtre shows them all again. A word that is not error, warning or info is said and ignored.

The daemon

The mod reads the per-user daemon of ktn-linter (KTN_USER_DAEMON=1, kodflow/ktn-linter#757) and nothing else. It finds it through endpoint.json alone, the pointer ktn-linter writes under HOME (~/.local/state/ktn-linter/, macOS ~/Library/Application Support/ktn-linter/): the socket path is never computed on this side, and state.json is not a source (a clean stop removes it, which is exactly when the launch button is needed). It then asks GET /status once per pointer (the protocol it speaks, the workspaces waiting for approval) and GET /api/view for the workspace, over the socket.

Every known failure ends in a drawn state, never in silence:

StateWhenOffered
out of a Go projectthe probe said sonothing at all
loadingno answer yet—
unreachableno endpoint.json, nothing on the socket, a daemon silent past the request's wait + 5 s, an answer too big or unreadablethe launch button, or the command to run
incompatibleanother protocol than v1nothing: no further call until endpoint.json changes
pending approvalthe daemon waits for the personthe daemon's exact ktn-linter admin workspace approve …
refused / not servedthe daemon's reason—
clean / findingsservedthe counts on the status line

A request refused before it left (an organization's web-fetch policy, a hook) is a state of its own, never "unreachable", and offers no launch.

One request at a time, tied to the underlying fetch: $.http.fetch has a fixed 30 s deadline and no signal, so the mod races its own (the request's wait + 5 s), draws "unreachable" when it fires, sends nothing more until the first request has settled, and drops its late answer. Five failures in a row hold the turn's refresh back (3 s doubling to 60 s); the person's own act — the command, a press — passes it. No timer exists while no pane is placed: the status line is refreshed at the end of each turn, with wait=0.

The launch button is a convenience, not the guarantee — the hooks and the MCP shim start the daemon. It runs <exe> daemon ensure with the absolute binary endpoint.json names (never a name looked up in PATH), from /, with KTN_USER_DAEMON=1, then watches the socket every 500 ms for 10 s: a zero exit proves a request, not a daemon. Two presses run one command. On failure it shows the exit code and the first 300 characters of stderr. Where the session has no host commands, the command is shown to copy instead.

Every string from the daemon is cleaned of control characters before it is drawn, by a plain loop: no regular expression runs on external data.

The pane

/ktn-view opens it in a Go project (/ktn-view off closes it); out of one the command answers and opens nothing. At the top, the synthesis: the state, the workspace, the totals by severity and by phase, how long since the last answer, the launch button when the daemon is down. Below, the findings as a collapsible tree, the way the daemon serves it: directories folded with their counts, only the children of the ones opened. A press on a directory or a file opens or folds it (the key of each row is the model's stable dir: / file: id, never a line or a counter); the opened ids live in $.state and come back after a hot reload. A press on a finding shows its detail above the tree — rule, severity, phase, file:line in a Code block, the message — and a second press, or Fermer le détail, hides it.

Scrolling (scrolling, kodflow/ktn-linter#787):

  • window (default): the mod windows the tree. The daemon serves 180 nodes from an offset (offset= / limit=); the snapshot kept in $.state is cut at 70 000 characters, since it is read again on every render, so on every wheel tick. The render stays pure: it draws the rows of ITS body (scroll.bodyRows less the head) from one offset, which it re-clamps to those rows. One pane is evaluated per surface with its own rows, and ui.scroll carries neither the surface nor the other surface's rows, so the offset is one value for the instance: a surface draws at a time. The head says lignes a–b sur N. ui.scroll moves the offset by by, clamped with the snapshot's total (never contentRows, which counts only the rows drawn), and keeps the engine's own window at the top; one spare row below the body leaves the engine a row to scroll, so it raises ui.scroll for the wheel and the arrows. Within 20 rows of either end of what is held, the next window, centred on what is looked at, is asked for on the clock, detached: a hook never waits on the daemon. A row not held yet draws as …. Windowing on e.viewport was set aside: it does not reflect the pane's body.
  • native: the way back to #777 — the engine scrolls the whole tree the daemon serves, and a window that stops short says "… N de plus, voir l'UI web".

Either way the drawing stops its rows below the engine's 100 000 characters.

While the pane is placed, and only then, one timer exists: a chain of one-shot timers, 3 s apart, each long-polling the daemon (wait=20, raced at 25 s). Closed, nothing is left armed. A press may send one request beside a long-poll that waits on a daemon that answers; the long-poll's answer, about a tree nobody looks at any more, is dropped.

Ouvrir l'UI web mints a bootstrap link over the socket (POST /ui/boot, same uid) on the press, never before. The daemon grants only read-only view sessions. The token is held in a module variable and drawn in the pane's Link alone: never in $.state, which every plugin can read, never in the command's text, which the model reads. The link's label is the URL without its fragment.

autoOpen is off by default, as kodflow/ktn-linter#774 recommended: the engine seats a pane nobody asked for only from 144 columns, and once you have opened it with /ktn-view it seats it again from 110, in every later session.

autoOpenEffect
false (default)the pane opens on /ktn-view
truethe pane opens when a Go session starts

What it looks like

tmux capture-pane of a terminal at 144 columns, fullscreen layout, against a test daemon (KTN_USER_DAEMON=1, private HOME and XDG_*), the pane opened by /ktn-view and three folders opened from the keyboard (the scratch path shortened, three of the six findings shown):

│ktn · 6 constats · 0 E · 2 W · 4 I
│…/scratchpad/kws
│phases 2:1 5:1 6:2 7:2
│actualisé il y a 0 s · moteur init
│http://127.0.0.1:8080/
│▾ .  6 · 2W 4I
│  ▾ pkg/  6 · 2W 4I
│    ▾ api/  6 · 2W 4I
│      ▾ handler.go  6 · 2W 4I
│        L1 KTN-SC-ST1000 at least one file in a package should…
│        L5 KTN-FUNC-MAXPARAM function 'Serve' has 7 parameters…
│        L6 KTN-VAR-USEANY prefer any to interface{}

Under the prompt: ⚠ kodflow-ktn: 6 constats · 0 E · 2 W · 4 I. The daemon stopped, the band above the prompt shows the button:

ktn · daemon injoignable — aucun daemon sur le socket
[ Lancer le daemon ]

A workspace waiting for approval, at 110 columns:

ktn · en attente d'approbation — repository not approved                  [-]
à lancer dans votre propre terminal :
ktn-linter admin workspace approve "/…/scratchpad/kws2"

One predicate, one table — and the view model

tests/fixtures/resolve-project.json is ktn-linter's golden table for the resolver (pkg/daemonaddr/project_roots_external_test.go), transcribed row for row at the commit its provenance.sha names, and checked against the Go resolver at that commit before it was committed. The pure tests replay every row; changing an expected value fails them, as it fails the Go test. To move the pin: copy the table again from the new commit, re-run the Go resolver on each tree, then update KTN_LINTER_SHA in hooks/mod/contract.ts.

tests/fixtures/view/ holds ktn-linter's golden view models (pkg/view/testdata/golden), byte for byte at the commit SOURCE names. The pure tests read every one back whole, check that the expansions the mod sends are the golden queries' own, and draw them under the 100 000-character limit. ktn-linter is private, so a public CI cannot read the pinned commit: CI holds only the pin (SOURCE's sha is KTN_LINTER_SHA), and scripts/sync-ktn-fixtures.sh --check is the maintainer's byte-for-byte check through gh (without an argument it rewrites the copies from the pin).

Tests and CI

make mod-check        # all of it, as CI runs it (from the repository root)
make mod-pure         # pure modules under node --test, no engine
make mod-engine       # claude plugin test, behind its precondition

Node 22.18 or later runs the TypeScript as it is. No npm dependency.

The lanes (kodflow/ktn-linter#788), none of which can redden ktn-linter's release — the plugin is published here, by commit or by its own kodflow-ktn/v* tags (kodflow-ktn-release.yml, gated on make mod-check):

  • mod-ktn in ci.yml, blocking. The pure modules first, before the engine is installed, so their verdict stands whatever happens to it; then make mod-check on Claude Code pinned by CLAUDE_CODE_VERSION, bumped by hand: the validator (one session.start, no tool hook, and the surface — the events hooked and the $ calls made — equal to tests/fixtures/surface.json), then claude plugin test.
  • The precondition. claude plugin test exits 1 when hooks modules are turned off on the machine (a remote switch, disableAllHooks). The engine is first asked about a probe mod with one passing test (scripts/mod-lane/probe): "turned off" there ends the lane neutral with a ::warning::, never red; any other failure of the probe stays red.
  • mod-latest.yml, advisory. Daily and on demand, never on a push or a pull request, in no needs: the latest Claude Code against the committed surface, the validator's findings and the engine suite's verdict, kept in one rolling issue labelled mod-latest (two runs on the same gap write nothing; a run with no gap closes it).
  • make ci-gates-check reads the workflows as YAML: mod-check is run by a blocking job of ci.yml, every make target a workflow runs exists, the advisory workflow stays off push and pull requests and out of every needs, actions/setup-node is pinned by a 40-character sha. make mod-lane-check tests all of the above against a fake engine and a fake gh.

A change to the surface (a new event, a new $ call) rewrites tests/fixtures/surface.json in the same change: python3 scripts/mod-surface.py surface <claude plugin validate --json report>.

Source 10 files
hooks/mod/register.ts 481 lines
1// register.ts — kodflow-ktn's function hooks: the one module that touches `$`.
2//
3// The mod COMPLETES ktn-linter's hooks and replaces none (decision of
4// 2026-10-14, kodflow/ktn-linter#774): the command hooks keep delivering the
5// findings to the model through the daemon's socket, everywhere, Kepler
6// included. So nothing here hooks a tool call (no `tool.call`, no
7// `classic.PreToolUse` / `PostToolUse`): CI asserts it on the validator's
8// report.
9//
10// Every hook is registered unconditionally and is inert until the session
11// proves to be a Go project:
12//   - nothing draws in a `-p` run, the Agent SDK or Kepler's launch mode
13//     (`$.session.surfaces()` empty, #774): the mod stays inert there;
14//   - under the version floor it says so once and does nothing else;
15//   - `session.start` registers the command and hands the probe to the
16//     background: it never waits on it, and it never calls the daemon;
17//   - the ONE reconciliation point is `turn.complete` of the main loop and
18//     `classic.SessionStart` after a /clear, /resume or fork: the root moved
19//     (`/cd`, a worktree), a folder gained its go.mod, `$.state` came back
20//     empty, a timer a hook refused — each is caught there and nowhere else.
21//
22// The daemon is reached through client.ts (pure, port-injected) and drawn by
23// view.ts (pure): what is here is the port and the wiring.
24//
25// The pane (#777) is opened by /ktn-view, or at the start with `autoOpen`
26// (off by default: the engine seats an unasked pane only from 144 columns,
27// and once the person has opened it, it seats it again from 110, session
28// after session — measured by #774). While it is placed, and only then, a
29// tick long-polls the daemon; closed, no timer is left.
30//
31// The tree is windowed by the mod (#787, `scrolling: window`, the default):
32// the daemon serves WINDOW_ROWS nodes from an offset, `$.state` keeps that
33// snapshot under WINDOW_MAX_CHARS, the render stays pure and draws the rows
34// of ITS body from ONE offset it re-clamps, and `ui.scroll` moves that offset
35// with the snapshot's total — asking for the next window, detached, near an
36// edge. `scrolling: native` is the way back to #777's native scrolling.
37
38import type { Register } from "claude-code";
39import type { KtnActivation, KtnDaemon, KtnModel, KtnSnap, KtnTree } from "../../types";
40import { Client, type Port, type UiLink } from "./client.ts";
41import {
42  COMMAND,
43  MIN_ENGINE,
44  PANE_ID,
45  PROBE_MAX_CALLS,
46  PROBE_MAX_MS,
47  SEVERITIES,
48} from "./contract.ts";
49import { atLeast } from "./engine.ts";
50import {
51  parseActivation,
52  resolveProject,
53  verdictOf,
54  workspaceRoot,
55  worthReprobing,
56  type Activation,
57  type Resolution,
58} from "./project.ts";
59import { band, capWindow, nextWindow, pane, safe, scrolled, stateLine, statusText } from "./view.ts";
60
61const SNAP = { plugin: "kodflow-ktn", key: "snap" } as const;
62const TREE = { plugin: "kodflow-ktn", key: "tree" } as const;
63const EXPANDED = { plugin: "kodflow-ktn", key: "expanded" } as const;
64const OFFSET = { plugin: "kodflow-ktn", key: "offset" } as const;
65const FILTER = { plugin: "kodflow-ktn", key: "filter" } as const;
66
67// The module's own copy: the fast source. A reload starts it over, and the
68// next reconciliation rebuilds it from the disk; `$.state` keeps what is drawn.
69let snap: KtnSnap = { activation: "probing" };
70let resolution: Resolution | undefined;
71let probing = false;
72let started = false;
73let activation: Activation = "auto";
74let client: Client | undefined;
75let lastStatus: string | undefined;
76let autoOpen = false;
77/** The dir: and file: ids opened in the pane. */
78let expanded: string[] = [];
79/**
80 * The web UI's bootstrap link. Held HERE and drawn in the pane's tree alone:
81 * never in `$.state`, which any plugin reads, never in the command's text,
82 * which the model reads.
83 */
84let uiLink: UiLink | undefined;
85/** `window` (the mod windows the tree, #787) or `native` (#777, the rollback). */
86let scrolling: "window" | "native" = "window";
87/** The windowed pane's first row; `$.state` holds the copy every surface reads. */
88let offset = 0;
89/** Rows the last windowed render gave its head, so a scroll clamps to the tree's rows. */
90let headRows = 0;
91/** The snapshot last written, for the scroll's edge check without a read. */
92let heldTree: KtnTree | undefined;
93/** The severities shown, empty for all. */
94let filter: string[] = [];
95/** The finding whose detail the pane shows. */
96let detail: string | undefined;
97
98// $.state takes JSON data: no undefined anywhere in it
99const plain = <T>(v: T): T => JSON.parse(JSON.stringify(v));
100
101/** Writes a transition twice: the module's variable, then `$.state`. */
102async function publish($: any, next: KtnSnap): Promise<void> {
103  snap = plain(next);
104  await $.state.set(SNAP, snap).catch(() => undefined);
105}
106
107/** The status line, written only when its text changes. */
108function status($: any): void {
109  const text = statusText(snap);
110  if (text === lastStatus) return;
111  lastStatus = text;
112  $.ui.status(text);
113}
114
115const isLive = (a: KtnActivation) => a !== "inert" && a !== "floor";
116
117/** Leaving a Go project: no timer, no request, nothing on screen. */
118function standDown($: any): void {
119  client?.stop();
120  lastStatus = undefined;
121  uiLink = undefined;
122  $.ui.status(undefined);
123  void $.ui.close({ id: PANE_ID }).catch(() => undefined);
124}
125
126/** Whether this mod's pane is placed now, by the engine's own record. */
127async function placed($: any): Promise<boolean> {
128  const panes = await $.ui.panes().catch(() => []);
129  return panes.some((p: any) => p.id === PANE_ID && p.isPlaced);
130}
131
132/** Opens the pane and starts the tick when the surface placed it. */
133async function openPane($: any): Promise<boolean> {
134  const r = await $.ui.open({ id: PANE_ID, title: "ktn" }).catch(() => undefined);
135  const isPlaced = r?.isPlaced === true;
136  if (isPlaced) client?.setTicking(true);
137  return isPlaced;
138}
139
140async function writeTree($: any, model: KtnModel): Promise<void> {
141  const nodes = scrolling === "window" ? capWindow(model.nodes) : model.nodes;
142  const tree: KtnTree = {
143    workspace: snap.workspace ?? "",
144    nodes,
145    truncated: model.truncated || nodes.length < model.nodes.length,
146    hidden: model.hidden,
147  };
148  if (scrolling === "window") {
149    tree.from = model.from;
150    tree.total = model.total;
151  }
152  heldTree = tree;
153  await $.state.set(TREE, plain(tree)).catch(() => undefined);
154}
155
156/** The windowed pane's offset, written where every surface reads it. */
157async function setOffset($: any, next: number): Promise<void> {
158  offset = next;
159  await $.state.set(OFFSET, next).catch(() => undefined);
160}
161
162/** A press on a finding: its detail, or none when it is the one shown. */
163function inspect($: any, id: string): void {
164  detail = detail === id ? undefined : id;
165  $.ui.invalidate("ui.render");
166}
167
168/** `/ktn-view filtre error,warning`: the severities shown, none for all. */
169async function setFilter($: any, words: string): Promise<string> {
170  const asked = words.split(/[\s,]+/).filter(Boolean);
171  const known = asked.filter((w) => (SEVERITIES as readonly string[]).includes(w));
172  filter = [...new Set(known)];
173  detail = undefined;
174  await $.state.set(FILTER, filter).catch(() => undefined);
175  await setOffset($, 0);
176  client?.setFilter(filter);
177  client?.nudge();
178  const left = asked.filter((w) => !known.includes(w));
179  const said = filter.length ? `ktn: filtre ${filter.join(", ")}` : "ktn: filtre retiré";
180  return left.length ? `${said} (ignoré : ${left.join(", ")} ; attendu : ${SEVERITIES.join(", ")})` : said;
181}
182
183/** A press on a directory or a file of the tree: open it, or fold it. */
184async function toggle($: any, id: string): Promise<void> {
185  if (!client) return;
186  expanded = expanded.includes(id) ? expanded.filter((x) => x !== id) : [...expanded, id];
187  await $.state.set(EXPANDED, expanded).catch(() => undefined);
188  client.setExpand(expanded);
189  client.nudge();
190}
191
192/** "Ouvrir l'UI web": a fresh link, kept in the module, drawn in the pane. */
193async function openUi($: any): Promise<void> {
194  if (!client) return;
195  const r = await client.mint();
196  if ("error" in r) {
197    $.ui.toast(`ktn: UI web indisponible (${r.error})`);
198    return;
199  }
200  uiLink = r;
201  $.ui.invalidate("ui.render");
202}
203
204/** The engine, as client.ts sees it. */
205function portOf($: any, canRun: boolean): Port {
206  return {
207    now: () => $.clock.now(),
208    after: (ms, fn) => $.clock.after(ms, fn),
209    read: (path) => $.fs.read(path),
210    home: () => $.env.get("HOME"),
211    fetch: (url, init) => $.http.fetch(url, init),
212    run: canRun ? (argv, init) => $.process.run(argv, init) : undefined,
213    emit: (daemon: KtnDaemon, model: KtnModel | undefined) => {
214      if (snap.activation !== "active") return;
215      void publish($, { ...snap, daemon }).then(() => status($));
216      if (model) void writeTree($, model);
217    },
218  };
219}
220
221/**
222 * The activation probe: at most three listings and 250 ms, walked up from
223 * the session's root (never `repo().root`, which names the MAIN working tree
224 * of a linked worktree and would turn every Kepler worktree off).
225 */
226async function probe($: any): Promise<void> {
227  if (probing) return;
228  probing = true;
229  try {
230    const root: string = await $.session.root();
231    const t0: number = await $.clock.now();
232    const r = await resolveProject(root, (dir) => $.fs.list(dir), {
233      maxCalls: PROBE_MAX_CALLS,
234      expired: async () => (await $.clock.now()) - t0 > PROBE_MAX_MS,
235    });
236    resolution = r;
237    const verdict = verdictOf(r, activation);
238    const was = snap.activation;
239    if (verdict !== "active") {
240      await publish($, { activation: verdict, root });
241      if (was === "active") standDown($);
242      return;
243    }
244    const workspace = workspaceRoot(r);
245    const same = was === "active" && snap.workspace === workspace;
246    await publish($, {
247      activation: "active",
248      root,
249      workspace,
250      daemon: same ? snap.daemon : { kind: "loading", launch: "none" },
251    });
252    if (!same) {
253      expanded = [];
254      uiLink = undefined;
255      detail = undefined;
256      heldTree = undefined;
257      client?.setExpand([]);
258      await setOffset($, 0);
259    }
260    client?.setWorkspace(workspace);
261    status($);
262    // Off the start's path: the hook that probed has returned long ago
263    if (!same) void client?.refresh();
264    if (!same && autoOpen) await openPane($);
265  } finally {
266    probing = false;
267  }
268}
269
270/**
271 * The one reconciliation point. Walks again when the root moved or the last
272 * walk could still change its mind, puts the snapshot back in `$.state` when
273 * it came back empty (a /clear, a worker that was replaced), re-arms a timer
274 * that never fired, and refreshes the status line with a request that waits
275 * on nothing (`wait=0`).
276 */
277async function reconcile($: any): Promise<void> {
278  if (!started || !isLive(snap.activation)) return;
279  const root: string | undefined = await $.session.root().catch(() => undefined);
280  if (root !== undefined && (root !== snap.root || worthReprobing(resolution)))
281    await probe($);
282  const held = await $.state.get(SNAP).catch(() => undefined);
283  if (held && held.value === undefined) await publish($, snap);
284  if (snap.activation !== "active" || !client) return;
285  // A pane the engine placed since (a wider terminal, a surface attaching)
286  // starts the tick; one that went away stops it
287  client.setTicking(await placed($));
288  await client.reconcile();
289  if (!client.ticking) void client.refresh({ waitS: 0 });
290}
291
292/** The session's start, or a surface attaching to a session that had none. */
293async function start($: any, surfaces: readonly string[]): Promise<void> {
294  started = true;
295  const v = await $.session.version().catch(() => undefined);
296  if (!atLeast(v?.base ?? v?.version, MIN_ENGINE)) {
297    await publish($, { activation: "floor" });
298    $.ui.status(`Claude Code ${MIN_ENGINE} ou plus requis`);
299    return;
300  }
301  // Host commands are the CLI's (`$.process` is "CLI only"): on a session
302  // the terminal does not draw, the button becomes a command to copy
303  const canRun = surfaces.includes("terminal");
304  client = new Client(portOf($, canRun));
305  client.windowed = scrolling === "window";
306  // A hot reload keeps $.state: the person's opened folders come back
307  const held = await $.state.get(EXPANDED).catch(() => undefined);
308  if (Array.isArray(held?.value)) {
309    expanded = held.value.filter((x: unknown) => typeof x === "string").slice(0, 500);
310    client.setExpand(expanded);
311  }
312  const kept = await $.state.get(FILTER).catch(() => undefined);
313  if (Array.isArray(kept?.value)) {
314    filter = kept.value.filter((x: unknown) => (SEVERITIES as readonly string[]).includes(x as string));
315    client.setFilter(filter);
316  }
317  await $.command
318    .register({
319      name: "ktn-view",
320      description: "ktn-linter : état du daemon et constats du projet Go",
321    })
322    .catch((err: unknown) =>
323      $.ui.log(`kodflow-ktn: /${COMMAND} refusé : ${String(err)}`, {
324        to: "debug",
325      }),
326    );
327  await publish($, { activation: "probing" });
328  // Detached: the probe's listings are not the start's to wait on
329  void probe($).catch(() => undefined);
330}
331
332function commandText(): string {
333  switch (snap.activation) {
334    case "active":
335      return `${stateLine(snap).text.replace("ktn · ", "ktn: ")} (workspace ${snap.workspace ?? "?"})`;
336    case "undetermined":
337      return "ktn: projet indéterminé (sonde interrompue) ; activation: always pour forcer";
338    case "probing":
339      return "ktn: sonde du projet en cours";
340    case "floor":
341      return `ktn: Claude Code ${MIN_ENGINE} ou plus requis`;
342    default:
343      return "ktn: pas un projet Go";
344  }
345}
346
347/** The launch button's action: a person's act, so the breaker gives way. */
348function launch(): void {
349  if (!client) return;
350  client.userAction();
351  void client.launch();
352}
353
354export const register: Register = (on, options) => {
355  activation = parseActivation(options.activation);
356  autoOpen = options.autoOpen === true;
357  scrolling = options.scrolling === "native" ? "native" : "window";
358
359  // ONE session.start: two without a matcher keep the module from loading
360  on("session.start", async ($, e, next) => {
361    const surfaces = await $.session.surfaces().catch(() => []);
362    if (surfaces.length === 0) {
363      await publish($, { activation: "inert" });
364      return next(e);
365    }
366    const result = next(e);
367    await start($, surfaces);
368    return result;
369  }).catch(($, e, next) => next(e));
370
371  // A host that attaches its first surface after the start
372  on("session.attach", async ($, e, next) => {
373    const result = await next(e);
374    if (!started && snap.activation === "inert")
375      await start($, await $.session.surfaces().catch(() => [e.surface])).catch(
376        () => undefined,
377      );
378    return result;
379  }).catch(($, e, next) => next(e));
380
381  on("turn.complete", async ($, e, next) => {
382    const result = await next(e);
383    if (e.agentId === undefined) void reconcile($).catch(() => undefined);
384    return result;
385  }).catch(($, e, next) => next(e));
386
387  on("classic.SessionStart", async ($, e, next) => {
388    const result = await next(e);
389    void reconcile($).catch(() => undefined);
390    return result;
391  }).catch(($, e, next) => next(e));
392
393  // The name is spelled out (COMMAND) so the validator reads the matcher.
394  // Answers from what the module holds: never a daemon call, which would
395  // hold the prompt up to 30 s (#774). A person's act: the breaker gives way
396  // and a refresh leaves in the background.
397  on("command.run", { command: "ktn-view" }, async ($, e) => {
398    const arg = String(e.args ?? "").trim().toLowerCase();
399    if (arg === "filtre" || arg.startsWith("filtre ")) return { text: await setFilter($, arg.slice(6)) };
400    if (arg === "off" || arg === "close") {
401      client?.setTicking(false);
402      await $.ui.close({ id: PANE_ID }).catch(() => undefined);
403      return { text: "ktn: panneau fermé" };
404    }
405    // Out of a Go project: the text alone, no pane
406    if (snap.activation === "active" && client) {
407      await openPane($);
408      client.nudge();
409    }
410    return { text: commandText() };
411  });
412
413  // The person closed the pane (its mark, ctrl+x x): the tick goes with it
414  on("ui.close", async ($, e, next) => {
415    const result = await next(e);
416    if (e.id === PANE_ID) client?.setTicking(false);
417    return result;
418  }).catch(($, e, next) => next(e));
419
420  on("ui.render", { component: "Pane", requestId: "ktn-view" }, async ($, e) => {
421    const els: any = $.ui.resolve(e);
422    const held = (await $.state.get(SNAP).catch(() => undefined))?.value ?? snap;
423    const tree = (await $.state.get(TREE).catch(() => undefined))?.value;
424    const now: number = await $.clock.now();
425    const link =
426      uiLink && (uiLink.expiresAt === 0 || uiLink.expiresAt > now)
427        ? { url: uiLink.url, label: uiLink.url.split("#")[0]! }
428        : undefined;
429    let win: { offset: number; bodyRows: number } | undefined;
430    if (scrolling === "window") {
431      const shared = (await $.state.get(OFFSET).catch(() => undefined))?.value;
432      const rows = Number((e.props as any)?.scroll?.bodyRows);
433      win = { offset: typeof shared === "number" ? shared : offset, bodyRows: Number.isFinite(rows) ? rows : 0 };
434    }
435    return safe(els, () =>
436      pane(els, { snap: held, tree, link, now, window: win, filter, detail, onLayout: (rows: number) => {
437        headRows = Math.max(0, (win?.bodyRows ?? 0) - rows);
438      } }, {
439        launch,
440        toggle: (id) => void toggle($, id),
441        openUi: () => void openUi($),
442        inspect: (id) => inspect($, id),
443      }),
444    );
445  });
446
447  // The windowed pane's scroll (#787): the mod moves its own offset, with
448  // the snapshot's total (never `e.contentRows`, which counts the rows drawn)
449  // and the rows this site's body gives the tree; the engine's own window is
450  // kept at the top. Near an edge of what is held, the next window is asked
451  // for, detached on the clock: the hook never waits on the daemon.
452  on("ui.scroll", { component: "Pane", requestId: "ktn-view" }, async ($, e, next) => {
453    if (scrolling !== "window") return next(e);
454    // After a hot reload the module's copy is gone; `$.state` kept it
455    heldTree ??= (await $.state.get(TREE).catch(() => undefined))?.value;
456    const tree = heldTree;
457    if (!tree) return next(e);
458    const total = tree.total ?? tree.nodes.length;
459    const rows = Math.max(1, e.bodyRows - headRows);
460    // The offset the renders read: after a hot reload the module's is 0
461    const shared = (await $.state.get(OFFSET).catch(() => undefined))?.value;
462    const from = typeof shared === "number" ? shared : offset;
463    const moved = scrolled(from, e.by, total, rows);
464    if (moved !== from) {
465      await setOffset($, moved);
466      $.ui.invalidate("ui.render");
467    }
468    const ask = nextWindow(tree, moved, rows);
469    if (ask !== undefined && client?.setWindow(ask)) $.clock.after(0, () => client?.nudge());
470    return next({ ...e, offset: 0 });
471  }).catch(($, e, next) => next(e));
472
473  // The band above the prompt, while there is something to act on
474  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
475    const els: any = $.ui.resolve(e);
476    const held = (await $.state.get(SNAP).catch(() => undefined))?.value ?? snap;
477    const tree = safe(els, () => band(els, held, { launch }));
478    return tree ?? next(e);
479  });
480};
481
hooks/mod/client.ts 599 lines
1// client.ts — the mod's side of the daemon: discovery, the refresh, the
2// states, the launch button. Pure: the engine is a port handed in, so the
3// node tests drive every failure with a clock of their own.
4//
5// "Never crashes" (kodflow/ktn-linter#776) is held as two properties:
6//   1. no callback holds the worker every mod shares: one request at a time,
7//      a body too big to parse refused unread, every loop bounded;
8//   2. every known failure ends in a DRAWN state, never in silence: each
9//      path below ends in `set(...)`, and nothing here throws past `refresh`.
10//
11// One request at a time: `inflight` is tied to the UNDERLYING fetch, not to
12// the race the mod runs against it. `$.http.fetch` has a fixed 30 s deadline
13// and no signal, so when the race's own timer (the request's wait + 5 s)
14// fires first, the state turns unreachable at once, but no second request
15// leaves until the first one has settled; and its late answer is dropped
16// (the generation moved on). One exception, bounded: while a pane's
17// long-poll waits on a HEALTHY daemon (it is answering, just holding the
18// request for up to 20 s), a person's press may send one request beside it,
19// and the long-poll's answer — now about a tree the person no longer looks
20// at — is dropped by the same generation. Never more than two.
21//
22// No timer exists unless a pane is placed (#777 sets `ticking`): the status
23// line is refreshed by the turn's end, the pane by a chain of one-shot
24// timers, re-armed in a `finally`, never `every` (two periods could overlap).
25import type { KtnDaemon, KtnModel } from "../../types";
26import {
27  BACKOFF_MAX_MS,
28  BACKOFF_MIN_MS,
29  BREAKER_AFTER,
30  LAUNCH_POLL_MS,
31  LAUNCH_TIMEOUT_MS,
32  MAX_TEXT,
33  MAX_WAIT_S,
34  PROTOCOL_VERSION,
35  RACE_SLACK_MS,
36  UI_BOOT,
37  VIEW_ROUTE,
38  WINDOW_ROWS,
39} from "./contract.ts";
40import {
41  classifyRejection,
42  isNotServed,
43  parseJson,
44  parseModel,
45  parseStatus,
46  refusalOf,
47  type Failure,
48} from "./daemon.ts";
49import { anchorPaths, parseEndpoint, type Endpoint } from "./endpoint.ts";
50import { clean } from "./sanitize.ts";
51
52export type Answer = { status: number; text: string };
53export type Timer = { cancel(): void };
54
55/** What the client needs from the engine. */
56export type Port = {
57  now(): Promise<number>;
58  /** `$.clock.after`: one call of `fn` after `ms`, unless cancelled. */
59  after(ms: number, fn: () => void): Timer;
60  /** `$.fs.read`: rejects when the file is missing. */
61  read(path: string): Promise<string>;
62  home(): Promise<string | undefined>;
63  /** `$.http.fetch` over the socket: resolves any status, rejects on transport. */
64  fetch(url: string, init: { socketPath: string; method?: string }): Promise<Answer>;
65  /** `$.process.run`; absent where the surface has no host commands. */
66  run?: (
67    argv: string[],
68    init: { cwd: string; timeoutMs: number; env: Record<string, string> },
69  ) => Promise<{ exitCode: number; stderr: string }>;
70  /** Called on every change of what is drawn. */
71  emit(daemon: KtnDaemon, model: KtnModel | undefined): void;
72};
73
74const TIMEOUT = Symbol("timeout");
75/** An answer to a request someone else's has superseded: not a failure, nothing to draw. */
76const STALE = Symbol("stale");
77type Outcome = Answer | Failure | typeof STALE;
78const isFailure = (x: Answer | Failure): x is Failure => "kind" in x;
79
80/** A bootstrap link to the web UI: the token rides in the fragment. */
81export type UiLink = { url: string; expiresAt: number };
82
83/** The tick's period while a pane is placed (#777). */
84export const TICK_MS = 3_000;
85/** A launch still "starting" past this is given up at the next reconciliation. */
86const LAUNCH_STALE_MS = 3 * LAUNCH_TIMEOUT_MS;
87
88export class Client {
89  port: Port;
90  workspace = "";
91  view: KtnDaemon = { kind: "loading", launch: "none" };
92  model: KtnModel | undefined = undefined;
93  /** The model last handed to `emit`, so an unchanged one is not sent again. */
94  emitted: KtnModel | undefined = undefined;
95  endpoint: Endpoint | undefined = undefined;
96  endpointText: string | undefined = undefined;
97  handshaken = false;
98  incompatible = false;
99  /** Underlying fetches not settled yet: 0, 1, or 2 (a long-poll and a press). */
100  inflight = 0;
101  /** True while the request in flight is a long-poll. */
102  longPolling = false;
103  gen = 0;
104  failures = 0;
105  breakerUntil = 0;
106  rev = 0;
107  /**
108   * Bumped whenever what is asked changes — the workspace, the opened ids,
109   * the window, the filter (#787). An answer to a request of an older shape
110   * is dropped: its revision would otherwise be sent with the new query and
111   * its model drawn as the new window.
112   */
113  shape = 0;
114  /** Directory and file ids the pane asked to see opened (#777). */
115  expand: string[] = [];
116  /**
117   * The windowed mode (#787): each request names its window, `offset=from`
118   * and `limit=WINDOW_ROWS`; off, the daemon's default window is asked.
119   */
120  windowed = false;
121  /** The window's first node, in the windowed mode. */
122  from = 0;
123  /** The severities asked for (`severity=`), empty for all (#787). */
124  filter: string[] = [];
125  /** The long-poll's wait while a pane is placed, 0 otherwise. */
126  waitS = 0;
127  launching = false;
128  launchStartedAt = 0;
129  ticking = false;
130  timer: Timer | undefined = undefined;
131  dueAt = 0;
132  tickRunning = false;
133  stopped = false;
134
135  constructor(port: Port) {
136    this.port = port;
137  }
138
139  /** The workspace asked about; a new one starts the view over. */
140  setWorkspace(ws: string): void {
141    this.stopped = false;
142    if (ws === this.workspace) return;
143    this.workspace = ws;
144    this.rev = 0;
145    this.shape++;
146    this.model = undefined;
147    this.expand = [];
148    this.from = 0;
149    this.set({ kind: "loading", launch: "none" });
150  }
151
152  /** Leaving the Go project: no timer, no request. */
153  stop(): void {
154    this.stopped = true;
155    this.setTicking(false);
156  }
157
158  private set(next: Partial<KtnDaemon> & { kind?: KtnDaemon["kind"] }): void {
159    const view: KtnDaemon = { ...this.view, ...next };
160    // A state never claims more than it knows: counts go with "ready" alone
161    if (view.kind !== "ready") {
162      delete view.totals;
163      delete view.engine;
164    }
165    if (view.kind === "ready" || view.kind === "loading") {
166      delete view.detail;
167      delete view.command;
168    }
169    for (const k of Object.keys(view) as (keyof KtnDaemon)[])
170      if (view[k] === undefined) delete view[k];
171    // The same state again (a 204, the same failure) redraws nothing
172    const model = view.kind === "ready" ? this.model : undefined;
173    if (JSON.stringify(view) === JSON.stringify(this.view) && model === this.emitted) return;
174    this.view = view;
175    this.emitted = model;
176    try {
177      this.port.emit(view, model);
178    } catch {
179      // The drawing is the engine's business; a refused write changes nothing here
180    }
181  }
182
183  private async race<T>(p: Promise<T>, ms: number): Promise<T | typeof TIMEOUT> {
184    let timer: Timer | undefined;
185    const timeout = new Promise<typeof TIMEOUT>((resolve) => {
186      timer = this.port.after(ms, () => resolve(TIMEOUT));
187    });
188    try {
189      return await Promise.race([p, timeout]);
190    } finally {
191      timer?.cancel();
192    }
193  }
194
195  /** One request over the socket, raced; a failure is a value, never a throw. */
196  private async request(path: string, waitS: number, method?: string): Promise<Outcome> {
197    const socketPath = this.endpoint!.socket;
198    const mine = ++this.gen;
199    const long = waitS > 0;
200    this.inflight++;
201    if (long) this.longPolling = true;
202    const underlying: Promise<Answer | Failure> = this.port
203      .fetch(`http://ktn${path}`, method ? { socketPath, method } : { socketPath })
204      .then(
205        (r) => ({ status: Number(r?.status) || 0, text: typeof r?.text === "string" ? r.text : "" }),
206        (err) => classifyRejection(err),
207      )
208      .finally(() => {
209        this.inflight--;
210        if (long) this.longPolling = false;
211      });
212    const r = await this.race(underlying, waitS * 1_000 + RACE_SLACK_MS);
213    if (mine !== this.gen) return STALE;
214    if (r === TIMEOUT) {
215      // Whatever it says later is about a request nobody waits for any more
216      this.gen++;
217      return { kind: "silent", detail: "le daemon ne répond pas" };
218    }
219    return r;
220  }
221
222  private ensureCommand(): string {
223    return `KTN_USER_DAEMON=1 ${this.endpoint?.exe || "ktn-linter"} daemon ensure`;
224  }
225
226  private backoff(): number {
227    const n = Math.max(1, this.failures);
228    return Math.min(BACKOFF_MIN_MS * 2 ** Math.min(n - 1, 10), BACKOFF_MAX_MS);
229  }
230
231  private async failed(f: Failure): Promise<void> {
232    this.failures++;
233    this.handshaken = false;
234    if (this.failures >= BREAKER_AFTER)
235      this.breakerUntil = (await this.port.now()) + this.backoff();
236    if (f.kind === "policy") {
237      this.set({ kind: "policy", detail: f.detail, launch: "none", command: undefined });
238      return;
239    }
240    const launch =
241      f.kind === "absent" ? (this.endpoint?.exe && this.port.run ? "button" : "command") : "none";
242    this.set({
243      kind: "unreachable",
244      detail: f.kind === "absent" ? "aucun daemon sur le socket" : f.detail,
245      launch,
246      command: launch === "none" ? undefined : this.ensureCommand(),
247    });
248  }
249
250  /** endpoint.json from its anchors; a move resets what the old one taught. */
251  private async readEndpoint(): Promise<{ ok: true } | { ok: false; detail: string }> {
252    const paths = anchorPaths(await this.port.home());
253    for (const path of paths) {
254      let text: string;
255      try {
256        text = await this.port.read(path);
257      } catch {
258        continue;
259      }
260      if (text !== this.endpointText) {
261        this.endpointText = text;
262        this.handshaken = false;
263        this.incompatible = false;
264        this.failures = 0;
265        this.breakerUntil = 0;
266      }
267      const parsed = parseEndpoint(text);
268      if (!parsed.ok) {
269        this.endpoint = undefined;
270        return { ok: false, detail: parsed.reason };
271      }
272      this.endpoint = parsed.endpoint;
273      return { ok: true };
274    }
275    this.endpoint = undefined;
276    this.endpointText = undefined;
277    return { ok: false, detail: "endpoint.json absent : le daemon utilisateur n'a jamais démarré" };
278  }
279
280  private query(waitS: number): string {
281    const q = [`workspace=${encodeURIComponent(this.workspace)}`, `wait=${waitS}`];
282    if (this.rev > 0) q.push(`since=${this.rev}`);
283    for (const id of this.expand) q.push(`expand=${encodeURIComponent(id)}`);
284    if (this.windowed) q.push(`offset=${this.from}`, `limit=${WINDOW_ROWS}`);
285    if (this.filter.length > 0) q.push(`severity=${this.filter.map(encodeURIComponent).join(",")}`);
286    return q.join("&");
287  }
288
289  /**
290   * One look at the daemon. `waitS` is the long-poll (0 for the status line);
291   * `force` passes the breaker (a person's own act); `interactive` may go
292   * beside a long-poll that is waiting on a daemon that answers (a press on
293   * the tree), and supersedes it.
294   */
295  async refresh(opts: { waitS?: number; force?: boolean; interactive?: boolean } = {}): Promise<void> {
296    if (this.stopped || !this.workspace) return;
297    const beside = opts.interactive === true && this.inflight === 1 && this.longPolling && this.handshaken;
298    if (this.inflight > 0 && !beside) return;
299    try {
300      await this.refreshOnce(opts.waitS ?? 0, opts.force === true);
301    } catch (err) {
302      // Not a path anything above expects; still a drawn state, not a silence
303      await this.failed({ kind: "broken", detail: clean(String(err), MAX_TEXT) }).catch(() => undefined);
304    }
305  }
306
307  private async refreshOnce(waitS: number, force: boolean): Promise<void> {
308    const now = await this.port.now();
309    if (!force && now < this.breakerUntil) return;
310    const ep = await this.readEndpoint();
311    if (!ep.ok) {
312      // No pointer, no request: nothing on the network is asked
313      this.set({
314        kind: "unreachable",
315        detail: ep.detail,
316        launch: "command",
317        command: this.ensureCommand(),
318      });
319      return;
320    }
321    if (this.incompatible) return;
322    if (!this.handshaken) {
323      const st = await this.request("/status", 0);
324      if (st === STALE) return;
325      if (isFailure(st)) return this.failed(st);
326      if (st.status !== 200) return this.failed({ kind: "broken", detail: `HTTP ${st.status} sur /status` });
327      const parsed = parseStatus(st.text, this.workspace);
328      if (!parsed.ok) return this.failed({ kind: "broken", detail: parsed.detail });
329      if (parsed.protocol !== PROTOCOL_VERSION) return this.incompatibleWith(parsed.protocol);
330      this.handshaken = true;
331    }
332    const asked = this.shape;
333    const r = await this.request(`${VIEW_ROUTE}?${this.query(waitS)}`, waitS);
334    // STALE, or an answer about a query that no longer stands
335    if (r === STALE || asked !== this.shape) return;
336    if (isFailure(r)) return this.failed(r);
337    if (r.status === 204) return this.served(now, undefined);
338    if (r.status === 200) {
339      const m = parseModel(r.text);
340      if (m.ok) return this.served(now, m.model);
341      if (m.incompatible !== undefined) return this.incompatibleWith(m.incompatible);
342      return this.failed({ kind: "broken", detail: m.detail });
343    }
344    if (isNotServed(r.status, r.text)) return this.notServed(refusalOf(r.text));
345    if (r.status === 400)
346      return this.refused(refusalOf(r.text) || "requête refusée");
347    return this.failed({ kind: "broken", detail: `HTTP ${r.status}` });
348  }
349
350  private incompatibleWith(protocol: string): void {
351    this.incompatible = true;
352    this.handshaken = false;
353    this.set({
354      kind: "incompatible",
355      detail: `ktn-linter ${clean(this.endpoint?.version, 40) || "?"} parle ${clean(protocol, 20) || "?"}, ce mod attend ${PROTOCOL_VERSION}`,
356      launch: "none",
357      command: undefined,
358    });
359  }
360
361  private refused(reason: string): void {
362    this.failures = 0;
363    this.set({ kind: "refused", detail: reason, launch: "none", command: undefined });
364  }
365
366  /** Not served: waiting for the person's approval, or refused outright. */
367  private async notServed(reason: string): Promise<void> {
368    const st = await this.request("/status", 0);
369    if (st === STALE) return;
370    if (!isFailure(st) && st.status === 200) {
371      const parsed = parseStatus(st.text, this.workspace);
372      if (parsed.ok && parsed.pending) {
373        this.failures = 0;
374        this.set({
375          kind: "pending",
376          detail: parsed.pending.reason,
377          command: parsed.pending.command,
378          launch: "none",
379        });
380        return;
381      }
382    }
383    this.refused(reason || "workspace non servi");
384  }
385
386  private served(now: number, model: KtnModel | undefined): void {
387    this.failures = 0;
388    this.breakerUntil = 0;
389    if (model) {
390      this.model = model;
391      this.rev = model.rev;
392    }
393    const m = this.model;
394    this.set({
395      kind: "ready",
396      launch: "none",
397      version: this.endpoint?.version ? clean(this.endpoint.version, 40) : undefined,
398      totals: m?.totals,
399      engine: m?.state,
400      at: now,
401    });
402  }
403
404  /** A person's own act (a press, the command): the breaker gives way. */
405  userAction(): void {
406    this.failures = 0;
407    this.breakerUntil = 0;
408  }
409
410  /**
411   * A person's act (the command, a press): the breaker and the backoff give
412   * way, and a look leaves now — the tick's next one, or one beside a
413   * long-poll that is waiting on a daemon that answers.
414   */
415  nudge(): void {
416    this.userAction();
417    if (!this.ticking) {
418      void this.refresh({ waitS: 0, force: true });
419      return;
420    }
421    if (this.tickRunning) {
422      void this.refresh({ waitS: 0, force: true, interactive: true });
423      return;
424    }
425    this.timer?.cancel();
426    this.timer = undefined;
427    this.arm(0);
428  }
429
430  /** The pane changed what it shows opened: the next answer must be whole. */
431  setExpand(ids: string[]): void {
432    this.expand = ids;
433    this.rev = 0;
434    this.shape++;
435  }
436
437  /**
438   * The windowed pane scrolled near the edge of what it holds (#787): the
439   * next request asks for the window from `from`. Returns false when that
440   * window is already the one asked for, so a scroll inside it asks nothing.
441   */
442  setWindow(from: number): boolean {
443    const next = Math.max(0, Math.floor(from));
444    if (next === this.from) return false;
445    this.from = next;
446    this.rev = 0;
447    this.shape++;
448    return true;
449  }
450
451  /** The pane's severity filter changed: the next answer must be whole. */
452  setFilter(severities: string[]): void {
453    this.filter = severities;
454    this.from = 0;
455    this.rev = 0;
456    this.shape++;
457  }
458
459  private sleep(ms: number): Promise<void> {
460    return new Promise((resolve) => {
461      this.port.after(ms, resolve);
462    });
463  }
464
465  /**
466   * The launch button. Compare-and-set before any await, so two presses run
467   * one command; the binary is the absolute one endpoint.json names, never a
468   * name looked up in PATH; the working directory is `/`, never the project.
469   */
470  async launch(): Promise<void> {
471    if (this.launching) return;
472    this.launching = true;
473    try {
474      const exe = this.endpoint?.exe;
475      if (!exe || !this.port.run) return;
476      this.launchStartedAt = await this.port.now();
477      this.set({ launching: "starting", launchError: undefined });
478      let exit: { exitCode: number; stderr: string } | undefined;
479      let error = "";
480      try {
481        exit = await this.port.run([exe, "daemon", "ensure"], {
482          cwd: "/",
483          timeoutMs: LAUNCH_TIMEOUT_MS,
484          env: { KTN_USER_DAEMON: "1" },
485        });
486      } catch (err) {
487        error = clean(String((err as any)?.message ?? err), MAX_TEXT);
488      }
489      // A zero exit proves a request, not a daemon: the socket says
490      this.userAction();
491      const t0 = await this.port.now();
492      for (;;) {
493        this.handshaken = false;
494        await this.refresh({ waitS: 0, force: true });
495        if (this.view.kind !== "unreachable") break;
496        if ((await this.port.now()) - t0 >= LAUNCH_TIMEOUT_MS) break;
497        await this.sleep(LAUNCH_POLL_MS);
498      }
499      if (this.view.kind === "unreachable")
500        this.set({
501          launching: "failed",
502          launchError:
503            error || `code ${exit?.exitCode ?? "?"} : ${clean(exit?.stderr, MAX_TEXT).trim() || "pas de message"}`,
504        });
505      else this.set({ launching: undefined, launchError: undefined });
506    } finally {
507      this.launching = false;
508    }
509  }
510
511  /** The pane is placed (or no longer): the tick, and its long-poll, exist only then. */
512  setTicking(on: boolean): void {
513    this.ticking = on && !this.stopped;
514    if (!this.ticking) {
515      this.timer?.cancel();
516      this.timer = undefined;
517      this.waitS = 0;
518      return;
519    }
520    this.waitS = MAX_WAIT_S;
521    this.arm(0);
522  }
523
524  /**
525   * A bootstrap link to the web UI, minted over the socket (same uid) on the
526   * person's press: `POST /ui/boot`. The token is returned to the caller and
527   * kept by it in a module variable, drawn in the pane's tree alone — never
528   * written to `$.state` (any plugin reads it) nor to the command's text
529   * (the model reads it).
530   */
531  async mint(): Promise<UiLink | { error: string }> {
532    if (!this.endpoint) return { error: "daemon injoignable" };
533    const socketPath = this.endpoint.socket;
534    const underlying = this.port
535      .fetch(`http://ktn${UI_BOOT}`, { socketPath, method: "POST" })
536      .then(
537        (r) => ({ status: Number(r?.status) || 0, text: typeof r?.text === "string" ? r.text : "" }),
538        (err) => classifyRejection(err),
539      );
540    const r = await this.race(underlying, RACE_SLACK_MS);
541    if (r === TIMEOUT) return { error: "le daemon ne répond pas" };
542    if (isFailure(r)) return { error: r.detail };
543    if (r.status !== 200) return { error: clean(r.text, 160).trim() || `HTTP ${r.status}` };
544    const raw: any = parseJson(r.text);
545    const url = raw?.url;
546    // Only the loopback listener the daemon serves; anything else is not drawn
547    if (typeof url !== "string" || url.length > 2_000 || !(url.startsWith("http://127.0.0.1:") || url.startsWith("http://localhost:") || url.startsWith("http://[::1]:")))
548      return { error: "lien de l'UI inattendu" };
549    const expiresAt = Date.parse(String(raw?.expires_at));
550    return { url, expiresAt: Number.isFinite(expiresAt) ? expiresAt : 0 };
551  }
552
553  /** Arms the ONE timer of the chain, if none is armed. */
554  private arm(delay: number): void {
555    if (!this.ticking || this.timer || this.stopped) return;
556    let fired = false;
557    const timer = this.port.after(delay, () => {
558      fired = true;
559      if (this.timer === timer) this.timer = undefined;
560      void this.tick();
561    });
562    if (!fired) this.timer = timer;
563    void this.port.now().then((now) => {
564      if (this.timer === timer) this.dueAt = now + delay;
565    });
566  }
567
568  private async tick(): Promise<void> {
569    if (this.tickRunning) return;
570    this.tickRunning = true;
571    try {
572      await this.refresh({ waitS: this.waitS });
573    } finally {
574      this.tickRunning = false;
575      this.arm(this.failures > 0 ? this.backoff() : TICK_MS);
576    }
577  }
578
579  /**
580   * The reconciliation's part (#775 step b): a timer a hook refused never
581   * fires, and nothing else would notice. Past three periods beyond its due
582   * time, it is cancelled and armed again. A launch that never settled is
583   * given up the same way.
584   */
585  async reconcile(): Promise<void> {
586    const now = await this.port.now();
587    if (this.launching && now - this.launchStartedAt > LAUNCH_STALE_MS) {
588      this.launching = false;
589      this.set({ launching: "failed", launchError: "le lancement n'a pas abouti" });
590    }
591    if (!this.ticking || this.tickRunning) return;
592    if (this.timer === undefined || now > this.dueAt + 3 * TICK_MS) {
593      this.timer?.cancel();
594      this.timer = undefined;
595      this.arm(0);
596    }
597  }
598}
599
hooks/mod/contract.ts 129 lines
1// contract.ts — the constants this mod shares with ktn-linter and with the
2// engine, each with where it was measured or where the other side writes it.
3//
4// Nothing here is computed: a value that the daemon owns is read from the
5// daemon (endpoint.json, /status, /api/view), and the few constants a client
6// must know beforehand are pinned below with their source, so a change on
7// the other side is a diff someone reads, not a silent drift.
8
9/** The ktn-linter commit the constants and the fixtures were taken from. */
10export const KTN_LINTER_SHA = "bb5c349d2009ef79df8df1b9a5e2ba7758cb1827";
11
12/**
13 * The oldest Claude Code the spike of kodflow/ktn-linter#774 measured
14 * (2.1.299 and 2.1.301 only, no bisection below): the mod stays inert under
15 * it, with one status line saying why.
16 */
17export const MIN_ENGINE = "2.1.299";
18
19/**
20 * The activation probe's budget, fixed by the same spike: one `$.fs` call
21 * costs 1 to 9 ms, `session.start` is awaited before the first prompt, so the
22 * probe stops after three listings or 250 ms and answers "undetermined".
23 */
24export const PROBE_MAX_CALLS = 3;
25export const PROBE_MAX_MS = 250;
26
27/**
28 * pkg/daemonaddr/socket.go `ProtocolVersion`: the daemon's wire version, the
29 * `protocol_version` of /status and the `schema` of every /api/view answer.
30 */
31export const PROTOCOL_VERSION = "v1";
32
33/** pkg/daemonctl/files.go `EndpointSchema`: endpoint.json's layout version. */
34export const ENDPOINT_SCHEMA = 1;
35
36/**
37 * pkg/daemonctl/layout.go `CheckSocketPath`: the daemon refuses to bind a
38 * socket path over 96 bytes (the engine itself reaches 107, the Linux
39 * `sun_path` limit, measured by #774). A pointer naming a longer one was not
40 * written by a daemon that could serve it.
41 */
42export const SOCKET_MAX_BYTES = 96;
43
44/**
45 * pkg/userdirs `Anchor()`: endpoint.json sits under HOME alone, whatever
46 * XDG_STATE_HOME says, so a client finds it when the state is redirected.
47 * base_xdg.go: `~/.local/state`; base_darwin.go: `~/Library/Application
48 * Support`. Windows (LOCALAPPDATA) is out of the mod's support (#774).
49 */
50export const ANCHORS = [
51  ".local/state/ktn-linter/endpoint.json",
52  "Library/Application Support/ktn-linter/endpoint.json",
53] as const;
54
55/** pkg/view/wire.go `RoutePath`, mounted on the socket only. */
56export const VIEW_ROUTE = "/api/view";
57
58/** pkg/view/query.go `MaxWait`: the long-poll's wait while a pane is placed. */
59export const MAX_WAIT_S = 20;
60
61/**
62 * pkg/serve/ui.go `uiBootPath`: the socket route that mints a bootstrap link
63 * to the web UI, of class `view` (read-only, pkg/webui) — the only class it
64 * grants, so a token that went through a mod never opens an admin session.
65 */
66export const UI_BOOT = "/ui/boot";
67
68/**
69 * A rendered tree draws its first 100 000 characters (the engine's limit):
70 * the pane stops its rows at this budget and says how many it left out.
71 */
72export const RENDER_BUDGET = 90_000;
73
74/**
75 * The mod's own window over the tree (kodflow/ktn-linter#787), the
76 * `scrolling: window` mode: the daemon serves WINDOW_ROWS nodes from an
77 * offset (`offset=` / `limit=`, pkg/view), the snapshot kept in `$.state` is
78 * cut at WINDOW_MAX_CHARS of text (re-read on every render, so on every
79 * wheel tick), and a scroll that comes within WINDOW_EDGE rows of either end
80 * of what is held asks for the next window, detached.
81 */
82export const WINDOW_ROWS = 180;
83export const WINDOW_MAX_CHARS = 70_000;
84export const WINDOW_EDGE = 20;
85
86/**
87 * pkg/view/query.go `paramSeverity`: the severity filter the pane sends
88 * (`/ktn-view filtre error,warning`), each value one of these.
89 */
90export const SEVERITIES = ["error", "warning", "info"] as const;
91
92/** pkg/view/wire.go `CodeWorkspaceNotServed`. */
93export const NOT_SERVED = "workspace_not_served";
94
95/**
96 * pkg/view/build.go `MaxResponseBytes` is 1 MiB; the engine's fetch takes
97 * 4 MiB. Past 1.5 MiB the answer is not one a daemon of this protocol sends,
98 * and parsing it would hold the worker every mod shares: it is refused unread.
99 */
100export const MAX_BODY_CHARS = 1_572_864;
101
102/** pkg/view/build.go `MaxLimit`: the most nodes one window holds. */
103export const MAX_NODES = 1_000;
104
105/**
106 * `$.http.fetch` has one fixed deadline, 30 s, and no signal (#774). The mod
107 * races its own: the request's wait plus 5 s.
108 */
109export const RACE_SLACK_MS = 5_000;
110
111/** After this many failures in a row, the turn's refresh waits its backoff. */
112export const BREAKER_AFTER = 5;
113export const BACKOFF_MIN_MS = 3_000;
114export const BACKOFF_MAX_MS = 60_000;
115
116/** The launch button: `daemon ensure` gets 10 s, then a look every 500 ms for 10 s. */
117export const LAUNCH_TIMEOUT_MS = 10_000;
118export const LAUNCH_POLL_MS = 500;
119
120/** What a daemon string may take in a drawing, and an error the button shows. */
121export const MAX_TEXT = 300;
122
123/** The plugin's name, which `$.state` keys and the pane id are scoped by. */
124export const PLUGIN = "kodflow-ktn";
125/** `/ktn` belongs to kodflow-devops (#774): the mod's command is this one. */
126export const COMMAND = "ktn-view";
127/** The pane's id, the same word. */
128export const PANE_ID = "ktn-view";
129
hooks/mod/engine.ts 23 lines
1// engine.ts — the engine's version against the mod's floor. Pure.
2
3/** `2.1.299`, `2.1.299-dev…` → [2, 1, 299]; undefined when not a release. */
4export function release(v: string | undefined): number[] | undefined {
5  if (typeof v !== "string") return undefined;
6  const core = v.split("-")[0]!.split(".");
7  if (core.length !== 3) return undefined;
8  const nums = core.map((p) => (/^\d{1,6}$/.test(p) ? Number(p) : NaN));
9  return nums.some(Number.isNaN) ? undefined : nums;
10}
11
12/**
13 * Whether `version` is at or above `floor`. A version that is not spelled
14 * as a release is below it: the mod was measured on releases only.
15 */
16export function atLeast(version: string | undefined, floor: string): boolean {
17  const a = release(version);
18  const b = release(floor);
19  if (!a || !b) return false;
20  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! > b[i]!;
21  return true;
22}
23
hooks/mod/project.ts 183 lines
1// project.ts — is the session in a Go project, and which workspace would the
2// daemon serve for it. Pure: the file system is a lister handed in.
3//
4// It is ktn-linter's `daemonaddr.ResolveProject` (#743), walked the same way,
5// and it is held to the SAME golden table (tests/fixtures/resolve-project.json,
6// copied from the Go test at a pinned commit): a second predicate that
7// drifted from the daemon's would light the mod up where the hooks see no
8// project, or keep it dark where they serve one.
9//
10//   - git root: the nearest directory holding `.git`, a folder (main
11//     checkout) or a FILE (linked worktree); none outside a repository.
12//   - module roots: every directory from the start up to that boundary (or
13//     the file system's root) holding a regular `go.mod` or `go.work`,
14//     deepest first. Crossing a `vendor/` directory discards what was found
15//     below it: vendored copies are other modules.
16//   - module root: the nearest go.work among them, else the nearest go.mod.
17//   - Go: at least one module root. A repository whose modules all sit in
18//     subfolders is NOT Go from its root — the resolver's definition, which
19//     `activation: always` overrides.
20//
21// One listing per level, walked upward only: nothing below the start is ever
22// read, so a `bazel-out` link to a tree holding a go.mod is never followed.
23// The walk stops at the boundary, or at the budget (#774: three listings,
24// 250 ms), and then says so: an incomplete walk is UNDETERMINED, never a
25// guess.
26
27/** One directory entry, as `$.fs.list` gives it. */
28export type Entry = {
29  name: string;
30  kind: "file" | "dir" | "other";
31  isLink: boolean;
32};
33
34/** Lists a directory; rejects when it cannot be read. */
35export type Lister = (dir: string) => Promise<readonly Entry[]>;
36
37export type Resolution = {
38  /** Where the walk started, as given (absolute). */
39  dir: string;
40  /** "" outside a repository, or when the walk stopped short of it. */
41  gitRoot: string;
42  /** Deepest first. */
43  moduleRoots: string[];
44  /** The nearest go.work, else the nearest go.mod; "" for none. */
45  moduleRoot: string;
46  isGo: boolean;
47  /** False when the budget, a deadline or an unreadable folder cut the walk. */
48  complete: boolean;
49  /** Listings made. */
50  calls: number;
51};
52
53export type Activation = "auto" | "always" | "off";
54export type Verdict = "active" | "inactive" | "undetermined";
55
56export type Budget = {
57  /** At most this many listings; Infinity for none. */
58  maxCalls: number;
59  /** Answers true once the time is spent; checked before every listing. */
60  expired?: () => Promise<boolean>;
61};
62
63const VENDOR = "vendor";
64
65/** The parent of an absolute POSIX path; "/" is its own. */
66export function parentOf(dir: string): string {
67  const cut = dir.lastIndexOf("/");
68  return cut <= 0 ? "/" : dir.slice(0, cut);
69}
70
71export function baseOf(dir: string): string {
72  return dir.slice(dir.lastIndexOf("/") + 1);
73}
74
75/** Drops a trailing slash, keeping "/". */
76export function clean(dir: string): string {
77  let d = dir;
78  while (d.length > 1 && d.endsWith("/")) d = d.slice(0, -1);
79  return d;
80}
81
82// A go.mod or go.work counts when it is a regular file. A link is counted as
83// the file it most likely leads to: the Go side stats through it, and telling
84// a link to a folder from one to a file would cost a call per level.
85const isMarkerFile = (e: Entry | undefined): boolean =>
86  e !== undefined && (e.kind === "file" || e.isLink);
87
88/**
89 * Walks from `start` (absolute) up to the git root, the way
90 * `daemonaddr.ResolveProject` does, within the budget.
91 */
92export async function resolveProject(
93  start: string,
94  list: Lister,
95  budget: Budget,
96): Promise<Resolution> {
97  const dir = clean(start);
98  const out: Resolution = {
99    dir,
100    gitRoot: "",
101    moduleRoots: [],
102    moduleRoot: "",
103    isGo: false,
104    complete: false,
105    calls: 0,
106  };
107  // [dir, isWork], deepest first
108  let markers: [string, boolean][] = [];
109  let current = dir;
110  for (;;) {
111    if (out.calls >= budget.maxCalls) break;
112    if (budget.expired && (await budget.expired())) break;
113    let entries: readonly Entry[];
114    try {
115      out.calls++;
116      entries = await list(current);
117    } catch {
118      break;
119    }
120    const byName = new Map<string, Entry>();
121    for (const e of entries) byName.set(e.name, e);
122    const isWork = isMarkerFile(byName.get("go.work"));
123    if (isWork || isMarkerFile(byName.get("go.mod")))
124      markers.push([current, isWork]);
125    if (baseOf(current) === VENDOR) markers = [];
126    // `.git` of any kind marks the boundary (Lstat on the Go side)
127    if (byName.has(".git")) {
128      out.gitRoot = current;
129      out.complete = true;
130      break;
131    }
132    const parent = parentOf(current);
133    if (parent === current) {
134      out.complete = true;
135      break;
136    }
137    current = parent;
138  }
139  out.moduleRoots = markers.map(([d]) => d);
140  out.moduleRoot =
141    markers.find(([, w]) => w)?.[0] ?? markers[0]?.[0] ?? "";
142  out.isGo = out.complete && markers.length > 0;
143  return out;
144}
145
146/**
147 * The root a session in this directory declares to the per-user daemon
148 * (`ProjectRootsValue.WorkspaceRoot`, #758): the module root, else the git
149 * root, else the start. On an incomplete walk, the best seen so far.
150 */
151export function workspaceRoot(r: Resolution): string {
152  return r.moduleRoot || r.gitRoot || r.dir;
153}
154
155/**
156 * The highest directory a search upward may reach (`SearchTop`): the git
157 * root, else the highest module root, else the start.
158 */
159export function searchTop(r: Resolution): string {
160  return r.gitRoot || r.moduleRoots[r.moduleRoots.length - 1] || r.dir;
161}
162
163/** What the mod does with a resolution, under the person's setting. */
164export function verdictOf(r: Resolution, activation: Activation): Verdict {
165  if (activation === "off") return "inactive";
166  if (activation === "always") return "active";
167  if (!r.complete) return "undetermined";
168  return r.isGo ? "active" : "inactive";
169}
170
171export function parseActivation(v: unknown): Activation {
172  return v === "always" || v === "off" ? v : "auto";
173}
174
175/**
176 * Whether a resolution is worth walking again at the next turn: a folder may
177 * have gained its go.mod (`go mod init`), and an undetermined walk may finish
178 * on a quieter disk. A Go project stays one until the root moves.
179 */
180export function worthReprobing(r: Resolution | undefined): boolean {
181  return r === undefined || !r.complete || !r.isGo;
182}
183
hooks/mod/view.ts 416 lines
1// view.ts — what kodflow-ktn draws, from what it holds. Pure: the element
2// table is the surface's (`$.ui.resolve(e)`), `h` the module's JSX factory;
3// nothing here reads `$`, fetches or writes, so a drawing is a function of
4// the snapshot and nothing else.
5//
6// Only Box, Text, Button and Code are used, present on every surface; every
7// string from the daemon was sanitised before it got here (daemon.ts), and
8// `safe` turns any throw into a fallback tree of Box and Text, never a
9// closed pane or an empty band.
10import type { KtnCounts, KtnDaemon, KtnNode, KtnSnap, KtnTree } from "../../types";
11import { RENDER_BUDGET, WINDOW_EDGE, WINDOW_MAX_CHARS, WINDOW_ROWS } from "./contract.ts";
12import { clean } from "./sanitize.ts";
13
14declare const h: (type: unknown, props: Record<string, unknown> | null, ...children: unknown[]) => any;
15
16export type Els = Record<string, unknown>;
17export type Actions = {
18  launch?: () => void;
19  /** Opens or folds a directory or a file, by its id. */
20  toggle?: (id: string) => void;
21  /** Mints a link to the web UI. */
22  openUi?: () => void;
23  /** Shows a finding's detail, or hides it when it is the one shown (#787). */
24  inspect?: (id: string) => void;
25};
26
27/** h without the empty children a conditional leaves behind. */
28export function el(type: unknown, props: Record<string, unknown> | null, ...kids: unknown[]): any {
29  return h(type, props, ...kids.flat().filter((k) => k !== null && k !== undefined && k !== false));
30}
31
32export const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
33
34export function countsText(c: KtnCounts): string {
35  const s = c.severity;
36  return `${plural(c.findings, "constat", "constats")} · ${s.error} E · ${s.warning} W · ${s.info} I`;
37}
38
39/**
40 * The status line under the prompt, or undefined for none. The engine heads
41 * it with the plugin's name already ("kodflow-ktn: …").
42 */
43export function statusText(snap: KtnSnap): string | undefined {
44  if (snap.activation === "floor") return undefined; // said once, at the start
45  if (snap.activation !== "active") return undefined;
46  const d = snap.daemon;
47  if (!d || d.kind === "loading") return "…";
48  switch (d.kind) {
49    case "ready":
50      return d.totals && d.totals.findings > 0
51        ? countsText(d.totals)
52        : "✓ aucun constat";
53    case "unreachable":
54      return d.launching === "starting" ? "démarrage du daemon…" : "daemon injoignable";
55    case "incompatible":
56      return "API incompatible";
57    case "pending":
58      return "workspace en attente d'approbation";
59    case "refused":
60      return "workspace non servi";
61    case "policy":
62      return "requête refusée (politique)";
63  }
64}
65
66/** The line that names the state, for the band and the pane's head. */
67export function stateLine(snap: KtnSnap): { text: string; color?: string } {
68  if (snap.activation === "inactive" || snap.activation === "undetermined")
69    return { text: "ktn · hors projet Go", color: "inactive" };
70  if (snap.activation !== "active") return { text: "ktn · inactif", color: "inactive" };
71  const d = snap.daemon;
72  const why = (s: string) => (d?.detail ? `${s} — ${clean(d.detail, 200)}` : s);
73  switch (d?.kind) {
74    case undefined:
75    case "loading":
76      return { text: "ktn · chargement…", color: "inactive" };
77    case "unreachable":
78      return { text: why("ktn · daemon injoignable"), color: "warning" };
79    case "incompatible":
80      return { text: why("ktn · API incompatible"), color: "error" };
81    case "pending":
82      return { text: why("ktn · en attente d'approbation"), color: "warning" };
83    case "refused":
84      return { text: why("ktn · workspace refusé / non servi"), color: "error" };
85    case "policy":
86      return { text: why("ktn · requête refusée par une politique"), color: "error" };
87    case "ready":
88      return d.totals && d.totals.findings > 0
89        ? { text: `ktn · ${countsText(d.totals)}` }
90        : { text: "ktn · propre : aucun constat", color: "success" };
91  }
92}
93
94/** What the person can do about the state: a button, a command, a note. */
95export function remedy(els: Els, d: KtnDaemon | undefined, actions: Actions): any[] {
96  if (!d) return [];
97  const out: any[] = [];
98  if (d.kind === "unreachable") {
99    if (d.launching === "starting")
100      out.push(el(els.Text, { dimColor: true }, "démarrage du daemon…"));
101    else if (d.launch === "button" && actions.launch)
102      out.push(
103        el(els.Button, { key: "ktn-launch", label: "Lancer le daemon", onPress: actions.launch }),
104      );
105    if (d.launch === "command" && d.command)
106      out.push(
107        el(els.Text, { dimColor: true }, "à lancer dans un terminal :"),
108        el(els.Code, { source: clean(d.command, 600), language: "sh" }),
109      );
110    if (d.launching === "failed" && d.launchError)
111      out.push(el(els.Text, { color: "error" }, `échec du lancement : ${clean(d.launchError, 300)}`));
112  }
113  if (d.kind === "pending" && d.command)
114    out.push(
115      el(els.Text, { dimColor: true }, "à lancer dans votre propre terminal :"),
116      el(els.Code, { source: clean(d.command, 600), language: "sh" }),
117    );
118  return out;
119}
120
121/**
122 * The band above the prompt: drawn only while there is something to act on
123 * (the daemon to start, an approval to give, a refusal to read). A served
124 * workspace leaves the band to others; the status line says the counts.
125 */
126export function band(els: Els, snap: KtnSnap, actions: Actions): any | undefined {
127  if (snap.activation !== "active") return undefined;
128  const d = snap.daemon;
129  if (!d || d.kind === "ready" || d.kind === "loading") return undefined;
130  const line = stateLine(snap);
131  return el(
132    els.Box,
133    { flexDirection: "column" },
134    el(els.Text, line.color ? { color: line.color, wrap: "truncate-end" } : { wrap: "truncate-end" }, line.text),
135    remedy(els, d, actions),
136  );
137}
138
139/** A drawing that cannot throw: any failure becomes a two-element tree. */
140export function safe(els: Els, draw: () => any): any {
141  try {
142    return draw();
143  } catch (err) {
144    return fallback(els, err);
145  }
146}
147
148export function fallback(els: Els, err: unknown): any {
149  return h(
150    els.Box,
151    { flexDirection: "column" },
152    h(els.Text, { color: "warning" }, "ktn · rendu impossible"),
153    h(els.Text, { dimColor: true }, clean(String((err as any)?.message ?? err), 120)),
154  );
155}
156
157/** "7 · 1E 4W 2I", the severities that have any. */
158export function shortCounts(c: KtnCounts | undefined): string {
159  if (!c) return "";
160  const s = c.severity;
161  const parts = [s.error ? `${s.error}E` : "", s.warning ? `${s.warning}W` : "", s.info ? `${s.info}I` : ""].filter(Boolean);
162  return parts.length ? `${c.findings} · ${parts.join(" ")}` : String(c.findings);
163}
164
165export function phasesText(c: KtnCounts): string {
166  const keys = Object.keys(c.phase).sort((a, b) => Number(a) - Number(b));
167  return keys.length ? `phases ${keys.map((k) => `${k}:${c.phase[k]}`).join(" ")}` : "";
168}
169
170export function ago(ms: number): string {
171  const s = Math.max(0, Math.round(ms / 1000));
172  if (s < 60) return `${s} s`;
173  const m = Math.round(s / 60);
174  return m < 60 ? `${m} min` : `${Math.round(m / 60)} h`;
175}
176
177const SEVERITY_COLOR: Record<string, string> = { error: "error", warning: "warning" };
178
179/** One row of the tree: a pressable directory or file, or a finding. */
180function row(els: Els, n: KtnNode, actions: Actions): { tree: any; size: number } {
181  const indent = "  ".repeat(Math.min(n.depth, 32));
182  if (n.kind === "finding") {
183    const text = `${indent}L${n.line ?? 0} ${n.rule ?? ""} ${n.message ?? ""}`;
184    const color = SEVERITY_COLOR[n.severity ?? ""];
185    const label = el(els.Text, color ? { color, wrap: "truncate-end" } : { dimColor: true, wrap: "truncate-end" }, text);
186    // Pressed: its detail above the tree (#787)
187    if (actions.inspect)
188      return {
189        tree: el(els.Button, { key: n.id, plain: true, onPress: () => actions.inspect?.(n.id) }, label),
190        size: text.length,
191      };
192    return { tree: label, size: text.length };
193  }
194  const mark = n.expanded ? "▾" : "▸";
195  const label = `${indent}${mark} ${n.name}${n.kind === "dir" && n.name !== "." ? "/" : ""}`;
196  const counts = shortCounts(n.counts);
197  // The root is always open: drawn, never pressed
198  if (n.id === "dir:.")
199    return { tree: el(els.Text, { bold: true, wrap: "truncate-end" }, `${label}  ${counts}`), size: label.length + counts.length };
200  return {
201    tree: el(
202      els.Button,
203      { key: n.id, plain: true, onPress: () => actions.toggle?.(n.id) },
204      label,
205      "  ",
206      el(els.Text, { dimColor: true }, counts),
207    ),
208    size: label.length + counts.length + 2,
209  };
210}
211
212export type PaneData = {
213  snap: KtnSnap;
214  tree?: KtnTree;
215  /** The link the person minted, held by the module alone. */
216  link?: { url: string; label: string };
217  now: number;
218  /**
219   * The windowed mode (#787): the first row the mod shows and the rows of
220   * THIS render's body (`e.props.scroll.bodyRows`). Absent: the engine
221   * scrolls the whole tree natively (#777).
222   */
223  window?: { offset: number; bodyRows: number };
224  /** The severities shown, empty for all (#787). */
225  filter?: string[];
226  /** The id of the finding whose detail is shown (#787). */
227  detail?: string;
228  /** Told the rows the windowed render gave the tree (its body less its head). */
229  onLayout?: (rows: number) => void;
230};
231
232// --- the windowed mode (kodflow/ktn-linter#787) -------------------------------
233//
234// The daemon serves a window of WINDOW_ROWS nodes from `from`; the pane draws
235// [offset, offset + rows) of the whole tree, `rows` being THIS render's body
236// less the head. One instance is evaluated per surface with its own rows,
237// and `ui.scroll` carries neither the surface nor the other surface's rows:
238// the offset is one value, and every render re-clamps it to its own rows.
239
240/** The last first row a window of `rows` rows may show over `total`. */
241export function maxOffset(total: number, rows: number): number {
242  return Math.max(0, Math.floor(total) - Math.max(1, Math.floor(rows)));
243}
244
245/** `offset` brought inside [0, maxOffset]; anything not a number is 0. */
246export function clampOffset(offset: number, total: number, rows: number): number {
247  const o = Number.isFinite(offset) ? Math.floor(offset) : 0;
248  return Math.min(Math.max(0, o), maxOffset(total, rows));
249}
250
251/**
252 * `ui.scroll`: the offset moved by `by` rows, clamped with the snapshot's
253 * total — never `e.contentRows`, which counts only the rows drawn.
254 */
255export function scrolled(offset: number, by: number, total: number, rows: number): number {
256  return clampOffset((Number.isFinite(offset) ? offset : 0) + (Number.isFinite(by) ? by : 0), total, rows);
257}
258
259/**
260 * The window to ask for next, or undefined while [offset, offset + rows)
261 * stays more than WINDOW_EDGE rows inside what the snapshot holds. The new
262 * window is centred on what the person looks at, over the span a window
263 * actually keeps: WINDOW_ROWS, or fewer once capWindow cut it — centring
264 * on WINDOW_ROWS then would ask again for the window held, and the rows
265 * past the cut would stay "…".
266 */
267export function nextWindow(tree: KtnTree | undefined, offset: number, rows: number): number | undefined {
268  if (!tree) return undefined;
269  const from = tree.from ?? 0;
270  const held = tree.nodes.length;
271  const total = tree.total ?? from + held;
272  const nearTop = from > 0 && offset < from + WINDOW_EDGE;
273  const nearEnd = from + held < total && offset + rows > from + held - WINDOW_EDGE;
274  if (!nearTop && !nearEnd) return undefined;
275  const span = Math.min(WINDOW_ROWS, Math.max(1, held));
276  const centred = offset - Math.floor(Math.max(0, span - rows) / 2);
277  const next = Math.min(Math.max(0, centred), Math.max(0, total - span));
278  return next === from ? undefined : next;
279}
280
281/** The text a node weighs in the snapshot, as the engine counts characters. */
282const weight = (n: KtnNode) => n.id.length + n.name.length + (n.rule?.length ?? 0) + (n.message?.length ?? 0) + 16;
283
284/**
285 * The nodes the snapshot keeps: the window as served, cut once its text
286 * passes WINDOW_MAX_CHARS — `$.state` is re-read on every render, so on
287 * every wheel tick, and the worker every mod shares pays for its size.
288 */
289export function capWindow(nodes: KtnNode[], maxChars = WINDOW_MAX_CHARS): KtnNode[] {
290  let used = 0;
291  let i = 0;
292  for (; i < nodes.length; i++) {
293    used += weight(nodes[i]!);
294    if (used > maxChars) break;
295  }
296  return i === nodes.length ? nodes : nodes.slice(0, i);
297}
298
299/** The detail of the finding `id`, drawn above the tree. */
300function detailOf(els: Els, n: KtnNode, actions: Actions): any {
301  const file = n.parent?.startsWith("file:") ? n.parent.slice(5) : "?";
302  return el(
303    els.Box,
304    { flexDirection: "column" },
305    el(els.Text, { bold: true, wrap: "truncate-end" }, `${n.rule ?? "?"} · ${n.severity ?? "?"} · phase ${n.phase ?? "?"}`),
306    el(els.Code, { source: clean(`${file}:${n.line ?? 0}`, 1_100), language: "text" }),
307    el(els.Text, null, n.message ?? ""),
308    actions.inspect ? el(els.Button, { key: "ktn-detail-close", label: "Fermer le détail", onPress: () => actions.inspect?.(n.id) }) : null,
309  );
310}
311
312/** How many rows a head element takes: a detail block counts its lines. */
313const headRows = (head: any[]) => head.reduce((s, h) => s + (h?.props?.flexDirection === "column" ? 4 : 1), 0);
314
315/**
316 * The pane: the synthesis first (the state, the workspace, the totals by
317 * severity and by phase, how long since the last answer, the launch button
318 * when the daemon is down), then the collapsible tree as the daemon served
319 * it — directories folded with their counts, the children of the opened ones
320 * only. The pane does not window the tree: the engine scrolls it, and the
321 * daemon bounds it (`truncated`, then "… voir l'UI web"). Its rows stop at a
322 * text budget below the engine's 100 000 characters, saying what was left.
323 */
324export function pane(els: Els, data: PaneData, actions: Actions): any {
325  const { snap } = data;
326  const line = stateLine(snap);
327  const head: any[] = [
328    el(els.Text, line.color ? { color: line.color, wrap: "truncate-end" } : { bold: true, wrap: "truncate-end" }, line.text),
329  ];
330  if (snap.activation !== "active") return el(els.Box, { flexDirection: "column" }, head);
331  const d = snap.daemon;
332  if (snap.workspace) head.push(el(els.Text, { dimColor: true, wrap: "truncate-start" }, clean(snap.workspace, 300)));
333  if (d?.kind === "ready" && d.totals) {
334    const p = phasesText(d.totals);
335    if (p) head.push(el(els.Text, { dimColor: true, wrap: "truncate-end" }, p));
336    const age = d.at ? `actualisé il y a ${ago(data.now - d.at)}` : "";
337    const engine = d.engine ? `moteur ${clean(d.engine, 30)}` : "";
338    if (age || engine) head.push(el(els.Text, { dimColor: true }, [age, engine].filter(Boolean).join(" · ")));
339  }
340  head.push(...remedy(els, d, actions));
341  if (d?.kind === "ready" && actions.openUi) {
342    head.push(
343      data.link
344        ? el(els.Link, { href: data.link.url, label: data.link.label })
345        : el(els.Button, { key: "ktn-open-ui", label: "Ouvrir l'UI web", onPress: actions.openUi }),
346    );
347  }
348  const t = d?.kind === "ready" ? data.tree : undefined;
349  const filter = (data.filter ?? []).filter((s) => typeof s === "string");
350  if (filter.length > 0)
351    head.push(el(els.Text, { dimColor: true, wrap: "truncate-end" }, `filtre : ${clean(filter.join(", "), 60)}`));
352  const shown = data.detail && t ? t.nodes.find((n) => n.id === data.detail && n.kind === "finding") : undefined;
353  if (shown) head.push(detailOf(els, shown, actions));
354  if (data.window && t && t.workspace === snap.workspace)
355    return windowed(els, head, t, data.window, actions, data.onLayout);
356  const rows: any[] = [];
357  if (t && t.workspace === snap.workspace) {
358    let used = 0;
359    let left = 0;
360    for (const n of t.nodes) {
361      if (used >= RENDER_BUDGET) {
362        left++;
363        continue;
364      }
365      const r = row(els, n, actions);
366      used += r.size;
367      rows.push(r.tree);
368    }
369    const more = left + (t.truncated ? t.hidden : 0);
370    if (more > 0 || t.truncated)
371      rows.push(el(els.Text, { dimColor: true }, `… ${more > 0 ? `${more} de plus, ` : ""}voir l'UI web`));
372  }
373  return el(els.Box, { flexDirection: "column" }, head, rows);
374}
375
376/**
377 * The windowed tree: the head, then the rows [offset, offset + rows) of the
378 * whole tree, re-clamped to THIS render's rows, plus one spare row so the
379 * engine always has a row to scroll — and therefore raises `ui.scroll` for
380 * the wheel and the arrows, which the mod answers with its own offset. A
381 * row the snapshot does not hold yet draws as "…", never as a gap.
382 */
383function windowed(
384  els: Els,
385  head: any[],
386  t: KtnTree,
387  w: { offset: number; bodyRows: number },
388  actions: Actions,
389  onLayout?: (rows: number) => void,
390): any {
391  const from = t.from ?? 0;
392  const total = Math.max(t.total ?? from + t.nodes.length, 0);
393  const bodyRows = Number.isFinite(w.bodyRows) ? Math.max(0, Math.floor(w.bodyRows)) : 0;
394  // The position line is a row of the head too
395  const rows = Math.max(0, bodyRows - headRows(head) - (total > 0 ? 1 : 0));
396  const offset = clampOffset(w.offset, total, rows);
397  onLayout?.(rows);
398  if (total > 0)
399    head.push(el(els.Text, { dimColor: true }, `lignes ${offset + 1}–${Math.min(offset + Math.max(rows, 1), total)} sur ${total}`));
400  const out: any[] = [];
401  let used = 0;
402  const end = Math.min(total, offset + rows + 1);
403  for (let i = offset; i < end && used < RENDER_BUDGET; i++) {
404    const n = t.nodes[i - from];
405    if (!n) {
406      out.push(el(els.Text, { dimColor: true }, "…"));
407      used += 1;
408      continue;
409    }
410    const r = row(els, n, actions);
411    used += r.size;
412    out.push(r.tree);
413  }
414  return el(els.Box, { flexDirection: "column" }, head, out);
415}
416
hooks/mod/daemon.ts 194 lines
1// daemon.ts — what the daemon's answers mean, read defensively. Pure.
2//
3// The spike of kodflow/ktn-linter#774 measured how each failure reaches a mod
4// through `$.http.fetch`, and the states are told apart by that shape:
5//
6//   daemon absent         rejected: ECONNREFUSED (TCP) or ENOENT (socket)
7//   daemon silent         rejected at 30 s: "aborted … no complete answer"
8//                         (the mod's own race fires first, at wait + 5 s)
9//   HTTP error            resolved, ok:false
10//   invalid JSON          resolved; JSON.parse throws IN THE MOD
11//   answer too big        rejected: "over the 4194304-byte limit"
12//   socket path refused   rejected: "… refused: takes an absolute path"
13//   refused by a policy   rejected with the refusal's own text (a hook's
14//   or another plugin     `{ deny }` or the organization's web-fetch policy)
15//
16// The last one is NOT "daemon unreachable": offering to launch a daemon the
17// session is not allowed to reach would only fail again.
18import type { KtnCounts, KtnModel, KtnNode } from "../../types";
19import { MAX_BODY_CHARS, MAX_NODES, NOT_SERVED, PROTOCOL_VERSION } from "./contract.ts";
20import { clean, isPlain } from "./sanitize.ts";
21
22export type Failure =
23  | { kind: "absent"; detail: string }
24  | { kind: "silent"; detail: string }
25  | { kind: "broken"; detail: string }
26  | { kind: "policy"; detail: string };
27
28// A transport failure's own words, as the engine and the OS spell them
29const TRANSPORT = [
30  "ECONNREFUSED",
31  "ENOENT",
32  "ECONNRESET",
33  "EPIPE",
34  "EACCES",
35  "ENOTSOCK",
36  "ETIMEDOUT",
37  "EHOSTUNREACH",
38  "socket hang up",
39];
40
41/** A rejected fetch, by its message. */
42export function classifyRejection(err: unknown): Failure {
43  const msg = String((err as any)?.message ?? err);
44  const detail = clean(msg, 200);
45  if (msg.includes("no complete answer") || msg.includes("aborted"))
46    return { kind: "silent", detail: "le daemon ne répond pas" };
47  if (msg.includes("-byte limit"))
48    return { kind: "broken", detail: "réponse trop grosse" };
49  if (msg.includes("takes an absolute path"))
50    return { kind: "broken", detail: "chemin de socket refusé" };
51  for (const word of TRANSPORT)
52    if (msg.includes(word)) return { kind: "absent", detail };
53  return { kind: "policy", detail };
54}
55
56/** JSON.parse that answers undefined instead of throwing, and refuses a body too big to parse. */
57export function parseJson(text: unknown): unknown {
58  if (typeof text !== "string" || text.length > MAX_BODY_CHARS) return undefined;
59  try {
60    return JSON.parse(text);
61  } catch {
62    return undefined;
63  }
64}
65
66const num = (v: unknown): number =>
67  typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0;
68
69// "1" to "99": a phase number as the daemon keys it
70const isPhaseKey = (k: string): boolean =>
71  k.length >= 1 && k.length <= 2 && [...k].every((c) => c >= "0" && c <= "9");
72
73export function countsOf(raw: any): KtnCounts {
74  const sev = raw && typeof raw === "object" ? raw.severity : undefined;
75  const phase: Record<string, number> = {};
76  const p = raw && typeof raw === "object" ? raw.phase : undefined;
77  if (p && typeof p === "object")
78    for (const k of Object.keys(p).slice(0, 16))
79      if (isPhaseKey(k)) phase[k] = num(p[k]);
80  return {
81    findings: num(raw?.findings),
82    severity: {
83      error: num(sev?.error),
84      warning: num(sev?.warning),
85      info: num(sev?.info),
86    },
87    phase,
88  };
89}
90
91const KINDS = new Set(["dir", "file", "finding"]);
92
93function nodeOf(raw: any): KtnNode | undefined {
94  if (!raw || typeof raw !== "object") return undefined;
95  // An id goes back to the daemon as it came (expand=): never altered, so
96  // one with a control character or past any sane length is dropped instead
97  if (!isPlain(raw.id, 1_100) || !KINDS.has(raw.kind)) return undefined;
98  const node: KtnNode = {
99    id: raw.id,
100    kind: raw.kind,
101    name: clean(raw.name, 200),
102    depth: Math.min(num(raw.depth), 64),
103    expanded: raw.expanded === true,
104  };
105  if (isPlain(raw.parent, 1_100)) node.parent = raw.parent;
106  if (raw.kind === "finding") {
107    node.line = num(raw.line);
108    node.rule = clean(raw.rule, 80);
109    node.severity = clean(raw.severity, 16);
110    node.phase = num(raw.phase);
111    node.message = clean(raw.message, 200);
112  } else node.counts = countsOf(raw.counts);
113  return node;
114}
115
116export type ModelRead =
117  | { ok: true; model: KtnModel }
118  | { ok: false; incompatible?: string; detail: string };
119
120/** An /api/view answer of 200, read field by field; never a throw. */
121export function parseModel(text: string): ModelRead {
122  if (text.length > MAX_BODY_CHARS)
123    return { ok: false, detail: "réponse trop grosse" };
124  const raw: any = parseJson(text);
125  if (!raw || typeof raw !== "object")
126    return { ok: false, detail: "réponse illisible (JSON invalide)" };
127  if (raw.schema !== PROTOCOL_VERSION)
128    return {
129      ok: false,
130      incompatible: clean(String(raw.schema), 20),
131      detail: "schéma du modèle inconnu",
132    };
133  const rawNodes: unknown[] = Array.isArray(raw.tree?.nodes) ? raw.tree.nodes : [];
134  const nodes: KtnNode[] = [];
135  for (const n of rawNodes) {
136    if (nodes.length >= MAX_NODES) break;
137    const node = nodeOf(n);
138    if (node) nodes.push(node);
139  }
140  const total = num(raw.window?.total);
141  return {
142    ok: true,
143    model: {
144      rev: num(raw.rev),
145      workspace: clean(raw.workspace, 300),
146      state: clean(raw.state, 30),
147      totals: countsOf(raw.totals),
148      nodes,
149      // Cut by the server or by us: the rest is the web UI's
150      truncated: raw.truncated === true || rawNodes.length > nodes.length,
151      hidden: Math.max(0, total - nodes.length),
152      from: num(raw.window?.offset),
153      total: Math.max(total, nodes.length),
154    },
155  };
156}
157
158export type StatusRead =
159  | { ok: true; protocol: string; pending?: { reason: string; command: string } }
160  | { ok: false; detail: string };
161
162/**
163 * /status: the protocol it speaks and, when the workspace waits for the
164 * person's approval, the exact command the daemon says to run.
165 */
166export function parseStatus(text: string, workspace: string): StatusRead {
167  const raw: any = parseJson(text);
168  if (!raw || typeof raw !== "object")
169    return { ok: false, detail: "réponse illisible (JSON invalide)" };
170  const protocol = typeof raw.protocol_version === "string" ? raw.protocol_version : "";
171  const list: any[] = Array.isArray(raw.pending_workspaces) ? raw.pending_workspaces : [];
172  const hit = list.find((p) => p && p.root === workspace);
173  return {
174    ok: true,
175    protocol: clean(protocol, 20),
176    pending: hit
177      ? { reason: clean(hit.reason, 200), command: clean(hit.command, 600) }
178      : undefined,
179  };
180}
181
182/** The reason in a refusal's body: the typed error's message, or its text. */
183export function refusalOf(text: string): string {
184  const raw: any = parseJson(text);
185  const msg = raw?.error?.message;
186  return clean(typeof msg === "string" ? msg : text, 200).trim();
187}
188
189export function isNotServed(status: number, text: string): boolean {
190  if (status === 403) return text.includes("is not served");
191  if (status === 404) return (parseJson(text) as any)?.error?.code === NOT_SERVED;
192  return false;
193}
194
hooks/mod/endpoint.ts 62 lines
1// endpoint.ts — where the per-user daemon is, read from the ONE discovery
2// anchor ktn-linter writes for its clients: endpoint.json under HOME (#757,
3// pkg/daemonctl `EndpointValue`). Pure.
4//
5// The socket path is never computed here: it depends on the runtime directory
6// and the environment, and a second resolver in JS would agree with the Go one
7// on one platform out of three. The pointer names it; the mod reads it.
8// state.json is not a source either: a clean stop removes it, which is exactly
9// when the launch button has to appear.
10import { ANCHORS, ENDPOINT_SCHEMA, SOCKET_MAX_BYTES } from "./contract.ts";
11
12export type Endpoint = {
13  socket: string;
14  /** The absolute binary the launcher starts; "" when the pointer has none. */
15  exe: string;
16  version: string;
17};
18
19export type EndpointRead =
20  | { ok: true; endpoint: Endpoint }
21  | { ok: false; reason: string };
22
23/** The anchors to try, in order, under an absolute HOME. */
24export function anchorPaths(home: string | undefined): string[] {
25  if (!home || !home.startsWith("/")) return [];
26  const base = home.endsWith("/") ? home.slice(0, -1) : home;
27  return ANCHORS.map((rel) => `${base}/${rel}`);
28}
29
30const utf8Length = (s: string) => new TextEncoder().encode(s).length;
31
32/** Reads endpoint.json's text; every failure is a reason, never a throw. */
33export function parseEndpoint(text: string): EndpointRead {
34  let raw: any;
35  try {
36    raw = JSON.parse(text);
37  } catch {
38    return { ok: false, reason: "endpoint.json illisible (JSON invalide)" };
39  }
40  if (!raw || typeof raw !== "object")
41    return { ok: false, reason: "endpoint.json illisible" };
42  if (raw.schema !== ENDPOINT_SCHEMA)
43    return {
44      ok: false,
45      reason: `endpoint.json de schéma ${String(raw.schema)}, ${ENDPOINT_SCHEMA} attendu`,
46    };
47  const socket = raw.socket;
48  if (typeof socket !== "string" || !socket.startsWith("/") || socket.includes("\0"))
49    return { ok: false, reason: "endpoint.json sans socket absolu" };
50  if (utf8Length(socket) > SOCKET_MAX_BYTES)
51    return {
52      ok: false,
53      reason: `socket trop long (${utf8Length(socket)} octets, ${SOCKET_MAX_BYTES} au plus)`,
54    };
55  const exe =
56    typeof raw.exe === "string" && raw.exe.startsWith("/") && !raw.exe.includes("\0")
57      ? raw.exe
58      : "";
59  const version = typeof raw.version === "string" ? raw.version : "";
60  return { ok: true, endpoint: { socket, exe, version } };
61}
62
hooks/mod/sanitize.ts 33 lines
1// sanitize.ts — every string that came from the daemon (paths, messages,
2// rules, the command it suggests) passes here before it is drawn. Pure.
3//
4// The daemon already sanitises (pkg/view `Sanitize`); this is the client's own
5// guard, so a daemon of another version, or something else listening on the
6// socket, cannot move the cursor or recolour the terminal. A plain loop over
7// code points: no regular expression ever runs on external data.
8
9/** C0 (tab and newline included), DEL and C1 become a space; cut at `max`. */
10export function clean(input: unknown, max = 300): string {
11  if (typeof input !== "string") return "";
12  let out = "";
13  let n = 0;
14  for (const ch of input) {
15    if (n >= max) return out + "…";
16    const c = ch.codePointAt(0)!;
17    out += c < 0x20 || (c >= 0x7f && c <= 0x9f) ? " " : ch;
18    n++;
19  }
20  return out;
21}
22
23/** Whether a string is safe to send back as is (an id, a path): no control. */
24export function isPlain(input: unknown, max: number): input is string {
25  if (typeof input !== "string" || input.length === 0 || input.length > max)
26    return false;
27  for (let i = 0; i < input.length; i++) {
28    const c = input.charCodeAt(i);
29    if (c < 0x20 || (c >= 0x7f && c <= 0x9f)) return false;
30  }
31  return true;
32}
33
types/index.d.ts 149 lines
1// The values kodflow-ktn keeps in `$.state` for the session. `$.state` is
2// the DISPLAY copy: every transition writes the module's own variable first
3// (the fast source, lost on a reload) and then this snapshot (what the
4// drawings subscribe to, kept across a hot reload). Any plugin may read any
5// value here, so nothing secret is ever written: no token, no credential.
6
7/**
8 * Where the mod stands in this session:
9 *   inert         nothing draws here (`-p`, the Agent SDK, Kepler's launch
10 *                 mode): no probe, no daemon call, nothing opened;
11 *   floor         Claude Code older than the version the mod was measured on;
12 *   probing       the activation probe is under way;
13 *   active        a Go project (or `activation: always`);
14 *   inactive      not a Go project (or `activation: off`);
15 *   undetermined  the probe ran out of budget: drawn as inactive.
16 */
17export type KtnActivation =
18  | "inert"
19  | "floor"
20  | "probing"
21  | "active"
22  | "inactive"
23  | "undetermined";
24
25/** Findings counted in total, by effective severity and by phase. */
26export type KtnCounts = {
27  findings: number;
28  severity: { error: number; warning: number; info: number };
29  /** By phase number, as the daemon keys it ("1" to "9"). */
30  phase: Record<string, number>;
31};
32
33/** One node of the view model (pkg/view): a directory, a file or a finding. */
34export type KtnNode = {
35  /** Stable: dir:<path>, file:<path>, finding:<fingerprint>. */
36  id: string;
37  kind: "dir" | "file" | "finding";
38  name: string;
39  parent?: string;
40  depth: number;
41  expanded: boolean;
42  counts?: KtnCounts;
43  line?: number;
44  rule?: string;
45  severity?: string;
46  phase?: number;
47  message?: string;
48};
49
50/** What one /api/view answer said, cut to what the mod draws. */
51export type KtnModel = {
52  rev: number;
53  workspace: string;
54  /** The engine's lifecycle state, "idle" before any engine serves it. */
55  state: string;
56  totals: KtnCounts;
57  nodes: KtnNode[];
58  /** The server's window stopped short, or the mod cut it. */
59  truncated: boolean;
60  /** Visible nodes not in this window: the web UI's to show. */
61  hidden: number;
62  /** The window's first node, as the daemon served it (pkg/view `window.offset`). */
63  from: number;
64  /** Every visible node of the tree, the window's included (`window.total`). */
65  total: number;
66};
67
68/**
69 * The daemon, as the mod sees it — the seven drawn states of #776 are
70 * `activation` not active (out of a Go project) and these:
71 *   loading       no answer yet;
72 *   unreachable   no endpoint.json, nothing on the socket, a silent or
73 *                 broken daemon;
74 *   incompatible  another protocol: no further call until endpoint.json moves;
75 *   pending       the workspace waits for the person's approval (the command);
76 *   refused       the daemon does not serve it (its reason);
77 *   policy        the request was refused before it left (an organization's
78 *                 policy, a hook): distinct from unreachable, no launch offered;
79 *   ready         served: clean when `totals.findings` is 0.
80 */
81export type KtnDaemonKind =
82  | "loading"
83  | "unreachable"
84  | "incompatible"
85  | "pending"
86  | "refused"
87  | "policy"
88  | "ready";
89
90export type KtnDaemon = {
91  kind: KtnDaemonKind;
92  /** Why, in the daemon's or the transport's words, sanitised. */
93  detail?: string;
94  /** A command for the person to run: the approval, or the launch. */
95  command?: string;
96  /** What is offered to start the daemon: a button, a command, or nothing. */
97  launch: "button" | "command" | "none";
98  launching?: "starting" | "failed";
99  launchError?: string;
100  /** The ktn-linter version endpoint.json names. */
101  version?: string;
102  totals?: KtnCounts;
103  /** The engine's lifecycle state. */
104  engine?: string;
105  /** When the last answer came, milliseconds since the epoch. */
106  at?: number;
107};
108
109export type KtnSnap = {
110  activation: KtnActivation;
111  /** The session's project root the probe walked from. */
112  root?: string;
113  /** The root the daemon is asked about (the module root, else the git root). */
114  workspace?: string;
115  daemon?: KtnDaemon;
116};
117
118/** The pane's tree: the window of the view model the last answer served. */
119export type KtnTree = {
120  workspace: string;
121  nodes: KtnNode[];
122  truncated: boolean;
123  hidden: number;
124  /** The index of `nodes[0]` in the whole tree (the windowed mode, #787). */
125  from?: number;
126  /** Every visible node of the tree (the windowed mode, #787). */
127  total?: number;
128};
129
130declare module "claude-code" {
131  interface PluginState {
132    "kodflow-ktn": {
133      snap: KtnSnap;
134      /** The pane's tree; absent until a model was served. */
135      tree: KtnTree;
136      /** The dir: and file: ids the person opened in the pane. No secret. */
137      expanded: string[];
138      /**
139       * The first row of the tree the windowed pane shows (#787): ONE value
140       * for the instance, shared by every surface that draws it — each
141       * render re-clamps it to its own rows, so a surface draws at a time.
142       */
143      offset: number;
144      /** The severities the pane shows; empty for all of them (#787). */
145      filter: string[];
146    };
147  }
148}
149