pi-evals 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - New command `/ask-ai <question>` has the agent answer you now instead of taking the question as a reproach and starting new work. The question goes in with a short instruction: answer first, in your language, change nothing, start no work, and end with at most one line of suggested next step. While that run lasts (until it ends or you send another message), `write`, `edit`, `subagent`, `boss_pair`, `MonitorCreate`, `LoopCreate`, `call_tower`, `todo` (except `list`/`get`) and `intercom` (`send`/`ask`/`handover`) are refused with a one-line reason; `bash`, `read` and other tools still run.
6
+ - Each ask is recorded in `asks.jsonl` (session, time, project, todo item; never the question or the answer). The report's 「你的標記」 section and the `labels` query view say how many times you asked and how many you followed with a label in the same session within 30 minutes.
7
+
8
+ ## 0.5.2
9
+
10
+ - A later human label on the same session, rule and item replaces the earlier one in the report and agreement; `labels.jsonl` keeps both. New `source: "recheck"` for your second look at a label given after the fact (counted as 事後標). Each 「其他」 label stays its own event, and agent corrections are never replaced.
11
+
3
12
  ## 0.5.1
4
13
 
5
14
  - The two anchor checks read the forms agents actually use, checked against 30 sessions you labelled by hand. An anchor counts when the agent or its brief names the check before the first edit: an `Anchor:` line, a `Gates:`, `Checks:`, `Verify:`, `Done when` or `驗證:` line, a todo anchor or sb check spec, or a check command named in the brief. It also counts when the first change is a test file (red first). A brief's anchor is no longer failed as `anchor_only_in_brief`.
package/README.md CHANGED
@@ -55,6 +55,23 @@ The observer loads in every session, subagents included.
55
55
  A label records the session, the time, and the key of the todo item in progress, if any (its `uid`, else `<session>#<id>`, as work items are keyed).
56
56
  It reaches the report and `evals_query` at their next read, without an extract.
57
57
 
58
+ ### `/ask-ai`: get an answer before the agent acts
59
+
60
+ | Command | What it does |
61
+ | --- | --- |
62
+ | `/ask-ai <your question>` | Has the agent answer your question now, e.g. `/ask-ai 你剛剛有照並行設計流程嗎?`. With no question it shows the usage. |
63
+
64
+ Sometimes an agent hears a question as a reproach and starts re-planning, so the moment to label how it worked passes.
65
+ `/ask-ai` sends your question with a short instruction: answer first, in your language; read only what the answer needs; change nothing, start no work and dispatch nothing; if the question is about how it worked, say what happened and whether that followed the rule; end with at most one line of suggested next step, and wait.
66
+ If the agent is working, the question goes in after its current tool calls.
67
+
68
+ Until that run ends, or you send another message, these tools are refused with a one-line reason telling the agent to answer first: `write`, `edit`, `subagent`, `boss_pair`, `MonitorCreate`, `LoopCreate`, `call_tower`, `todo` (except `list` and `get`), and `intercom` (`send`, `ask` and `handover`).
69
+ `bash`, `read` and every other tool still run, so the agent can look things up.
70
+ Only you can type the command; agents cannot call it.
71
+
72
+ pi-evals records only that you asked (session, time, project and the todo item in progress), never the question or the answer.
73
+ The report's 「你的標記」 section says how many times you asked and how many of those you followed with a label in the same session within 30 minutes.
74
+
58
75
  The same operations run from a shell, where extraction defaults to one fewer worker than available CPUs (at least one, at most eight).
59
76
  On either surface, `--workers 0` reads the files sequentially without worker threads:
60
77
 
@@ -141,6 +158,7 @@ Use the section links for usage, process checks, cost and cleanup coverage, or r
141
158
  | `index/lines.json` | Cached `git diff --numstat` line counts between evidence commits. |
142
159
  | `changes.jsonl`, `marks.jsonl` | The change timeline and your notes. |
143
160
  | `labels.jsonl` | Your labels and agents' corrections, appended one per line ([docs/schema.md](docs/schema.md#labels)). The report shows how often you and the automatic checks agree, split by labels given after the fact and in the moment; `unclear` labels are counted apart. Its 「被糾正」 section counts the corrections by rule, failure type, skill loaded and anchorloop version. |
161
+ | `asks.jsonl` | One row per `/ask-ai`: session, time, project and todo item, without the question ([docs/schema.md](docs/schema.md#asks)). |
144
162
  | `reports/report.html`, `reports/model.json` | The report. |
145
163
 
146
164
  The record format is in [docs/schema.md](docs/schema.md); the decisions behind it are in [docs/design.md](docs/design.md).
package/dist/ask-ai.js ADDED
@@ -0,0 +1,58 @@
1
+ import { appendAsk } from "./asks.js";
2
+ import { itemOnBranch } from "./labels.js";
3
+ import { context } from "./ops.js";
4
+ import { projectKey } from "./project.js";
5
+ import { turnWindow } from "./turn-window.js";
6
+ const always = () => true;
7
+ /** Tools refused during an `/ask-ai` turn, each with the inputs it is refused for; any other tool runs. */
8
+ export const ASK_AI_BLOCKED = {
9
+ write: always,
10
+ edit: always,
11
+ subagent: always,
12
+ boss_pair: always,
13
+ MonitorCreate: always,
14
+ LoopCreate: always,
15
+ call_tower: always,
16
+ todo: (input) => input.action !== "list" && input.action !== "get",
17
+ intercom: (input) => input.action === "send" || input.action === "ask" || input.action === "handover",
18
+ };
19
+ const USAGE = "pi-evals 用法:/ask-ai <你的問題>,代理人會先直接回答,不改任何東西、不開始新工作。";
20
+ /** The question, last and verbatim, after the instruction to answer it now and do nothing else. */
21
+ export function askPrompt(question) {
22
+ return [
23
+ "[/ask-ai] Answer the user's question below now, directly and first, in the user's language. Read only what you need to answer; change nothing, start no work, dispatch nothing. If it asks how you worked, say plainly what happened and whether it followed the rule. End with at most one line of suggested next step, then wait for the user.",
24
+ "",
25
+ `Question: ${question}`,
26
+ ].join("\n");
27
+ }
28
+ export function askAi(pi, options) {
29
+ const { env, now } = options;
30
+ const asking = turnWindow(pi);
31
+ pi.on("tool_call", (event, ctx) => {
32
+ const { toolName, input } = event;
33
+ const refuse = Object.hasOwn(ASK_AI_BLOCKED, toolName) ? ASK_AI_BLOCKED[toolName] : undefined;
34
+ if (!refuse || !refuse(input ?? {}) || !asking.current(ctx.sessionManager.getSessionId()))
35
+ return undefined;
36
+ return { block: true, reason: `Refused during /ask-ai: answer the user's question first, change nothing and start no work; ${toolName} can run after the user replies.` };
37
+ });
38
+ pi.registerCommand("ask-ai", {
39
+ description: "Ask the agent a question and have it answer now, without starting work: /ask-ai <question>",
40
+ handler: async (args, ctx) => {
41
+ const question = args.trim();
42
+ if (!question)
43
+ return ctx.ui.notify(USAGE, "warning");
44
+ const c = context(env);
45
+ const session = ctx.sessionManager.getSessionId();
46
+ let branch;
47
+ try {
48
+ branch = ctx.sessionManager.getBranch?.();
49
+ }
50
+ catch { }
51
+ appendAsk(c.layout.asks, { session_id: session, at: new Date(now()).toISOString(), kind: "ask_ai", project: projectKey(ctx.cwd, c.home), item: itemOnBranch(branch, session) });
52
+ const prompt = askPrompt(question);
53
+ asking.arm({ session, prompt, data: undefined });
54
+ // While the agent works, the question goes in after its current tool calls, not after the whole run.
55
+ pi.sendUserMessage(prompt, ctx.isIdle() ? undefined : { deliverAs: "steer" });
56
+ },
57
+ });
58
+ }
package/dist/asks.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * `asks.jsonl` (append-only): one row per `/ask-ai`, when and where it was asked. Never the question or the answer.
3
+ * The report counts them and how many were followed by a label in the same session within 30 minutes.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+ import { readLabels } from "./labels.js";
8
+ import { traceId } from "./schema.js";
9
+ /** How long after an ask a label in the same session counts as following it. */
10
+ export const ASK_LABEL_WINDOW_MS = 30 * 60 * 1000;
11
+ export function appendAsk(file, row) {
12
+ mkdirSync(dirname(file), { recursive: true });
13
+ appendFileSync(file, `${JSON.stringify(row)}\n`);
14
+ }
15
+ export function readAsks(file) {
16
+ if (!existsSync(file))
17
+ return [];
18
+ return readFileSync(file, "utf8")
19
+ .split("\n")
20
+ .filter(Boolean)
21
+ .flatMap((line) => {
22
+ try {
23
+ const row = JSON.parse(line);
24
+ return row && row.kind === "ask_ai" && typeof row.session_id === "string" && typeof row.at === "string" ? [row] : [];
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ });
30
+ }
31
+ /**
32
+ * Asks in scope (a session in the index belongs by its start; one not indexed yet by the ask's own time and project),
33
+ * and how many a human label in the same session followed within `ASK_LABEL_WINDOW_MS`.
34
+ */
35
+ export function asksModel(asksFile, labelsFile, scope) {
36
+ if (!asksFile)
37
+ return { n: 0, labelled: 0 };
38
+ const inDates = (at) => (!scope.since || at.slice(0, 10) >= scope.since) && (!scope.until || at.slice(0, 10) <= scope.until);
39
+ const asks = readAsks(asksFile).filter((r) => {
40
+ if (!scope.selected)
41
+ return true;
42
+ const id = traceId(r.session_id, "labels");
43
+ return scope.selected.has(id) || (!scope.indexed?.has(id) && inDates(r.at) && (!scope.project || r.project === scope.project));
44
+ });
45
+ if (!asks.length)
46
+ return { n: 0, labelled: 0 };
47
+ const labels = readLabels(labelsFile).filter((l) => l.annotator !== "agent" && typeof l.at === "string");
48
+ const labelled = asks.filter((a) => {
49
+ const t = Date.parse(a.at);
50
+ return labels.some((l) => l.session_id === a.session_id && Date.parse(l.at) >= t && Date.parse(l.at) - t <= ASK_LABEL_WINDOW_MS);
51
+ }).length;
52
+ return { n: asks.length, labelled };
53
+ }
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  /**
2
- * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), and the `evals_query` and `evals_label` tools.
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), `/ask-ai`, and the `evals_query` and `evals_label` tools.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { Type } from "typebox";
8
+ import { askAi } from "./ask-ai.js";
8
9
  import { scriptsDir } from "./findings.js";
9
10
  import { liveLabels } from "./live-labels.js";
10
11
  import { observe } from "./observer.js";
@@ -41,6 +42,7 @@ export function createEvals(options = {}) {
41
42
  const ctx0 = context(env);
42
43
  const observed = observe(pi, { layout: ctx0.layout, home: ctx0.home, now: options.now });
43
44
  const labels = liveLabels(pi, { env, now: options.now ?? Date.now, observed });
45
+ askAi(pi, { env, now: options.now ?? Date.now });
44
46
  let settingsWarned = false;
45
47
  pi.on("session_start", (_event, ctx) => {
46
48
  if (settingsWarned || !ctx0.settings.error)
@@ -14,6 +14,8 @@ export function labelsView(m) {
14
14
  `human: after the fact ${l.bySource.batch} (${l.sessions.batch} sessions), in the moment ${l.bySource.live} (${l.sessions.live} sessions${l.fromWords ? `; ${l.fromWords} formatted by the agent from your words` : ""}); unclear ${l.unclear}; no code verdict ${l.noCode}; on other ${l.other}`,
15
15
  "code vs human, agreed/compared (after the fact; in the moment):",
16
16
  ];
17
+ if (l.asks.n)
18
+ out.splice(2, 0, `/ask-ai questions: ${l.asks.n}; followed by a label in the same session within 30 min: ${l.asks.labelled}`);
17
19
  for (const a of l.agreement)
18
20
  out.push(`${a.detector}: ${ratio(a)} (${ratio(a.bySource.batch)}; ${ratio(a.bySource.live)})`);
19
21
  out.push(`corrections the agent logged (not all mistakes): ${c.n} in ${c.sessions} sessions${c.n && c.n < SMALL_SAMPLE ? `; small (<${SMALL_SAMPLE}), a hint not a trend` : ""}`);
package/dist/labels.js CHANGED
@@ -45,8 +45,21 @@ function parse(file) {
45
45
  }
46
46
  });
47
47
  }
48
- /** Rows in effect, in file order. A withdrawal cancels its session's latest live row still in effect before it. */
48
+ /**
49
+ * Rows in effect, in file order. A withdrawal cancels its session's latest live row still in effect before it, and a
50
+ * later human verdict on the same session, rule and item replaces an earlier one (the file keeps both). Each "other"
51
+ * label is its own event, and agent rows are never replaced.
52
+ */
49
53
  export function readLabels(file) {
54
+ const rows = withdrawn(file);
55
+ const latest = new Map();
56
+ rows.forEach((r, i) => {
57
+ if (r.annotator !== "agent" && r.evaluation_name !== "other")
58
+ latest.set(`${r.session_id}\u0000${r.evaluation_name}\u0000${r.item ?? ""}`, i);
59
+ });
60
+ return rows.filter((r, i) => r.annotator === "agent" || r.evaluation_name === "other" || latest.get(`${r.session_id}\u0000${r.evaluation_name}\u0000${r.item ?? ""}`) === i);
61
+ }
62
+ function withdrawn(file) {
50
63
  const rows = parse(file);
51
64
  const gone = new Set();
52
65
  const live = new Map();
@@ -2,6 +2,7 @@ import { Type } from "typebox";
2
2
  import { agentLabel, appendLabel, cleanNote, FAILURE_TYPES, itemOnBranch, RULES, ruleLabel, undoLast, VERDICT_META, VERDICTS } from "./labels.js";
3
3
  import { context } from "./ops.js";
4
4
  import { projectKey } from "./project.js";
5
+ import { turnWindow } from "./turn-window.js";
5
6
  const VERDICT_WORDS = new Map(VERDICTS.flatMap((v) => [[v, v], [VERDICT_META[v].zh, v]]));
6
7
  const USAGE = `pi-evals 用法:/evals label(一步步選)、/evals label <規則> pass|fail|unclear [說明],或 /evals label <你的話>(交給代理人整理成標記);規則:${RULES.join("、")};/evals label undo 撤銷這段工作上一筆當下標記。`;
7
8
  /** The turn that formats the user's words: the instruction to the agent, with the words last and verbatim. */
@@ -16,34 +17,8 @@ export function promptFor(words) {
16
17
  }
17
18
  export function liveLabels(pi, options) {
18
19
  const { env, now, observed } = options;
19
- /** The user's words waiting for their turn to start, and the turn that may speak for the user. */
20
- let waiting;
21
- let speaking;
22
- const textOf = (content) => typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof p.text === "string" ? p.text : "")).join("") : "";
23
- const start = (text) => {
24
- if (waiting && text === waiting.prompt) {
25
- speaking = { ...waiting };
26
- waiting = undefined;
27
- }
28
- };
29
- pi.on("before_agent_start", (event) => start(event.prompt));
30
- // A prompt queued behind a running turn starts its own run without before_agent_start: its user message opens it.
31
- pi.on("message_end", (event) => {
32
- const message = event.message;
33
- if (message?.role !== "user")
34
- return;
35
- const text = textOf(message.content);
36
- // Another message from the user in the same run is not part of the words the agent is formatting.
37
- if (speaking && text !== speaking.prompt)
38
- speaking = undefined;
39
- start(text);
40
- });
41
- pi.on("agent_end", () => {
42
- speaking = undefined;
43
- });
44
- pi.on("session_start", () => {
45
- waiting = speaking = undefined;
46
- });
20
+ /** The turn that may speak for the user: the one the user's words started. */
21
+ const speaking = turnWindow(pi);
47
22
  const where = (ctx) => {
48
23
  const c = context(env);
49
24
  const session = ctx.sessionManager.getSessionId();
@@ -71,8 +46,9 @@ export function liveLabels(pi, options) {
71
46
  note = words.slice(2).join(" ");
72
47
  if (!rule || !verdict) {
73
48
  const text = cleanNote(words.join(" "));
74
- waiting = { session: w.session, prompt: promptFor(text), note: text };
75
- pi.sendUserMessage(waiting.prompt, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
49
+ const prompt = promptFor(text);
50
+ speaking.arm({ session: w.session, prompt, data: { note: text } });
51
+ pi.sendUserMessage(prompt, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
76
52
  return say(`pi-evals:已把你的話交給代理人,請它整理成標記${ctx.isIdle() ? "" : "(等目前的工作告一段落)"};它會回報記了什麼,不對就用 /evals label undo 撤銷。`);
77
53
  }
78
54
  }
@@ -111,7 +87,7 @@ export function liveLabels(pi, options) {
111
87
  }, { additionalProperties: false }),
112
88
  async execute(_id, params, _signal, _onUpdate, ctx) {
113
89
  const session = ctx.sessionManager.getSessionId();
114
- const voice = speaking?.session === session ? speaking : undefined;
90
+ const voice = speaking.current(session)?.data;
115
91
  const { rule, label, type, onBehalf } = agentLabel(params, !!voice);
116
92
  const w = where(ctx);
117
93
  if (onBehalf) {
package/dist/model.js CHANGED
@@ -9,6 +9,7 @@ import { DETECTORS, ERA_START } from "./detectors.js";
9
9
  import { CHANGE_KIND_META, CLOSE_KIND_META, DETECTOR_META, METRICS, NOTICE_META, STALL_KIND_META } from "./meta.js";
10
10
  import { staticOwner } from "./owners.js";
11
11
  import { weeklyRises } from "./trends.js";
12
+ import { asksModel } from "./asks.js";
12
13
  import { labelsModel } from "./labels.js";
13
14
  import { ANCHORLOOP } from "./work/join.js";
14
15
  import { workModel } from "./work/model.js";
@@ -186,8 +187,9 @@ export function buildModel(options) {
186
187
  const selected = projectRows.filter(r => inRange(r.s)), children = selected.filter(r => r.k);
187
188
  const scoped = Boolean(filter.since || filter.until || filter.project);
188
189
  const hasSessionIds = selected.every(r => r.id !== undefined);
189
- const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
190
+ const labelIds = scoped && (existsSync(options.labelsFile) || (!!options.asksFile && existsSync(options.asksFile))) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
190
191
  const indexedIds = labelIds && new Set(options.rows.flatMap(r => r.id ? [r.id] : []));
192
+ const labelScope = { ...filter, until: options.openEnd ? undefined : filter.until, selected: labelIds, indexed: indexedIds };
191
193
  const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
192
194
  const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
193
195
  const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
@@ -295,7 +297,8 @@ export function buildModel(options) {
295
297
  .filter((c) => inRange(c.at))
296
298
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
297
299
  labels: {
298
- ...labelsModel(options.labelsFile, options.sessionEvalsFile, { ...filter, until: options.openEnd ? undefined : filter.until, selected: labelIds, indexed: indexedIds }, (at) => versionAt(sortedChanges, ANCHORLOOP, at)),
300
+ ...labelsModel(options.labelsFile, options.sessionEvalsFile, labelScope, (at) => versionAt(sortedChanges, ANCHORLOOP, at)),
301
+ asks: asksModel(options.asksFile, options.labelsFile, labelScope),
299
302
  needsIndex: !!labelIds && !hasSessionIds,
300
303
  },
301
304
  coverage: options.coverage ?? null,
package/dist/ops.js CHANGED
@@ -68,7 +68,7 @@ function snapshot(env, withCoverage = true) {
68
68
  const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
69
69
  // A range ends at the last extract unless the user ends it; a label given since then has no session in the index yet.
70
70
  return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays, openEnd: input.until === undefined,
71
- labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
71
+ labelsFile: ctx.layout.labels, asksFile: ctx.layout.asks, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
72
72
  } };
73
73
  }
74
74
  export function indexedModel(filter, env, withCoverage = true) {
package/dist/paths.js CHANGED
@@ -68,6 +68,7 @@ export function layout(state = stateDir()) {
68
68
  changes: join(state, "changes.jsonl"),
69
69
  marks: join(state, "marks.jsonl"),
70
70
  labels: join(state, "labels.jsonl"),
71
+ asks: join(state, "asks.jsonl"),
71
72
  status: join(state, "index", "status.json"),
72
73
  reports: join(state, "reports"),
73
74
  items: join(state, "index", "items.json"),
@@ -48,11 +48,14 @@ export function sections(m, lang, cards) {
48
48
  : `<p>${L("Coverage not measured; keep cleanup off.", "沒有索引覆蓋資料,請勿開啟清理。")}</p>`);
49
49
  const lb = m.labels, rule = (r) => ruleLabel(r, lang);
50
50
  const pair = (c) => (c.n ? `${num(c.agree)} / ${num(c.n)}` : "—");
51
+ const asked = lb.asks.n
52
+ ? `<p>${L(`You asked with /ask-ai ${num(lb.asks.n)} times; ${num(lb.asks.labelled)} of them were followed within 30 minutes by a label in the same session.`, `你用 /ask-ai 問了 ${num(lb.asks.n)} 次,其中 ${num(lb.asks.labelled)} 次在同一段工作裡、30 分鐘內接著標記了。`)}</p>`
53
+ : "";
51
54
  const labels = section("labels", L("Your labels", "你的標記"), meta.agreement.meaning[lang], lb.needsIndex ? `<p>${L("Run /evals extract to count labels in this period.", "請執行 /evals extract 以計算這段期間的標記。")}</p>` : lb.present && lb.n
52
55
  ? `<p>${L(`After the fact ${num(lb.bySource.batch)} (${num(lb.sessions.batch)} sessions) / In the moment ${num(lb.bySource.live)} (${num(lb.sessions.live)} sessions)`, `事後標 ${num(lb.bySource.batch)} 筆(${num(lb.sessions.batch)} 段工作) / 當下標 ${num(lb.bySource.live)} 筆(${num(lb.sessions.live)} 段工作)`)}${lb.fromWords ? L(`; ${num(lb.fromWords)} of them the agent wrote from your words`, `;其中 ${num(lb.fromWords)} 筆是代理人依你的話整理的`) : ""}</p>` +
53
56
  T([L("Check", "檢查"), L("Agreement", "一致比例"), L("After the fact: agreed / compared", "事後標:一致 / 比對"), L("In the moment: agreed / compared", "當下標:一致 / 比對"), L("Cannot tell", "看不出來")], lb.agreement.map((r) => [rule(r.detector), `${pct(r.rate)}(${num(r.n)})`, pair(r.bySource.batch), pair(r.bySource.live), r.unclear])) +
54
- `<p class="muted">${L(`Cannot tell ${num(lb.unclear)}: labels marked unclear are left out of the agreement rate.`, `看不出來 ${num(lb.unclear)}:標成「看不出來」的不算進一致比例。`)}${lb.noCode ? L(` ${num(lb.noCode)} labels have no code verdict to compare: the session is not extracted yet (run /evals extract), or the rule did not apply to it.`, `另有 ${num(lb.noCode)} 筆沒有程式判斷可比:那段工作還沒整理(執行 /evals extract 後就能比),或這條規則不適用於它。`) : ""}${lb.other ? L(` ${num(lb.other)} labels are on "Other", which no code check covers.`, `${num(lb.other)} 筆標在「其他」,沒有程式檢查可比。`) : ""}</p>` + lesson(cards.labelTiming, L)
55
- : `<p>${L("No labels yet. Type /evals label in any session to say, while the work is in front of you, whether the agent followed a rule.", "還沒有標記。在任何工作階段輸入 /evals label,就能趁工作還在眼前,標記代理人有沒有照規則做。")}</p>` + lesson(cards.labelTiming, L));
57
+ `<p class="muted">${L(`Cannot tell ${num(lb.unclear)}: labels marked unclear are left out of the agreement rate.`, `看不出來 ${num(lb.unclear)}:標成「看不出來」的不算進一致比例。`)}${lb.noCode ? L(` ${num(lb.noCode)} labels have no code verdict to compare: the session is not extracted yet (run /evals extract), or the rule did not apply to it.`, `另有 ${num(lb.noCode)} 筆沒有程式判斷可比:那段工作還沒整理(執行 /evals extract 後就能比),或這條規則不適用於它。`) : ""}${lb.other ? L(` ${num(lb.other)} labels are on "Other", which no code check covers.`, `${num(lb.other)} 筆標在「其他」,沒有程式檢查可比。`) : ""}</p>` + asked + lesson(cards.labelTiming, L)
58
+ : `<p>${L("No labels yet. Type /evals label in any session to say, while the work is in front of you, whether the agent followed a rule.", "還沒有標記。在任何工作階段輸入 /evals label,就能趁工作還在眼前,標記代理人有沒有照規則做。")}</p>` + asked + lesson(cards.labelTiming, L));
56
59
  const c = lb.corrections, few = c.n < SMALL_SAMPLE;
57
60
  const corrections = section("corrections", L("Times the agent was corrected", "被糾正"), L("When you correct how the agent worked, it logs one line with evals_label. This counts the corrections it logged, not all its mistakes: a slip nobody caught, or one it forgot to log, is not here.", "你糾正代理人的做法時,它會用 evals_label 自己記一筆。這裡數的是它記下的被糾正次數,不是所有錯誤:沒人發現、沒被糾正,或它忘了記的,都不在這裡。"), c.n
58
61
  ? `<p class="big">${num(c.n)} <small>${L("corrections", "次")} · ${num(c.sessions)} ${L("sessions", "段工作")}</small></p>${few ? `<p class="stale">${L(`Only ${num(c.n)}: too few to show a trend. Read it as a hint of where slips may recur.`, `只有 ${num(c.n)} 次,太少,看不出趨勢;只能當提醒,看哪裡可能常出錯。`)}</p>` : ""}<div class="pair"><article class="panel"><h3>${L("By rule", "依規則")}</h3>${T([L("Rule", "規則"), L("Times", "次數")], c.byRule.map((r) => [rule(r.rule), r.n]))}</article><article class="panel"><h3>${L("By kind of slip", "依錯誤類型")}</h3>${T([L("Kind", "類型"), L("Times", "次數")], c.byType.map((r) => [FAILURE_TYPE_META[r.type]?.[lang] ?? r.type, r.n]))}</article></div>` +
@@ -0,0 +1,37 @@
1
+ export const textOf = (content) => typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof p.text === "string" ? p.text : "")).join("") : "";
2
+ export function turnWindow(pi) {
3
+ let waiting;
4
+ let open;
5
+ const start = (text) => {
6
+ if (waiting && text === waiting.prompt) {
7
+ open = waiting;
8
+ waiting = undefined;
9
+ }
10
+ };
11
+ pi.on("before_agent_start", (event) => start(event.prompt));
12
+ pi.on("message_end", (event) => {
13
+ const message = event.message;
14
+ if (message?.role !== "user")
15
+ return;
16
+ const text = textOf(message.content);
17
+ if (open && text !== open.prompt)
18
+ open = undefined;
19
+ start(text);
20
+ });
21
+ pi.on("agent_end", () => {
22
+ open = undefined;
23
+ });
24
+ pi.on("session_start", () => {
25
+ waiting = open = undefined;
26
+ });
27
+ return {
28
+ /** The message the command is about to send; its turn opens when that message starts a run. */
29
+ arm(turn) {
30
+ waiting = turn;
31
+ },
32
+ /** The open turn of this session, if any. */
33
+ current(session) {
34
+ return open?.session === session ? open : undefined;
35
+ },
36
+ };
37
+ }
package/docs/schema.md CHANGED
@@ -66,6 +66,8 @@ There are three kinds of rows:
66
66
  - A row without `source` is a human verdict given after the fact (the report calls it 事後標, the code `batch`).
67
67
  - `source: "live"` is a human verdict given in the moment with `/evals label`. `/evals label undo` appends `{ …, "source": "live", "undo": "<at of the withdrawn row>" }`, which withdraws the session's latest live row still in effect.
68
68
  - `source: "live-prompt"` is a human verdict too: the user's words after `/evals label`, which the agent turned into rows with `evals_label` and `on_behalf: "user"` during the turn those words started. The note is the user's words, taken from the command, never from the agent.
69
+ - `source: "recheck"` is a human verdict given again after the fact; it replaces the earlier label.
70
+ - A later human row on the same `session_id`, `evaluation_name` and `item` replaces an earlier one (the file keeps both); each `other` row and every agent row stays its own.
69
71
  - `source: "correction"` is an agent's `evals_label` call: `label` is always `fail`, and `type` is one of `no_check_stated`, `no_check_run`, `skipped_rule`, `wrong_order`, `unverified_claim`, `ignored_instruction`, `other`. The tool accepts no other field or value, and refuses `on_behalf` outside such a turn.
70
72
 
71
73
  `evaluation_name` is a process check name or `other`.
@@ -80,6 +82,18 @@ With a date or project filter, a row belongs to the range by its session's start
80
82
  A range without an end date the user gave ends at the last extract, but a row of a session not indexed yet is not cut there, so a label given after the last extract still shows.
81
83
  The report counts the `live-prompt` rows among 當下標 and says how many there are.
82
84
 
85
+ ## Asks
86
+
87
+ `asks.jsonl` in the state dir gets one row per `/ask-ai`, appended when the command runs and read at every report and query:
88
+
89
+ ```json
90
+ { "session_id": "01a2…", "at": "2026-11-26T06:00:00Z", "kind": "ask_ai", "project": "demo-repo", "item": "MP-1234" }
91
+ ```
92
+
93
+ `item` is the todo item in progress, keyed as in labels, and is absent when none is.
94
+ The row holds no question text, and the agent's answer is not stored anywhere.
95
+ The report counts asks in range (scoped like live labels) and how many had a human label in the same session at most 30 minutes after the ask; the `labels` view of `evals_query` gives the same two numbers.
96
+
83
97
  ## Change timeline
84
98
 
85
99
  `changes.jsonl`, rebuilt by every extract, one change per line:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-evals",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Usage and process records for pi: how skills, packages, ask-user, monitors and subagents are used, back-filled from past sessions, with a static report and an evals_query tool",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/ask-ai.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `/ask-ai <question>`: the user asks, and the agent answers now. The question goes to the agent wrapped in a short
3
+ * answer-first instruction, and while that turn runs the tools that change things or start work are refused, so a
4
+ * question is not taken for a reproach and turned into new work before the user can label how it went.
5
+ */
6
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
+ import { appendAsk } from "./asks.ts";
8
+ import { itemOnBranch } from "./labels.ts";
9
+ import { context } from "./ops.ts";
10
+ import { projectKey } from "./project.ts";
11
+ import { turnWindow } from "./turn-window.ts";
12
+
13
+ type Env = Record<string, string | undefined>;
14
+ type Input = Record<string, unknown>;
15
+
16
+ const always = () => true;
17
+ /** Tools refused during an `/ask-ai` turn, each with the inputs it is refused for; any other tool runs. */
18
+ export const ASK_AI_BLOCKED: Readonly<Record<string, (input: Input) => boolean>> = {
19
+ write: always,
20
+ edit: always,
21
+ subagent: always,
22
+ boss_pair: always,
23
+ MonitorCreate: always,
24
+ LoopCreate: always,
25
+ call_tower: always,
26
+ todo: (input) => input.action !== "list" && input.action !== "get",
27
+ intercom: (input) => input.action === "send" || input.action === "ask" || input.action === "handover",
28
+ };
29
+
30
+ const USAGE = "pi-evals 用法:/ask-ai <你的問題>,代理人會先直接回答,不改任何東西、不開始新工作。";
31
+
32
+ /** The question, last and verbatim, after the instruction to answer it now and do nothing else. */
33
+ export function askPrompt(question: string): string {
34
+ return [
35
+ "[/ask-ai] Answer the user's question below now, directly and first, in the user's language. Read only what you need to answer; change nothing, start no work, dispatch nothing. If it asks how you worked, say plainly what happened and whether it followed the rule. End with at most one line of suggested next step, then wait for the user.",
36
+ "",
37
+ `Question: ${question}`,
38
+ ].join("\n");
39
+ }
40
+
41
+ export function askAi(pi: ExtensionAPI, options: { env: Env; now: () => number }) {
42
+ const { env, now } = options;
43
+ const asking = turnWindow<undefined>(pi);
44
+
45
+ pi.on("tool_call", (event, ctx) => {
46
+ const { toolName, input } = event as { toolName: string; input?: Input };
47
+ const refuse = Object.hasOwn(ASK_AI_BLOCKED, toolName) ? ASK_AI_BLOCKED[toolName] : undefined;
48
+ if (!refuse || !refuse(input ?? {}) || !asking.current(ctx.sessionManager.getSessionId())) return undefined;
49
+ return { block: true, reason: `Refused during /ask-ai: answer the user's question first, change nothing and start no work; ${toolName} can run after the user replies.` };
50
+ });
51
+
52
+ pi.registerCommand("ask-ai", {
53
+ description: "Ask the agent a question and have it answer now, without starting work: /ask-ai <question>",
54
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
55
+ const question = args.trim();
56
+ if (!question) return ctx.ui.notify(USAGE, "warning");
57
+ const c = context(env);
58
+ const session = ctx.sessionManager.getSessionId();
59
+ let branch: unknown[] | undefined;
60
+ try {
61
+ branch = ctx.sessionManager.getBranch?.();
62
+ } catch {}
63
+ appendAsk(c.layout.asks, { session_id: session, at: new Date(now()).toISOString(), kind: "ask_ai", project: projectKey(ctx.cwd, c.home), item: itemOnBranch(branch, session) });
64
+ const prompt = askPrompt(question);
65
+ asking.arm({ session, prompt, data: undefined });
66
+ // While the agent works, the question goes in after its current tool calls, not after the whole run.
67
+ pi.sendUserMessage(prompt, ctx.isIdle() ? undefined : { deliverAs: "steer" });
68
+ },
69
+ });
70
+ }
package/src/asks.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `asks.jsonl` (append-only): one row per `/ask-ai`, when and where it was asked. Never the question or the answer.
3
+ * The report counts them and how many were followed by a label in the same session within 30 minutes.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+ import { type LabelScope, readLabels } from "./labels.ts";
8
+ import { traceId } from "./schema.ts";
9
+
10
+ export interface AskRow {
11
+ session_id: string;
12
+ at: string;
13
+ kind: "ask_ai";
14
+ project?: string;
15
+ item?: string;
16
+ }
17
+
18
+ /** How long after an ask a label in the same session counts as following it. */
19
+ export const ASK_LABEL_WINDOW_MS = 30 * 60 * 1000;
20
+
21
+ export function appendAsk(file: string, row: AskRow): void {
22
+ mkdirSync(dirname(file), { recursive: true });
23
+ appendFileSync(file, `${JSON.stringify(row)}\n`);
24
+ }
25
+
26
+ export function readAsks(file: string): AskRow[] {
27
+ if (!existsSync(file)) return [];
28
+ return readFileSync(file, "utf8")
29
+ .split("\n")
30
+ .filter(Boolean)
31
+ .flatMap((line) => {
32
+ try {
33
+ const row = JSON.parse(line) as AskRow;
34
+ return row && row.kind === "ask_ai" && typeof row.session_id === "string" && typeof row.at === "string" ? [row] : [];
35
+ } catch {
36
+ return [];
37
+ }
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Asks in scope (a session in the index belongs by its start; one not indexed yet by the ask's own time and project),
43
+ * and how many a human label in the same session followed within `ASK_LABEL_WINDOW_MS`.
44
+ */
45
+ export function asksModel(asksFile: string | undefined, labelsFile: string, scope: LabelScope): { n: number; labelled: number } {
46
+ if (!asksFile) return { n: 0, labelled: 0 };
47
+ const inDates = (at: string) => (!scope.since || at.slice(0, 10) >= scope.since) && (!scope.until || at.slice(0, 10) <= scope.until);
48
+ const asks = readAsks(asksFile).filter((r) => {
49
+ if (!scope.selected) return true;
50
+ const id = traceId(r.session_id, "labels");
51
+ return scope.selected.has(id) || (!scope.indexed?.has(id) && inDates(r.at) && (!scope.project || r.project === scope.project));
52
+ });
53
+ if (!asks.length) return { n: 0, labelled: 0 };
54
+ const labels = readLabels(labelsFile).filter((l) => l.annotator !== "agent" && typeof l.at === "string");
55
+ const labelled = asks.filter((a) => {
56
+ const t = Date.parse(a.at);
57
+ return labels.some((l) => l.session_id === a.session_id && Date.parse(l.at) >= t && Date.parse(l.at) - t <= ASK_LABEL_WINDOW_MS);
58
+ }).length;
59
+ return { n: asks.length, labelled };
60
+ }
package/src/index.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /**
2
- * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), and the `evals_query` and `evals_label` tools.
2
+ * pi-evals: the live observer, the `/evals` command (status, extract, report, mark, label), `/ask-ai`, and the `evals_query` and `evals_label` tools.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
8
8
  import { Type } from "typebox";
9
+ import { askAi } from "./ask-ai.ts";
9
10
  import { scriptsDir } from "./findings.ts";
10
11
  import { liveLabels } from "./live-labels.ts";
11
12
  import { observe } from "./observer.ts";
@@ -44,6 +45,7 @@ export function createEvals(options: { env?: Env; spawnExtract?: typeof spawn; n
44
45
  const ctx0 = context(env);
45
46
  const observed = observe(pi, { layout: ctx0.layout, home: ctx0.home, now: options.now });
46
47
  const labels = liveLabels(pi, { env, now: options.now ?? Date.now, observed });
48
+ askAi(pi, { env, now: options.now ?? Date.now });
47
49
  let settingsWarned = false;
48
50
  pi.on("session_start", (_event, ctx) => {
49
51
  if (settingsWarned || !ctx0.settings.error) return;
@@ -16,6 +16,7 @@ export function labelsView(m: ReportModel): string[] {
16
16
  `human: after the fact ${l.bySource.batch} (${l.sessions.batch} sessions), in the moment ${l.bySource.live} (${l.sessions.live} sessions${l.fromWords ? `; ${l.fromWords} formatted by the agent from your words` : ""}); unclear ${l.unclear}; no code verdict ${l.noCode}; on other ${l.other}`,
17
17
  "code vs human, agreed/compared (after the fact; in the moment):",
18
18
  ];
19
+ if (l.asks.n) out.splice(2, 0, `/ask-ai questions: ${l.asks.n}; followed by a label in the same session within 30 min: ${l.asks.labelled}`);
19
20
  for (const a of l.agreement) out.push(`${a.detector}: ${ratio(a)} (${ratio(a.bySource.batch)}; ${ratio(a.bySource.live)})`);
20
21
  out.push(`corrections the agent logged (not all mistakes): ${c.n} in ${c.sessions} sessions${c.n && c.n < SMALL_SAMPLE ? `; small (<${SMALL_SAMPLE}), a hint not a trend` : ""}`);
21
22
  if (c.n) {
package/src/labels.ts CHANGED
@@ -16,8 +16,11 @@ export const VERDICTS = ["pass", "fail", "unclear"] as const;
16
16
  export type Verdict = (typeof VERDICTS)[number];
17
17
  export const FAILURE_TYPES = ["no_check_stated", "no_check_run", "skipped_rule", "wrong_order", "unverified_claim", "ignored_instruction", "other"] as const;
18
18
  export type FailureType = (typeof FAILURE_TYPES)[number];
19
- /** `live-prompt`: the user's words after `/evals label`, which the agent turned into rows on the user's behalf. */
20
- export type LabelSource = "batch" | "live" | "live-prompt" | "correction";
19
+ /**
20
+ * `live-prompt`: the user's words after `/evals label`, which the agent turned into rows on the user's behalf.
21
+ * `recheck`: the user's later verdict on a label given after the fact; it replaces that label.
22
+ */
23
+ export type LabelSource = "batch" | "live" | "live-prompt" | "correction" | "recheck";
21
24
  export const NOTE_MAX = 500;
22
25
 
23
26
  const t = (en: string, zh: string): Text => ({ en, zh });
@@ -71,8 +74,21 @@ function parse(file: string): LabelRow[] {
71
74
  });
72
75
  }
73
76
 
74
- /** Rows in effect, in file order. A withdrawal cancels its session's latest live row still in effect before it. */
77
+ /**
78
+ * Rows in effect, in file order. A withdrawal cancels its session's latest live row still in effect before it, and a
79
+ * later human verdict on the same session, rule and item replaces an earlier one (the file keeps both). Each "other"
80
+ * label is its own event, and agent rows are never replaced.
81
+ */
75
82
  export function readLabels(file: string): LabelRow[] {
83
+ const rows = withdrawn(file);
84
+ const latest = new Map<string, number>();
85
+ rows.forEach((r, i) => {
86
+ if (r.annotator !== "agent" && r.evaluation_name !== "other") latest.set(`${r.session_id}\u0000${r.evaluation_name}\u0000${r.item ?? ""}`, i);
87
+ });
88
+ return rows.filter((r, i) => r.annotator === "agent" || r.evaluation_name === "other" || latest.get(`${r.session_id}\u0000${r.evaluation_name}\u0000${r.item ?? ""}`) === i);
89
+ }
90
+
91
+ function withdrawn(file: string): LabelRow[] {
76
92
  const rows = parse(file);
77
93
  const gone = new Set<number>();
78
94
  const live = new Map<string, number[]>();
@@ -9,6 +9,7 @@ import { agentLabel, appendLabel, cleanNote, FAILURE_TYPES, type FailureType, it
9
9
  import type { Observed } from "./observer.ts";
10
10
  import { context } from "./ops.ts";
11
11
  import { projectKey } from "./project.ts";
12
+ import { turnWindow } from "./turn-window.ts";
12
13
 
13
14
  type Env = Record<string, string | undefined>;
14
15
  type Ctx = Pick<ExtensionCommandContext, "cwd" | "sessionManager">;
@@ -29,33 +30,8 @@ export function promptFor(words: string): string {
29
30
 
30
31
  export function liveLabels(pi: ExtensionAPI, options: { env: Env; now: () => number; observed: Observed }) {
31
32
  const { env, now, observed } = options;
32
- /** The user's words waiting for their turn to start, and the turn that may speak for the user. */
33
- let waiting: { session: string; prompt: string; note?: string } | undefined;
34
- let speaking: { session: string; prompt: string; note?: string } | undefined;
35
- const textOf = (content: unknown) =>
36
- typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof (p as { text?: unknown }).text === "string" ? (p as { text: string }).text : "")).join("") : "";
37
- const start = (text: string | undefined) => {
38
- if (waiting && text === waiting.prompt) {
39
- speaking = { ...waiting };
40
- waiting = undefined;
41
- }
42
- };
43
- pi.on("before_agent_start", (event) => start((event as { prompt?: string }).prompt));
44
- // A prompt queued behind a running turn starts its own run without before_agent_start: its user message opens it.
45
- pi.on("message_end", (event) => {
46
- const message = (event as { message?: { role?: string; content?: unknown } }).message;
47
- if (message?.role !== "user") return;
48
- const text = textOf(message.content);
49
- // Another message from the user in the same run is not part of the words the agent is formatting.
50
- if (speaking && text !== speaking.prompt) speaking = undefined;
51
- start(text);
52
- });
53
- pi.on("agent_end", () => {
54
- speaking = undefined;
55
- });
56
- pi.on("session_start", () => {
57
- waiting = speaking = undefined;
58
- });
33
+ /** The turn that may speak for the user: the one the user's words started. */
34
+ const speaking = turnWindow<{ note?: string }>(pi);
59
35
  const where = (ctx: Ctx) => {
60
36
  const c = context(env);
61
37
  const session = ctx.sessionManager.getSessionId();
@@ -83,8 +59,9 @@ export function liveLabels(pi: ExtensionAPI, options: { env: Env; now: () => num
83
59
  note = words.slice(2).join(" ");
84
60
  if (!rule || !verdict) {
85
61
  const text = cleanNote(words.join(" "))!;
86
- waiting = { session: w.session, prompt: promptFor(text), note: text };
87
- pi.sendUserMessage(waiting.prompt, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
62
+ const prompt = promptFor(text);
63
+ speaking.arm({ session: w.session, prompt, data: { note: text } });
64
+ pi.sendUserMessage(prompt, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
88
65
  return say(`pi-evals:已把你的話交給代理人,請它整理成標記${ctx.isIdle() ? "" : "(等目前的工作告一段落)"};它會回報記了什麼,不對就用 /evals label undo 撤銷。`);
89
66
  }
90
67
  } else {
@@ -122,7 +99,7 @@ export function liveLabels(pi: ExtensionAPI, options: { env: Env; now: () => num
122
99
  ),
123
100
  async execute(_id, params, _signal, _onUpdate, ctx) {
124
101
  const session = ctx.sessionManager.getSessionId();
125
- const voice = speaking?.session === session ? speaking : undefined;
102
+ const voice = speaking.current(session)?.data;
126
103
  const { rule, label, type, onBehalf } = agentLabel(params, !!voice);
127
104
  const w = where(ctx);
128
105
  if (onBehalf) {
package/src/model.ts CHANGED
@@ -11,6 +11,7 @@ import { DETECTORS, ERA_START } from "./detectors.ts";
11
11
  import { CHANGE_KIND_META, CLOSE_KIND_META, DETECTOR_META, METRICS, NOTICE_META, STALL_KIND_META } from "./meta.ts";
12
12
  import { staticOwner } from "./owners.ts";
13
13
  import { weeklyRises } from "./trends.ts";
14
+ import { asksModel } from "./asks.ts";
14
15
  import { labelsModel } from "./labels.ts";
15
16
  import { ANCHORLOOP, type ItemsFile } from "./work/join.ts";
16
17
  import { workModel } from "./work/model.ts";
@@ -180,6 +181,8 @@ export function buildModel(options: {
180
181
  filter: Filter;
181
182
  windowDays: number;
182
183
  labelsFile: string;
184
+ /** `asks.jsonl`, when the caller has one. */
185
+ asksFile?: string;
183
186
  sessionEvalsFile: string;
184
187
  coverage?: Coverage;
185
188
  /** Joined work items (`index/items.json`), when built. */
@@ -215,8 +218,9 @@ export function buildModel(options: {
215
218
  const selected = projectRows.filter(r => inRange(r.s)), children = selected.filter(r => r.k);
216
219
  const scoped = Boolean(filter.since || filter.until || filter.project);
217
220
  const hasSessionIds = selected.every(r => r.id !== undefined);
218
- const labelIds = scoped && existsSync(options.labelsFile) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
221
+ const labelIds = scoped && (existsSync(options.labelsFile) || (!!options.asksFile && existsSync(options.asksFile))) ? new Set(selected.flatMap(r => r.id ? [r.id] : [])) : undefined;
219
222
  const indexedIds = labelIds && new Set(options.rows.flatMap(r => r.id ? [r.id] : []));
223
+ const labelScope = { ...filter, until: options.openEnd ? undefined : filter.until, selected: labelIds, indexed: indexedIds };
220
224
  const calls = Object.values(total.tools).reduce((s, t) => s + t.calls, 0);
221
225
  const errors = Object.values(total.tools).reduce((s, t) => s + t.errors, 0);
222
226
  const tokens = total.usage.input + total.usage.output + total.usage.cacheRead + total.usage.cacheWrite;
@@ -324,7 +328,8 @@ export function buildModel(options: {
324
328
  .filter((c) => inRange(c.at))
325
329
  .map((c) => ({ ...c, impact: index.range.start && c.at > index.range.start ? impactFromRows(projectRows, c, sortedChanges, options.windowDays, index.range, owner) : null })),
326
330
  labels: {
327
- ...labelsModel(options.labelsFile, options.sessionEvalsFile, { ...filter, until: options.openEnd ? undefined : filter.until, selected: labelIds, indexed: indexedIds }, (at) => versionAt(sortedChanges, ANCHORLOOP, at)),
331
+ ...labelsModel(options.labelsFile, options.sessionEvalsFile, labelScope, (at) => versionAt(sortedChanges, ANCHORLOOP, at)),
332
+ asks: asksModel(options.asksFile, options.labelsFile, labelScope),
328
333
  needsIndex: !!labelIds && !hasSessionIds,
329
334
  },
330
335
  coverage: options.coverage ?? null,
package/src/ops.ts CHANGED
@@ -80,7 +80,7 @@ function snapshot(env?: Env, withCoverage = true) {
80
80
  const filter = rangeFilter(input, index.lastExtract ?? now.toISOString(), preset);
81
81
  // A range ends at the last extract unless the user ends it; a label given since then has no session in the index yet.
82
82
  return buildModel({ index, rows, changes, comparisons, filter, now, windowDays: ctx.settings.impactWindowDays, openEnd: input.until === undefined,
83
- labelsFile: ctx.layout.labels, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
83
+ labelsFile: ctx.layout.labels, asksFile: ctx.layout.asks, sessionEvalsFile: ctx.layout.sessionEvals, coverage: cov?.(filter), work });
84
84
  } };
85
85
  }
86
86
  export function indexedModel(filter: RangeInput, env?: Env, withCoverage = true) {
package/src/paths.ts CHANGED
@@ -83,6 +83,8 @@ export interface Layout {
83
83
  changes: string;
84
84
  marks: string;
85
85
  labels: string;
86
+ /** One row per /ask-ai, never the question. */
87
+ asks: string;
86
88
  status: string;
87
89
  reports: string;
88
90
  /** Joined work items (what the report reads), their records, and the lines-changed cache. */
@@ -103,6 +105,7 @@ export function layout(state = stateDir()): Layout {
103
105
  changes: join(state, "changes.jsonl"),
104
106
  marks: join(state, "marks.jsonl"),
105
107
  labels: join(state, "labels.jsonl"),
108
+ asks: join(state, "asks.jsonl"),
106
109
  status: join(state, "index", "status.json"),
107
110
  reports: join(state, "reports"),
108
111
  items: join(state, "index", "items.json"),
@@ -154,6 +154,9 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
154
154
  );
155
155
  const lb = m.labels, rule = (r: string) => ruleLabel(r, lang);
156
156
  const pair = (c: { agree: number; n: number }) => (c.n ? `${num(c.agree)} / ${num(c.n)}` : "—");
157
+ const asked = lb.asks.n
158
+ ? `<p>${L(`You asked with /ask-ai ${num(lb.asks.n)} times; ${num(lb.asks.labelled)} of them were followed within 30 minutes by a label in the same session.`, `你用 /ask-ai 問了 ${num(lb.asks.n)} 次,其中 ${num(lb.asks.labelled)} 次在同一段工作裡、30 分鐘內接著標記了。`)}</p>`
159
+ : "";
157
160
  const labels = section(
158
161
  "labels",
159
162
  L("Your labels", "你的標記"),
@@ -168,13 +171,13 @@ export function sections(m: ReportModel, lang: Lang, cards: ReturnType<typeof co
168
171
  ) +
169
172
  `<p class="muted">${L(`Cannot tell ${num(lb.unclear)}: labels marked unclear are left out of the agreement rate.`, `看不出來 ${num(lb.unclear)}:標成「看不出來」的不算進一致比例。`)}${
170
173
  lb.noCode ? L(` ${num(lb.noCode)} labels have no code verdict to compare: the session is not extracted yet (run /evals extract), or the rule did not apply to it.`, `另有 ${num(lb.noCode)} 筆沒有程式判斷可比:那段工作還沒整理(執行 /evals extract 後就能比),或這條規則不適用於它。`) : ""
171
- }${lb.other ? L(` ${num(lb.other)} labels are on "Other", which no code check covers.`, `${num(lb.other)} 筆標在「其他」,沒有程式檢查可比。`) : ""}</p>` + lesson(cards.labelTiming, L)
174
+ }${lb.other ? L(` ${num(lb.other)} labels are on "Other", which no code check covers.`, `${num(lb.other)} 筆標在「其他」,沒有程式檢查可比。`) : ""}</p>` + asked + lesson(cards.labelTiming, L)
172
175
  : `<p>${
173
176
  L(
174
177
  "No labels yet. Type /evals label in any session to say, while the work is in front of you, whether the agent followed a rule.",
175
178
  "還沒有標記。在任何工作階段輸入 /evals label,就能趁工作還在眼前,標記代理人有沒有照規則做。",
176
179
  )
177
- }</p>` + lesson(cards.labelTiming, L),
180
+ }</p>` + asked + lesson(cards.labelTiming, L),
178
181
  );
179
182
  const c = lb.corrections, few = c.n < SMALL_SAMPLE;
180
183
  const corrections = section(
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The turn a command's own message starts: armed when the command sends it, open from the moment that message starts
3
+ * the run (`before_agent_start`, or its user message when it was queued behind a running turn), and closed at
4
+ * `agent_end`, on another message from the user, or at a new session.
5
+ */
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+
8
+ export interface Turn<T> {
9
+ session: string;
10
+ prompt: string;
11
+ data: T;
12
+ }
13
+
14
+ export const textOf = (content: unknown) =>
15
+ typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof (p as { text?: unknown }).text === "string" ? (p as { text: string }).text : "")).join("") : "";
16
+
17
+ export function turnWindow<T>(pi: ExtensionAPI) {
18
+ let waiting: Turn<T> | undefined;
19
+ let open: Turn<T> | undefined;
20
+ const start = (text: string | undefined) => {
21
+ if (waiting && text === waiting.prompt) {
22
+ open = waiting;
23
+ waiting = undefined;
24
+ }
25
+ };
26
+ pi.on("before_agent_start", (event) => start((event as { prompt?: string }).prompt));
27
+ pi.on("message_end", (event) => {
28
+ const message = (event as { message?: { role?: string; content?: unknown } }).message;
29
+ if (message?.role !== "user") return;
30
+ const text = textOf(message.content);
31
+ if (open && text !== open.prompt) open = undefined;
32
+ start(text);
33
+ });
34
+ pi.on("agent_end", () => {
35
+ open = undefined;
36
+ });
37
+ pi.on("session_start", () => {
38
+ waiting = open = undefined;
39
+ });
40
+ return {
41
+ /** The message the command is about to send; its turn opens when that message starts a run. */
42
+ arm(turn: Turn<T>) {
43
+ waiting = turn;
44
+ },
45
+ /** The open turn of this session, if any. */
46
+ current(session: string): Turn<T> | undefined {
47
+ return open?.session === session ? open : undefined;
48
+ },
49
+ };
50
+ }