Skip to content

Add agents/ and Oracle, the first fleet agent (local mode) - #56

Merged
joshsiaw merged 16 commits into
mainfrom
oracle-agent
Nov 20, 2026
Merged

joshsiaw merged 16 commits into
mainfrom
oracle-agent

Conversation

@joshsiaw

Copy link
Copy Markdown
Contributor

Summary

Adds agents/ — the first part of a Watchtower agent fleet — and Oracle, its first agent.

Oracle finds places in a codebase that will break when someone changes one side of an unwritten agreement, and proposes the guard that prevents it.

The scanners measure; agents act. Oracle audits a repository for hidden agreements (two or more places that must stay consistent with no type, shared import, test or CI check to warn someone who changes only one), verifies them, and writes a run folder. This PR is local mode only: nothing is published and no pull request is opened. Design and build order: agents/oracle/DESIGN.md.

What's in it

  • agents/README.md — fleet table, configuration, how to run an agent.
  • agents/_shared/ — written once for every agent:
    • config from the same watchtower.config.json (agents.<name> section, per-system overrides); credentials never in the file
    • provider interface with two adapters: anthropic (key from the variable key_env names) and vertex (keyless — Google ADC / Workload Identity Federation)
    • read-only tree tools (list, read, search) confined to the copied tree — .., absolute paths and symlinks refused
    • agent loop (answers handed in as a tool call, wrap-up warning before the turn limit), one retry after a transient provider error, optional spending cap, run folders
  • agents/oracle/ — prompts (versioned like scanner pins), agent.json defaults, and the pipeline: split → audit (one auditor per area, in parallel) → merge duplicates → verify the top findings → report.
  • Reuses engine-config and target-tree: the target is a copy or shallow clone, never read in place.
  • Never falsely clean: an area whose auditor fails is listed as not audited and the run exits non-zero.

Evidence

  • Back-tested on two unrelated codebases by auditing an old snapshot and checking against what broke later: about 1 in 5 findings broke within 5–6 months, about half of those rated high, essentially none invented.
  • First live runs on a ~3,000-file TypeScript monorepo (Vertex, estimates at Anthropic list prices): Sonnet 5.5 $20 / 16 min, Opus 5.5 $28 / 23 min, ~80–90 verified agreements each; their top 10 agreed on 8. Sonnet is the default.

Not in this PR

Comparing with the previous run (step 5), the remote workflow and bundling into dist/, the dashboard summary, proposed fixes as PRs. See Build order in DESIGN.md.

Testing

  • npm test: 640 tests, 634 pass, 0 fail (6 skipped, unchanged). 28 new tests under tests/agents/ with a fake provider — no API calls.
  • npm run build leaves dist/ unchanged (agents are not bundled yet).

Notes for review

  • New runtime dependencies: @anthropic-ai/sdk, @anthropic-ai/vertex-sdk.
  • Spending cap (max_cost_usd) is off by default and counts at Anthropic list prices whatever the provider (an estimate on Vertex).
  • Refusal fallback (Anthropic provider only) is opt-in and off; a declined step fails loudly.

🤖 Generated with Claude Code

joshsiaw and others added 6 commits November 16, 2026 16:31
Oracle finds places that will break when someone changes one side of an
unwritten agreement. This adds the shared agent layer (config with keys only
from the environment, provider interface with an Anthropic adapter, read-only
tree tools, agent loop, spending cap, run folders) and Oracle's steps 1-4 and
7: split, audit, merge, verify, report. Local mode only; nothing is published
and no pull request is opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ether, never drop a file

Areas now carry their parts explicitly, so a split can never lose files (a
real repo lost 134 before). Folders under 4% of the source share one area,
which frees auditors to split the big ones, stepping past any child that holds
most of the code (apps/api -> src -> domains).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cap off by default; fallbacks opt-in

Vertex is how the fleet's other agents reach Claude in CI: no model key, a
short-lived Google credential from the workflow's OIDC token. The spending cap
is now off unless set, and counts at Anthropic list prices whatever the
provider (an estimate on Vertex). Refusal fallbacks are opt-in on the Anthropic
provider; a declined step fails loudly instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ore the turn limit, smaller tool outputs

First real run (Program Intelligence, Opus 5.5 on Vertex) stopped at its $40
cap after 5 of 9 areas: 58% of spend was re-reading the conversation each turn,
and one auditor used all 120 turns without submitting. Now: config/ops and the
largest areas go first; an agent is told to submit when 10 turns remain; the
turn limit is 80; reads and searches return less; the prompt asks for
independent tool calls in one turn (prompt_version 2026-11-17). Also stops grep
writing to the console.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run 2 lost one area to a Vertex 'try again' error that outlasted the SDK's
retries. Never retried: the spending cap, a refusal, an agent with no answer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the same commit Sonnet and Opus agreed on 8 of their top 10 findings; the
variation between runs mattered more than the model, and Sonnet cost ~70%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread agents/oracle/report.js Fixed
…caping or encoding'

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

@maciej-szlosarczyk maciej-szlosarczyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found a few bugs, in review are the tests to reproduce them. You can drop them into code and try to go around and fix them 🙏

Comment thread agents/oracle/schemas.js Outdated
items: {
type: 'object',
properties: {
places: { type: 'array', items: { type: 'string' } },

@maciej-szlosarczyk maciej-szlosarczyk Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
places: { type: 'array', items: { type: 'string' } },
places: { type: 'array', items: { type: 'string' }, minItems: 1 },

Not a bug, but extra spec: At least one place must exist.

Comment thread agents/oracle/schemas.js Outdated
items: {
type: 'object',
properties: {
places: { type: 'array', items: { type: 'string' } },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
places: { type: 'array', items: { type: 'string' } },
places: { type: 'array', items: { type: 'string' }, minItems: 1 },

At least one place must exist.

assert.equal(a, b);
assert.notEqual(a, fingerprint(['a.ts', 'c.ts']));
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bug I found given Next.js naming convention for folders:

test('folders can have parenthesis in their names', () => {
  assert.equal(placeFile('app/(marketing)/page.tsx:12'), 'app/(marketing)/page.tsx');
});

assert.equal(run.status, 'incomplete');
assert.ok(run.counts.raw_findings >= 1);
assert.match(fs.readFileSync(path.join(runDir, 'report.md'), 'utf8'), /stopped at the spending cap/);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Few more tests:

test('"failed" status is not overriden by "incomplete"', async () => {
  const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-oracle-run-'));
  const meter = new CostMeter({ prices: { m: { input: 4000, output: 20000 } }, capUsd: 5, reserveUsd: 0, model: 'm' });
  const run = await runOracle({
    systemKey: 'web', settings: { ...SETTINGS, concurrency: 1 }, defaults: DEFAULTS, agentDir: AGENT_DIR,
    provider: scriptedProvider({ failArea: CONFIG_AREA }), treeDir: fixtureTree(), runDir, meter,
  });
  assert.deepEqual(run.not_audited, [CONFIG_AREA, 'src']);
  assert.ok(run.problems.some((p) => p.includes('model declined')));
  assert.equal(run.status, 'failed');
});

test('two findings in the same file report separately', async () => {
  const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-oracle-run-'));
  await runOracle({
    systemKey: 'web', settings: SETTINGS, defaults: DEFAULTS, agentDir: AGENT_DIR,
    provider: scriptedProvider({ mergeApart: true, reject: '(src)' }), treeDir: fixtureTree(), runDir, meter: new CostMeter({}),
  });
  const { findings, rejected } = JSON.parse(fs.readFileSync(path.join(runDir, 'findings.json'), 'utf8'));
  const verdicts = Object.fromEntries([...findings, ...rejected].map((f) => [f.agreement, f.verification.verdict]));
  assert.deepEqual(verdicts, {
    'port copied (config and operations)': 'confirmed',
    'port copied (src)': 'rejected',
  });
});

test('an area is not retried after the model says the conversation is too long', async () => {
  const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-oracle-run-'));
  const provider = scriptedProvider({ tooLongArea: 'src' });
  await runOracle({
    systemKey: 'web', settings: SETTINGS, defaults: DEFAULTS, agentDir: AGENT_DIR,
    provider, treeDir: fixtureTree(), runDir, meter: new CostMeter({}),
  });
  assert.equal(provider.tooLongAttempts, 1);
});

Comment thread tests/agents/oracle.test.js Outdated

// --- pipeline end to end, with a scripted provider -------------------------

function scriptedProvider({ failArea, flakyArea } = {}) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update to this to trigger the tests below:

function scriptedProvider({ failArea, flakyArea, mergeApart, reject, tooLongArea } = {}) {
  let flaked = false;
  const provider = {
    tooLongAttempts: 0,
    conversation({ system }) {
      const kind = /Group findings/.test(system) ? 'merge' : /Check findings/.test(system) ? 'verify' : 'audit';
      return {
        async send(content) {
          const usage = { input: 1000, output: 200 };
          if (kind === 'audit') {
            const area = String(content).match(/starting area: (.*)\n/)?.[1] || '';
            if (failArea && area === failArea) return { toolCalls: [], text: '', stop: 'refusal', usage, model: 'm' };
            if (flakyArea && area === flakyArea && !flaked) { flaked = true; throw new Error('Unable to complete this request right now'); }
            if (tooLongArea && area === tooLongArea) {
              provider.tooLongAttempts += 1;
              throw Object.assign(new Error('prompt is too long'), { status: 400 });
            }
            return {
              stop: 'tool', usage, model: 'm', text: '',
              toolCalls: [{
                id: 's', name: 'submit_findings', input: {
                  findings: [{ places: ['package.json', 'src/a.ts:1'], agreement: `port copied (${area})`, unguarded: 'no shared const', trigger: 'change one', effect: 'e2e fails', fix: 'shared const', likelihood: 'high', harm: 'medium' }],
                  current_bugs: area === CONFIG_AREA ? [{ places: ['src/a.ts'], what: 'open endpoint', security: true }, { places: ['package.json'], what: 'stale doc' }] : [],
                },
              }],
            };
          }
          const items = JSON.parse(content);
          if (kind === 'merge') {
            const groups = mergeApart ? items.map((i) => [i.id]) : [items.map((i) => i.id)];
            return { stop: 'tool', usage, model: 'm', text: '', toolCalls: [{ id: 'g', name: 'submit_groups', input: { groups } }] };
          }
          return { stop: 'tool', usage, model: 'm', text: '', toolCalls: [{ id: 'v', name: 'submit_verdicts', input: { verdicts: items.map((i) => ({ id: i.id, verdict: reject && i.agreement.includes(reject) ? 'rejected' : 'confirmed', note: 'read both' })) } }] };
        },
      };
    },
  };
  return provider;
}

assert.equal(warned.length, 1);
assert.equal(warned[0][1], 4); // turn 5 of 15: ten turns left
assert.match(warned[0][0], /10 turns left.*submit_answer/);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug repro:

test('the model is told it has ten turns left even if its previous reply was text', async () => {
  const root = tmpTree({ 'a.ts': 'x' });
  const listFiles = { stop: 'tool', toolCalls: [{ id: 't', name: 'list_files', input: {} }] };
  const p = fakeProvider([listFiles, listFiles, listFiles, { stop: 'end', text: 'thinking out loud' }, listFiles]);
  const notes = [];
  const provider = {
    conversation(opts) {
      const c = p.conversation(opts);
      return { send: (content, extra) => { notes.push(extra && extra.note); return c.send(content); } };
    },
  };
  await assert.rejects(
    runAgent({ provider, system: 's', prompt: 'go', tools: treeTools(root), submit: SUBMIT, meter: new CostMeter({}), maxTurns: 15 }),
    /no answer after 15 turns/,
  );
  assert.deepEqual(notes.filter(Boolean), [
    '10 turns left. Finish what you are checking and call submit_answer with what you have confirmed.',
  ]);
});

assert.deepEqual(out, [2, 4, 6, 8, 10]);
assert.equal(peak, 2);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more bug repro:

test('concurrent agents do not exceed the cost cap', async () => {
  const meter = new CostMeter({ prices: { m: { input: 1000, output: 0 } }, capUsd: 1.2, reserveUsd: 0.5, model: 'm' });
  const provider = fakeProvider([{ stop: 'tool', toolCalls: [{ id: 's', name: 'submit_answer', input: {} }], usage: { input: 1000, output: 0 } }]);
  await mapLimit([1, 2, 3], 3, () => runAgent({
    provider, system: 's', prompt: 'go', tools: treeTools(tmpTree({ a: '' })), submit: SUBMIT, meter,
  }).catch((err) => { if (!(err instanceof CostCapError)) throw err; }));
  assert.ok(meter.summary().usd <= 1.2, `spent $${meter.summary().usd} against a $1.20 cap`);
});

joshsiaw and others added 9 commits November 20, 2026 15:02
Next.js route groups name folders like app/(marketing)/page.tsx. placeFile
cut every place at its first parenthesis, so such a file became 'app/' and
fingerprints collided. Only a parenthesis after the file name, with no
folder after it, is now treated as commentary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reaching the cap set the status to incomplete even after an area had
already failed, so the run read as merely stopped. Whether the cap was
reached is now its own flag; failed outranks incomplete. The test's
scripted provider gains Maciej's options for the next fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The verifier was given each finding's fingerprint as its id. Two
agreements between the same files share a fingerprint, so both took the
last verdict returned: a confirmed finding could be reported as rejected.
Findings are now numbered by position for the verifier.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An area was retried after any provider error, including a 400 such as
"prompt is too long", which fails the same way twice and pays twice.
A 4xx other than 408, 409 and 429 is no longer retried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The wrap-up note was only attached to tool results. When the turn ten
before the limit followed a text reply (so it carried the nudge instead),
the agent was never warned. The note now rides on whatever that turn sends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Covers the CodeQL fix in f310147. Fails against the escaping before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agents running at once share one meter, but each checked only spent +
reserve before its call, so all of them could start on the same headroom:
three agents spent $3 against a $1.20 cap. The meter now holds room for
the calls still running. Until a call has finished they run one at a time;
after that each running call is held at the larger of the reserve and the
most expensive call seen. A call that does not fit waits while others run
and is refused when none are. The hold is released when a send finishes,
whether it succeeded or threw. beforeCall is now async and resolves to that
release function. One agent alone checks spent + reserve as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A new call that would run beside others is now held at the larger of the
reserve and the most expensive call seen, like the calls already running;
one agent alone still checks spent + reserve. cost.js now says that waiters
are not served in order and that the cap bounds the estimate, not the bill.
run.js says a run that hit the cap and also failed exits 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@joshsiaw

Copy link
Copy Markdown
Contributor Author

Thanks for the repro tests. All of them are in verbatim, each one failed before its fix, and each passes now. npm test reports 649 tests: 643 pass, 0 fail, and 6 are skipped because Elixir isn't installed locally.

  • Parentheses in folders (d86c11c). placeFile keeps route-group folders such as app/(marketing)/page.tsx, and still trims a.ts(PORT). Fingerprints for files under such folders change once.
  • Failed vs incomplete (f7c7365). A separate capped flag now drives stop-on-cap, so failed is never downgraded. A run that hit the cap and also failed exits 1.
  • Two findings in one file (2397122). The checker now gets positional ids, so findings that share a fingerprint no longer receive each other's verdict.
  • Too long, not retried (e20a53d). A 4xx is not retried, except 408, 409 and 429. 5xx responses and errors without a status are still retried once.
  • Ten turns left (1000059). The note is attached whenever ten turns remain, whatever the turn carries. It is sent once.
  • Concurrent cost cap (60ab18d, 7dbfdb0).
    • The meter now accounts across agents. beforeCall is async and returns a release.
    • Until the first call finishes, calls run one at a time.
    • After that, each in-flight call, and any new one, is held at the larger of the reserve and the most expensive call seen so far.
    • A call that doesn't fit waits for the in-flight calls to finish. It is refused only when nothing is running.
    • A send that throws releases its hold.
    • Your test is unchanged. With a $0.50 reserve against $1 calls, a plain reserve-then-settle approach would still have spent $2, which is why it is built this way.
  • minItems: 1 on places in both schemas (590925f).
  • CodeQL backslash escaping. A test now covers it (07d2ffe).

Ready for another look.

@joshsiaw
joshsiaw added this pull request to the merge queue Nov 20, 2026
Merged via the queue into main with commit 7e59d79 Nov 20, 2026
5 checks passed
@joshsiaw
joshsiaw deleted the oracle-agent branch November 20, 2026 14:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants