Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
297 changes: 297 additions & 0 deletions docs/dev-loop-runs/2026-12-01-tool-system/00-audit.md

Large diffs are not rendered by default.

184 changes: 184 additions & 0 deletions docs/dev-loop-runs/2026-12-01-tool-system/01-design.md

Large diffs are not rendered by default.

37 changes: 37 additions & 0 deletions docs/dev-loop-runs/2026-12-01-tool-system/02-review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 审计与设计复核记录

2026-12-01,main a91f643。仅审计与设计,不是实现验收。

## 审计独立复核

Reviewer: audit_review,code-reviewer,结论 APPROVE。

独立重跑 main-repro.mjs 与 main-trace-repro.mjs,均 exit0,核对核心结论与保存输出一致,37工具计数正确。修正入口引用为tools.ts107/152/189;补明默认Runtime注入launchWork/nudge,缺callback属于自定义Registry配置缺口;补齐artifact重跑README。

新增main-contracts.mjs由主审计运行:5项正确行为契约均失败,exit1。原始脚本和失败输出已保存。复现脚本exit0与安全契约exit1不可混为产品通过。

## 架构审查

Reviewer: design_review,architect。

第一轮 REQUEST_CHANGES:

1. 模块归属错误:M2=Store、M9=Env,不能写成M2=Env/M5=Store。
2. 子session不能隐式继承父memory与speculative工作区;需要明确授权、输入/产出交接和父终止清理。
3. 四个工作流不应合成四个过大PR,应逐concern交付,共享文件串行交接。

修订:模块归属已更正;child使用独立host身份,memory/read_object不开放,父按ACL提供任务片段;WorkspaceLease与受控manifest/artifact交接;speculative父禁止spawn;父终止撤销lease、传播取消、按真实进程状态清理;重启保留unknown不自动重放。四工作流拆为小PR并按依赖串行集成。

第二轮 APPROVE,无新的必须修正项。审查明确:接口与方案本身不能证明实际取消、ACL或sandbox实现正确,后续需要具体回归测试和实现审查。

## 本地验证与未完成范围

- pnpm typecheck:exit0。
- 13个定向测试文件:89 passed,exit0。
- 独立边界3文件:37 passed,与89项部分重叠。
- pnpm lint首次因sandbox禁止tsx IPC pipe失败;等价执行 `NODE_NO_WARNINGS=1 node --import tsx scripts/lint.ts`,lint ok。最终提交前再次检查新增tracked文件。
- git diff --check:通过。
- 未执行完整离线套件、coverage、live模型、真实浏览器driver或生产副作用。
- 尚未修改运行时源码;无实现PR、无集成验证,所有已复现bug仍存在于基线。

下一步为owner审阅01-design.md,随后按技能流程编写实施计划、先锁定失败回归,再逐项实现和独立审查。
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# M1 Tool System Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use subagent-driven-development or executing-plans to implement task-by-task, with TDD and independent review.

**Goal:** Implement owner-approved 01-design.md and close audit B01–B15 with executable evidence.
**Architecture:** Catalog is the sole discovery/authorization source; executor validates, claims and observes calls. Domain handlers retain ACL/approval checks. Real bounded child executions replace timer-only success.
**Tech Stack:** Node22, TypeScript, pnpm, Vitest, MCP SDK, OpenTelemetry, SQLite.

## Global constraints

Owner approved design on 2026-12-02. Implementation base origin/main 49aad78c9f09816be71e1f161790d9f025410d00; audit remains historical a91f643. One concern per PR, no main commits/force pushes/protection bypass. Runtime policies, memory ACL, PR/fill approvals remain enforced. No production restart or external sending. Only root updates state/master plans. Existing PR274/276/278/279 are independent; trace changes must preserve compatible APIs. Every behavior change starts with a failing real-path test. No hidden scope reduction: all tasks remain required until acceptance.

## File ownership and task order

### Task A — Tool-call protocol (parallel independent slice)
Files: src/harness/model.ts, src/harness/loop.ts, new src/harness/tool-calls.ts, test/tool-call-protocol.test.ts. Owner protocol implementer in .worktrees/tool-call-protocol.
Interfaces: validateToolCalls(value: unknown): ToolCall[]; throws safe protocol error for malformed/duplicate IDs. Both adapters and runTurn consume it; reject the entire malformed batch before execution. A turn must not execute a repeated call ID on a later step. No global dedup across turns. Preserve valid images/replay and provider conversion.
- [ ] Write fetch-stub HttpOpenAI/Anthropic tests for null/arrays/scalars/empty names/IDs, duplicate IDs, mixed batches; real runTurn fixture counts executor calls and verifies zero side effects for invalid batches.
- [ ] Run pnpm run test test/tool-call-protocol.test.ts and save expected failures under /private/tmp/lofibot-tool-implementation/protocol-red.txt.
- [ ] Implement shared parser/batch validation, apply before journal/tool dispatch, add structured safe error code without raw args.
- [ ] Run focused model, memory/approval replay, Phoenix suites; typecheck/lint/full offline test before PR.
- [ ] Commit scoped implementation and report SHA/evidence; independent review before PR integration.

### Task B — M9 bounded UTF8 output (parallel independent slice)
Files: src/env/local-env.ts, new src/env/bounded-output.ts if justified, test/local-env-output.test.ts. Owner env implementer in .worktrees/tool-env-output. No approval or file-path behavior changes.
Interfaces: shell return code/stdout/stderr preserved; maxOutputBytes bounds each returned stream including marker, UTF8 remains valid at chunk/truncation boundaries.
- [ ] Write subprocess tests split UTF8 across chunks, CJK byte caps, stdout/stderr independent limits, exact cap/zero output, timeout existing semantics.
- [ ] Run focused test and preserve RED output.
- [ ] Implement byte-bound per-stream decoder; preserve process-group cleanup and redaction.
- [ ] Run LocalEnv/symlink/hardening tests and all required gates before PR; commit only owned files.

### Task C — MCP discovery/cancellation (parallel independent slice)
Files: src/harness/mcp.ts, test/mcp-source.test.ts, test/mcp-invoke.test.ts, new test/fixtures MCP protocol fixtures. Owner MCP implementer .worktrees/tool-mcp-runtime. Artifact security is separate subsequent commit/PR; do not mix.
Interfaces: existing McpToolSourceLike compatible, optional refresh/diagnostics only if needed. Invoke requires a discovered exact name; failed discoveries retry; list_changed invalidates catalog. Deadline propagates AbortSignal and timeout is controlled OUTCOME_UNKNOWN, retryable false after request sent. No claim that server cancellation undoes effects.
- [ ] Write stdio fixture tests undiscovered name zero calls, discovery recovery/change invalidation, on-deadline cancellation and ignored-cancel late result classification.
- [ ] Run and preserve RED tests.
- [ ] Implement discovery state/allowlist and cancellation without duplicate requests or automatic retries of unknown work. Keep schema names stable for integration; aliases handled later in catalog.
- [ ] Run MCP config/source/runtime/invoke suites and required gates, scoped commits separating discovery and cancellation; report evidence.

### Task D — Catalog/schema/executor foundation (after A, can prepare while A–C run)
Files: src/harness/tools.ts facade; new src/harness/tools/{types,catalog,validation,executor}.ts; package.json/pnpm-lock.yaml; builtin extraction files; test/tool-catalog.test.ts and test/tool-validation.test.ts. Root coordinates implementer.
Interfaces: ToolCatalog snapshots definitions/status/reasons; ToolExecutor resolve→current permission→schema→handler, compatibility invoke returns original payload. One direct locked validator, no remote refs/defaults/coercion. Memory/MCP pass same boundary. Execution context is host-built, not model args.
- [ ] Convert audit main-contracts into Vitest failures: wrong command/missing body, unknown MCP, unavailable teams/publisher, stopped foreign jobs; assert handler I/O remains zero.
- [ ] Implement strict per-tool required/optional schemas; nested approval schemas, memory schemas and members array/legacy replay compatibility; controlled errors.
- [ ] Extract handlers by domain preserving ACL/approval logic; remove create_worker from new model surface; false capabilities unavailable with diagnostics.
- [ ] Add CLI tools --role/--json with no-discovery default and explicit discovery mode, no model/network runs by default.
- [ ] Run matrix role/config/restriction/sessions, validation error secret tests, full gates and independent code/security review.

### Task E — Job/Team real execution and cancellation
Files: src/harness/jobs.ts (new), team.ts, loop.ts, tools/builtin/worker.ts, src/shared/{types,ports}.ts, src/store/{schema,sqlite}.ts, runtime.ts, env workspace lease adapter, job/team/regression tests. Serial ownership after protocol and catalog integration.
Interfaces: durable Job execution identity/task/owner/executor, lifecycle outcome distinct from completion delivery; bounded child session uses host authorization. Child cannot parent-report/approve/publish/subscribe/delegate recursively or access memory/read_object; explicit input manifests/artifact handoff. Speculative spawn disabled.
- [ ] Port jobs-audit queue barriers to deterministic Vitest (wait for pending condition, no fixed sleep as proof); foreign stop, pending stop, restarted stopped pending, team/job mismatch all RED.
- [ ] Implement cancellation/receipt CAS and dequeue checks; preserve normal succeeded pending recovery. Stop returns actual terminal or cancel_requested status.
- [ ] Add schema migration for real child attempts; legacy timer-only running records become unavailable, never auto-success; preserve historical rows.
- [ ] Implement bounded child model turn task with own session/workspace; at least two tasks produce distinct real outputs. Parent termination revokes leases and cancels. On restart, interrupted child turns are unknown unless an explicit durable checkpoint proves safe continuation; the current text-only executor has no such checkpoint, so it must not replay them. The parent can inspect the retained result/unknown state before starting a new task.
- [ ] Team aggregates job facts; complete_team refuses running members. Add failure/budget/cancel/sandbox/artifact/memory denial tests.
- [ ] Run full gates, independent code/security/QA; small PRs for ownership, state machine, child execution, team aggregation.

### Task F — Artifact security and provider names
Files: new src/harness/artifacts.ts or M9 artifact adapter, src/harness/mcp.ts, catalog integration, M2 metadata storage/tests. Serial ownership after C.
- [ ] RED fixture tests unredacted resource text, symlink directory escape, unsafe modes, per-call and cumulative limits, MIME mismatch classification, long-name mapping/collisions.
- [ ] Implement predecode bounds, private no-follow storage, quota and ACL artifact metadata, retention references and cleanup; no automatic deletion of referenced artifacts. Maintain spill/image compatibility.
- [ ] Normalize provider names to stable bounded aliases with collision checks; schema snapshots reject stale calls rather than silently adapting.
- [ ] Add LocalEnv read-size cap without weakening descriptor checks. Run all artifact/MCP/memory/path suites and full gates; independent security review.

### Task G — Executor facts, trace and diagnostics
Files: tools/executor.ts, tools/audit.ts, harness/tracing.ts, loop.ts, runtime.ts, cli diagnostics, versioned desktop tool events if compatible with PR276, docs/PHOENIX.md; tracing/transport tests.
- [ ] RED real runTurn tests model_failed/exit1/approval_wait/budget_exhausted and complete manifest under long history; host deferred call must have exactly one tool execution span.
- [ ] Add host turn/step/execution IDs and durable receipts; trace registered tool name, safe error/outcome, separate catalog/history budgets. No raw exception/secret export.
- [ ] Expose requested/initialized/export_failed diagnostics without requiring collector success for execution. Preserve approved PR278/279 APIs when integrated separately.
- [ ] Verify CLI diagnostics and desktop start/result/hold events independently from Phoenix; no invented historic payloads.
- [ ] Full offline tests/typecheck/lint/build/coverage as required CI, independent code/security/QA review. Record live limitations, PR URLs/CI and postmerge verification.

## Review and delivery

Each small concern gets RED/GREEN evidence, scoped commit, independent spec/code review (security for untrusted input/I/O). Required local typecheck/lint/test before opening PR; observe exact-head CI before ordinary merge, retain owner merge gate for high-risk changes. Do not present a partial slice as entire redesign complete. Final acceptance maps each B01–B15 to code/test/review/PR/integration evidence.
31 changes: 31 additions & 0 deletions docs/dev-loop-runs/2026-12-01-tool-system/artifacts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# 修复前复现证据

基线 a91f6435c5811d970d3cecdc316b5bfb8f434d31,2026-12-01。

这些脚本为了审计有意断言当前错误行为。exit 0 证明复现成立,不证明修复通过。实现时必须将相应预期反转,形成真正的失败→通过回归测试。

例外是 `main-contracts.mjs`:它断言应有的安全契约,修复前实跑 exit 1、5项失败,日志为 `main-contracts.txt`。此脚本可直接作为红灯反馈环。

原始运行输出按执行时内容保留。复现脚本的源码导入现指向运行脚本所在的checkout;历史输出仍绑定审计时的基线SHA。

从仓库根目录运行(Node.js 22.15.0+,已执行 `pnpm install --frozen-lockfile`):

```sh
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/main-repro.mjs "$PWD"
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/main-contracts.mjs "$PWD"
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/main-trace-repro.mjs "$PWD"
Comment thread
LofiSu marked this conversation as resolved.
Resolved
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/jobs-audit.mjs
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/boundaries.mjs
node --import tsx docs/dev-loop-runs/2026-12-01-tool-system/artifacts/mcp-audit.mjs
```

`jobs-audit.mjs` 和 `mcp-audit.mjs` 在系统临时目录创建各自的运行目录;MCP服务脚本使用本目录提交的 `server.mjs`。MCP脚本会清理并重建自己命名的mcp-case-*子目录,然后写入临时二进制资源和协议日志;不要指向用户数据目录。jobs脚本用20ms等待fixture timer,再以同session队列barrier控制竞争窗口,输出必须检查pending确实存在,不能只看exit状态。历史复现脚本面向审计基线;当前修复版可能产生不同结果,应以对应SHA和测试断言解释差异。

- `main-repro.*`:真实 registry 分发、stub executor、副作用计数和OpenAI解析。
- `main-trace-repro.*`:真实 SDK、内存exporter、runTurn和原始capture函数。
- `jobs-*`:实际Runtime、队列屏障、持久completion、取消和provider反例。
- `mcp-*`、`server.mjs`:真实stdio协议;取消、发现、版本、落盘、限额。case-*的server.jsonl为原始运行快照。
- `boundaries.*`、`boundaries-output.jsonl`:本地shell的中文输出和临时文件边界。
- `main-existing-tests.txt`:13文件89项通过。`boundaries-tests.txt`:3文件37项通过,与前者部分重叠。

所有凭据样式和 TOKEN_AUDIT_SENTINEL 都是合成字符串,未连接真实模型/外部服务。大二进制fixture未复制入Git;长度和原始协议证据保留在结果文件。
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{"case":"utf8_byte_limit","configured":10,"actualBytes":42,"text":"你你你你你你你你你你\n[truncated]"}
{"case":"split_utf8","expected":"你","actual":"���"}
{"case":"explicit_private_allowed","input":"http://127.0.0.1:99/path","result":"http://127.0.0.1:99/path"}
{"case":"explicit_private_allowed","input":"http://169.254.169.254/latest/meta-data","result":"http://169.254.169.254/latest/meta-data"}
{"case":"explicit_private_allowed","input":"http://2130706433/path","result":"http://127.0.0.1/path"}
{"case":"file_boundary","p":"../outside","error":"path escapes workspace"}
{"case":"file_boundary","p":"link","error":"path escapes workspace: symlinks are not allowed"}
Loading