Files
open-design/apps/daemon/tests/thinking-stream-panel-grammar.test.ts
bb9682a5f9 feat(daemon): make OD Next the default route, and keep the switch usable (#7876)
* feat(daemon): make OD Next the default route, and keep an opt-out opted out

An installation that configured nothing ran the ordinary strategy route, so
shipping OD Next in a build never changed how a run behaved until someone
opened Settings and asked for it. That made the Labs switch the whole rollout:
the strategy could only reach the users who already knew to look for it.

`resolveRequestedMode` now resolves an unconfigured installation to `active`.
Every other admission condition already defaulted open — assignment bucket,
both content flags, the production approval flag — so this last default was the
only thing holding the route closed.

The one-line change is the small part. Flipping the default inverts which case
is load-bearing. While the strategy was opt-in, an installation that lost its
saved mode kept the behaviour it already had; now an installation that loses
its saved mode is switched back on. So the invariant this has to keep is that
an installation which opted out reads `off` through every later release, and
that rests on opting out being stored rather than erased: `off` is a value the
config carries, `applyConfigValue` drops the key only for a value it cannot
store, and `assertWritableControlValues` refuses those on the way in.

That last guard is the same code as before but now protects the opposite
direction. It used to stop a typo from masquerading as an opt-out; it now stops
a typo from revoking one. Its docblock, the field comments on both sides of the
contract, the `od strategy` help text, and the prompt-composition note all
described the opt-in world and would have read as the reverse of the truth.

Tests carry the semantics:

- a new assertion pins the opt-out invariant, and checks not just the value
  read back but that the decision built from it actually evaluates to `off`;
- the route test now separates `default` from a saved `off`, which resolve to
  opposite routes and no longer to the same one;
- the app-config acceptance case against a real server is rewritten end to end.
  It was "nothing configured takes the ordinary route, and the same running
  daemon takes OD Next once you opt in". It is now the opt-out direction, and
  proves it from the agent invocation log rather than from the run record: the
  first run's prompt is the strategy's, the run after `off` is saved is not.

Packaged installs have no second control — the packaged child environment
allowlist carries no `OD_NEXT_*` key — so the saved mode is the only thing
standing between an opted-out user and this default.

e2e is deliberately untouched here and follows separately. Its specs mostly
never set this mode, so prototype and deck cases now take the OD Next route.
Pinning the env var in the harness is not the fix: the env var outranks the
saved config by design, which would break the spec asserting that an
app-config write takes effect with `app_config` as its source.

* test(daemon): stop the panel-grammar spec failing on the clock

`thinking-stream-panel-grammar` asserted that the whole SSE body contains
neither `Critic` nor `8.1`, on the stated premise that both "只可能来自标记内部".
That premise does not hold for the second one. The body also carries the
daemon's own `start` envelope, and `toolTokenExpiresAt` is an ISO timestamp: a
run whose token expiry lands on a second ending in `8` with milliseconds
starting with `1` produces `…:48.161Z`, which contains `8.1`. Roughly one run in
a hundred, and it hit on CI — with a thinking stream the log shows was clean,
so the spec failed on the clock rather than on a leak.

The two attribute-fragment assertions now run against the concatenated
`thinking_delta` / `text_delta` text instead of the raw body. That is not a
weaker check: persistence consumes exactly those deltas, so it is what the
spec's own "SSE clean ≡ database clean" argument was always about, and the
envelope fields it drops were never a place a leak could surface. The tag regex
stays on the whole body, where an opening `<PANELIST` cannot appear by accident.

The two prose assertions move to the same extracted text, which is what keeps
the negative assertions honest: an extractor that selected the wrong event type
would return an empty string, and every `not.toContain` would pass against it.

* feat(daemon): remove the OD Next stop latch

A run that hit certain failures wrote a row to `strategy_rollout_controls`.
From the next request on, every task on that installation took the legacy
route. The row outranked the saved mode, survived restart, and the Labs switch
kept reading "on" while the notice underneath said the harness had been paused —
with no control to unpause it. The only way back was an operator running
`od strategy rollout reset`.

The code already argued against this. The docblock over
`rolloutStopSignalForBlockedContinuation` says only a failure of the machine
contract itself may raise a latch, because an agent turn that mis-populates a
machine block "is already fail-closed for that task ... and it must not silently
return every later request in the daemon to the legacy path." One signal had
already been retired for doing exactly that: `complex_child_unverified` took OD
Next away from Codex, Claude and OpenCode because a fourth runtime lacks a
child-lifecycle producer. This generalises those narrowings instead of waiting
for the next signal to earn its own.

It also stopped being survivable. While OD Next was opt-in, the latch could only
reach the few installations that had asked for it; with the default flipped it
reaches everyone, and the population exposed to an automatic, restart-surviving,
UI-unrecoverable disable is now the whole install base.

Deleting it changes nothing about how any single failure is handled. All three
live trigger points were additive actions taken *after* the existing handling:
`native_resume_failed` already blocked the continuation, sent
`AGENT_SESSION_RESUME_FAILED` and finished the run failed; the blocked-
continuation cases were already set to `outcome: 'blocked'` with their reason
codes persisted for attribution. What goes away is only the side effect on every
later request. A fourth trigger — the run-duration threshold — never fired at
all: `OD_NEXT_STRATEGY_MAX_RUN_DURATION_MS` has no default anywhere, so the
comparison ran against NaN.

What is removed: the table and its migration, the write path and its telemetry
module, the single read in the run route, the reset endpoint, the
`od strategy rollout reset` subcommand, the latched lock in the Labs switch and
its 19 locale strings, and five contract types. `readOdNextRolloutControlStatus`
stays but no longer takes a database — the effective mode is now a pure function
of the requested mode and the content flags, so two callers reading it at the
same moment cannot disagree. Status is still worth an endpoint because
`requestedModeSource` names the authority, and `default` and a saved `off`
resolve to opposite routes.

Installations currently holding a latch recover on their own: with nothing left
to read the row, their next run is admitted normally. No migration needed, and a
downgrade is safe — older code recreates the table, reads it empty, and treats
the installation as unlatched.

Tests carry the invariant rather than a list. The cases that pinned which
signals were allowed to latch are replaced by one that pins the shape: the
decision is a function of the policy and this run's facts and takes no argument
through which an earlier run could reach it, so there is no signal left to
enumerate and none can be added by accident. The real-server case now asserts
that status still reports the deciding authority while both the reset endpoint
and its CLI subcommand are gone.

* fix(daemon): never leave the harness switch stuck, whatever the config says

Field report from a packaged build of this branch: the Design Harness switch
read on, greyed out, with "detected a problem, generation is using the original
approach" underneath, and every task on the machine taking the legacy route.
Nothing in the UI could clear it.

The diagnostics name the cause exactly. One agent turn ended mid-block —
`Unclosed <open-design-plan-contract> block`, 2 characters of visible text — and
that raised `machine_contract_leak`, whose stop mode is `off`, not `observe`. A
truncated response took the whole install off OD Next; the next daemon start
logged `requestedMode: 'active'`, `effectiveMode: 'off'`,
`od_next_rollout_stop_latched`, which is the screenshot.

That is not a rare condition. A stream ending early is the most ordinary failure
an agent has, and flipping the default hands it the entire install base.

Three changes, one property: the switch a user can see is a switch a user can
use.

1. The stop latch is removed (previously PR #7879, folded in here). A build that
   defaults on and still ships an automatic, restart-surviving, UI-unrecoverable
   disable is not shippable as two PRs — the window between them is exactly the
   build that was reported. Everything the latch did on top of the existing
   per-task handling is gone; the per-task handling is untouched.

2. An unreadable saved config no longer reads as an unconfigured one. The read
   path kept two states apart where it needed three: no file at all, a readable
   choice, and a config that exists but cannot be believed — malformed JSON, a
   non-object body, a mode this build does not recognise. The third used to
   collapse into the first harmlessly, because unconfigured meant `off` and so
   did an opt-out. Now unconfigured means `active`, so the same collapse turns
   "we cannot read your choice" into "you chose OD Next", against the
   installations most likely to have chosen the opposite. It resolves to `off`
   instead — the only answer that cannot override a real decision, and the
   recoverable one, since a user who never opted out sees the switch off and can
   turn it back on. `assertWritableControlValues` was never enough here: it
   guards writes through the API and can say nothing about a file that arrived
   bad, was hand-edited, or was written by another version.

3. A failed status read is retried from the switch instead of being permanent.
   It rendered the row locked and lifted only on remount, so a transient failure
   left a control that does nothing. A click on that lock now re-reads. The
   environment lock stays inert deliberately: the daemon would ignore the write,
   and pretending otherwise is worse than doing nothing — and no packaged
   install can reach it, since the packaged child env allowlist carries no
   `OD_NEXT_*`.

After this, the only greyed state a packaged user can reach is the moment before
the first read returns.

Installations already holding a latch recover on their own: with nothing left to
read the row, their next run is admitted normally. No migration, and a downgrade
is safe — older code recreates the table, reads it empty, and treats the
installation as unlatched.

Coverage follows the same split. The config cases run against real files through
`readAppConfig` rather than against the policy reader in isolation, because the
hole was in the join: truncated JSON, a non-object body, an unrecognised mode, a
typo, a non-string — each reads `off`, while a missing file and an explicit
`null` still reach the default. One case asserts the whole chain, saving `off`
then truncating the file and checking the mode survives, with a fresh
installation as the negative control so the guard cannot swallow the rollout it
protects. The UI case fails the first status read, clicks, and asserts the row
becomes operable.

* refactor(daemon): drop the JSDoc left above the removed latch classifier

The block described `MACHINE_CONTRACT_BOUNDARY_CODES` and
`rolloutStopSignalForBlockedContinuation`, both deleted with the stop latch.
Left in place it reads as documentation for the export below it, implying this
service still classifies machine-contract failures when it no longer does.

* fix(daemon): tell operators why `od strategy rollout reset` is gone

The command shipped in 0.21.0 and 0.21.1. Removing it left the subcommand
falling through to the generic usage dump, so an operator who scripted it saw a
list it was simply missing from and had to guess whether the command was
renamed, moved, or broken.

It now names itself: the daemon-instance stop latch it cleared no longer exists,
so there is nothing to reset, and the message points at the two commands that
replaced its use — `od config set odNextStrategyMode off` to opt out, and
`od strategy rollout status` to see which authority decides the mode.

It still exits non-zero rather than succeeding as a deprecated no-op. The
command meant "recover this machine's rollout". Reporting success for a recovery
that neither happened nor can happen is the same lie the latch itself told —
a control that says it acted while nothing changed — and this release is
removing that lie rather than relocating it into the CLI.

* fix(daemon): stop a broken config file from opting an installation out

The previous commit fixed a real hole — a saved `off` could be silently revoked
— but fixed it too widely and in the wrong direction for this rollout. It
treated a config file that failed to parse at all as evidence of an opt-out,
which it is not.

A file that will not parse resets every preference to its default: agent,
telemetry, all of it. Singling this one key out to resolve against its default
was inconsistent with the rest of the file, and the population it hits is the
wrong one — everyone whose config breaks, not everyone who opted out. Since the
second group is a subset of the first, the guard opted more installations out of
the rollout than it protected, in a change whose entire purpose is opting them
in.

The guard now covers only what it can actually see: `odNextStrategyMode` present
with a value that is not one of the modes — a hand edit, a typo, a mode written
by some other version. Something was configured and cannot be read, so it reads
`off` rather than becoming "you chose OD Next". A fresh install, a missing file,
an unparseable file and a config without the key all reach the default, which is
`active`.

That keeps both invariants this step owes: the default is on for anyone who has
not said otherwise, and a user who did say otherwise keeps their answer. The
switch stays operable in every one of these states, so nothing here can leave a
user looking at a control that does nothing.

* style(daemon): drop the blank line left at EOF by the classifier removal

The line separated `resolveAutomaticContinuationEvidence` from the JSDoc and
classifier below it. Removing those left the separator as a trailing blank line,
which `git diff --check` reports. No logic change.

* docs(daemon): stop enumerating which releases shipped `rollout reset`

The comment named 0.21.0 and 0.21.1. 0.22.0 shipped today and carries the
command too, so the enumeration was already wrong the day it was written --
any list of shipped versions goes stale by construction. Say "every release
since 0.21.0" instead, which stays true without maintenance.

The point the sentence is making is unchanged, and slightly stronger: the
surface has been out for three releases, so an operator who scripted it gets
told what happened rather than shown a help list it is missing from.

---------

Co-authored-by: Cheems <216108319+hihicheems@users.noreply.github.com>
2026-09-09 01:37:25 +00:00

171 lines
7.4 KiB
TypeScript

import type http from 'node:http';
import { randomUUID } from 'node:crypto';
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { delimiter, join } from 'node:path';
import { tmpdir } from 'node:os';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
/*
* 红测(W17,2026-09-02):**思考流**里的评审剧场语法也不许进客户端,更不许落库。
*
* 兜底剥离器(`apps/daemon/src/panel-grammar-strip.ts`)是 2026-08-26 为这件事建的,
* 但它当时只挂在 `text_delta` 那条路上:`sendAgentEvent` 里 `text_delta` 过
* `titleMarkerStripper`,其余事件类型一律直接 `emitAgentEvent(ev)` 原样放行。
* `thinking_delta` 就走后面这条 —— **一个剥离器都不过**。
*
* 后果比"正文里露出标签"更糟,因为它会**永久化**:
* `runtimes/chat-run-messages.ts` 的 `daemonAgentPayloadToPersistedAgentEvent`
* 把 `thinking_delta` 原样存成 `{ kind: 'thinking', text }`,而持久化就挂在
* `send()` 里(`server.ts` 的 `persistRunEventToAssistantMessage`)。所以剥离必须发生在
* **`send()` 之前** —— 这也是为什么修复落在 `emitAgentEvent` 的入口,而不是某个适配器。
*
* 断言 SSE 流干净,等价于断言落库干净:两者是同一个 `send()` 的两个消费方,
* 中间没有第二次加工。
*
* 这里用 codex 是因为它是**用户中招的那个 runtime**,而且它的 reasoning item
* (`json-event-stream.ts` 的 `emitCodexReasoningItem`)是本仓最直接的 `thinking_delta` 来源。
* 传输固定成 `exec-json`:出厂默认是 app-server(JSON-RPC),用假 CLI 不好摆,
* 而两条传输在 `sendAgentEvent` 之后汇到同一条路上 —— 剥离的位置与传输无关。
*/
/** 逐字取自用户现场;`role="Critic" score="8.1"` 这一条出现在 Thoughts 展开里 */
const THINKING_LEAK = [
'<ROUND index="2">',
'<PANELIST role="Critic" score="8.1">',
'THINKING_PROSE_SENTINEL_4f21 —— 这句人话必须原样留着。',
'</PANELIST>',
].join('\n');
const ANSWER_PROSE = 'ANSWER_PROSE_SENTINEL_9b03';
/**
* The agent text this run would persist, and nothing else.
*
* The attribute-fragment assertions below run against this rather than against
* the whole SSE body. The body also carries daemon-generated envelope fields
* that can legitimately contain those fragments: `toolTokenExpiresAt`
* (`server.ts`) is an ISO timestamp, so roughly one run in a hundred stamps a
* second ending in `8` with milliseconds starting with `1` — `…:48.161Z`
* contains `8.1`. Asserting on the whole body made this test fail on the clock
* instead of on a leak, which is what it did on 2026-09-08.
*
* This does not weaken the "SSE clean ≡ database clean" argument in the
* docblock above — it is what that argument was always about. Persistence
* consumes exactly these deltas
* (`daemonAgentPayloadToPersistedAgentEvent` turns `thinking_delta` into
* `{ kind: 'thinking', text }`), and nothing else in the envelope reaches an
* assistant message.
*
* The tag assertion stays on the whole body: an opening `<PANELIST` cannot
* appear in an envelope field by accident, so there the wider net costs
* nothing.
*/
function agentDeltaText(sseBody: string): string {
return sseBody
.split('\n')
.filter((line) => line.startsWith('data: '))
.map((line) => {
try {
return JSON.parse(line.slice('data: '.length)) as { type?: string; delta?: unknown };
} catch {
return null;
}
})
.filter((payload): payload is { type: string; delta: string } =>
typeof payload?.delta === 'string'
&& (payload.type === 'thinking_delta' || payload.type === 'text_delta'))
.map((payload) => payload.delta)
.join('');
}
describe('思考流也要过剧场语法剥离', () => {
let server: http.Server;
let baseUrl: string;
let binDir: string;
const originalPath = process.env.PATH;
const originalTransport = process.env.OD_CODEX_TRANSPORT;
beforeAll(async () => {
process.env.OD_CODEX_TRANSPORT = 'exec-json';
binDir = await mkdtemp(join(tmpdir(), 'od-thinking-grammar-'));
const bin = join(binDir, 'codex');
await writeFile(
bin,
`#!/usr/bin/env node
process.stdin.resume();
const line = (o) => console.log(JSON.stringify(o));
line({ type: 'thread.started', thread_id: '019eef4f-0000-7000-8000-0000000abcde' });
line({ type: 'turn.started' });
// 推理摘要 —— 走 thinking_delta。这一片在修复前会原样打到客户端并落库。
line({ type: 'item.completed', item: { id: 'r-1', type: 'reasoning', text: ${JSON.stringify(THINKING_LEAK)} } });
// 正文 —— 走 text_delta,这条路 2026-08-26 起就已经被剥离器盖住了。
line({ type: 'item.completed', item: { id: 'm-1', type: 'agent_message', text: ${JSON.stringify(ANSWER_PROSE)} } });
line({ type: 'turn.completed', usage: { input_tokens: 3, output_tokens: 2 } });
setTimeout(() => process.exit(0), 10);
`,
'utf8',
);
await chmod(bin, 0o755);
process.env.PATH = `${binDir}${delimiter}${originalPath ?? ''}`;
const { startServer } = await import('../src/server.js');
const started = (await startServer({ port: 0, returnServer: true })) as {
url: string;
server: http.Server;
};
baseUrl = started.url;
server = started.server;
// 冷启动要全量扫技能目录 + 设计体系,单跑这个文件时没有前面的文件帮忙暖缓存。
}, 60_000);
afterAll(async () => {
if (server) await new Promise<void>((resolve) => server.close(() => resolve()));
await rm(binDir, { recursive: true, force: true });
if (originalPath == null) delete process.env.PATH;
else process.env.PATH = originalPath;
if (originalTransport == null) delete process.env.OD_CODEX_TRANSPORT;
else process.env.OD_CODEX_TRANSPORT = originalTransport;
});
it('thinking_delta 里的剧场标记不进 SSE(也就不落库),标记之间的人话原样留着', async () => {
const projectId = `thinking-grammar-${randomUUID()}`;
const created = await fetch(`${baseUrl}/api/projects`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: projectId, name: 'Thinking grammar fixture' }),
});
expect(created.ok).toBe(true);
const chat = await fetch(`${baseUrl}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agentId: 'codex',
projectId,
message: 'Draft the page.',
}),
});
expect(chat.ok).toBe(true);
const body = await chat.text();
// 这一轮真的跑完了 —— 否则下面的"没漏"是空的
expect(body).toContain('event: end');
expect(body).toContain('thinking_delta');
// 标签名写死,不复用 `CRITIQUE_GRAMMAR_TAGS`:复用等于拿实现验实现。
expect(body).not.toMatch(
/<\/?(?:CRITIQUE_RUN|ROUND|ROUND_END|PANELIST|SHIP|MUST_FIX|RESOLVED)(?=[\s/>])/u,
);
// 属性碎片也不许剩 —— 这两个字符串只可能来自标记内部
const deltas = agentDeltaText(body);
expect(deltas).not.toContain('Critic');
expect(deltas).not.toContain('8.1');
// 剥壳不吞字:思考里的人话和正文都要在。
// 这两条同时钉住上面两条不是在空串上通过的 —— 提取器一旦选错事件类型就会返回
// 空串,而空串对任何 not.toContain 都成立。
expect(deltas).toContain('THINKING_PROSE_SENTINEL_4f21');
expect(deltas).toContain(ANSWER_PROSE);
}, 60_000);
});