Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ All notable changes to NanoClaw will be documented in this file.

## [Unreleased]

- **The guard seam.** Every privileged action crossing the container or channel boundary now passes ONE decision function — `guard()` in the new `src/guard/` leaf — before it executes: `allow`, `hold` (through the flow's existing approval mechanics), or `deny`. The keyed registries (ncl commands, delivery actions) wrap their handlers at registration, so the guarded path is the only path by construction: every ncl command derives its guard from its own definition inside `register()`, and a delivery action registers with a guard spec or an explicit `unguarded(<reason>)` declaration — omission doesn't compile, and `grep "unguarded("` is the complete justified inventory. The broadcast hooks (response handlers, message interceptors) stay plain registrations; the one privileged click path — channel registration — consults the guard inline in its handler, like the a2a route and the unknown-sender gate. Consults carry the branded `GuardedAction` value returned by `defineGuardedAction`, so a typo'd or dropped wiring is a compile error and a forged value is denied at runtime — never a fail-open. The decision is today's checks verbatim (cli_scope enforcement, create_agent's scope branch, a2a destination ACL + `agent_message_policies` hold, self-mod unconditional hold, unknown_sender_policy, channel-registration click auth, host-as-trusted-caller in code). Policy-as-data (tighten-only rule sources composing with the decision) is deliberately deferred — a generalized rules table can arrive later, with its first operator-visible consumer. Approved replays now carry the verified approval row as a **grant** — the `approved: true` boolean is deleted — and the guard re-runs the structural checks on every replay. Two outcome changes are inherent to that replay semantics and ship deliberately: **(a)** approving a held a2a message after its destination was revoked no longer delivers it (the checks re-run live; the refusal is an expected policy outcome — the requester is told "approved, but not delivered" and the host logs a warning, not a handler crash); **(b)** a forged, already-consumed, or wrong-action/wrong-payload grant refuses the replay instead of executing (previously any in-process caller passing `approved: true` executed). Zero rules ship by default — the seeded posture is today's behavior. (The D1/D2/D4 click-auth fixes from the guarded-actions defect inventory are NOT in this change — they belong to the approval-contract PR.)
- **Delivery-registry hardening.** Re-registering a guard-wrapped delivery action *without* a guard spec now throws at registration — previously that silently replaced the guarded handler while the catalog still reported the action as guarded. (The cross-registry pairing — every holding action has a registered approve continuation — is enforced by the conformance test; at runtime a missing continuation already resolves loudly, telling the requester no handler is installed.)
- [BREAKING] **`whatsapp-formatting` and `slack-formatting` container skills moved from trunk to the `channels` branch.** They now install with their channel — `/add-whatsapp` / `/add-slack` and the setup installers copy them in — so installs without those channels stop carrying channel-specific formatting instructions in every agent's context. **Migration — only if this install has the channel wired** (check `src/channels/whatsapp.ts` / `src/channels/slack.ts`): updating removes both skills from the working tree — WhatsApp agents lose the formatting fragment from their composed CLAUDE.md on next spawn, Slack agents lose the mrkdwn skill from `~/.claude/skills`. Re-run the matching skill, `/add-whatsapp` or `/add-slack` (idempotent), to restore. Installs without the channel need nothing — do NOT run the add-skill just in case; it installs the full channel adapter.
- **Pre-task script failures back their series off instead of spinning.** A `--script` that errors lands the occurrence as a failed run (`script-skip:error` ack → `failed` status); recurrence reads the series' trailing failed streak and re-arms at `max(cron next, now + 2·2^(n−1) min, cap 60)`; after 8 consecutive failures the series is auto-paused with a host-written note in its run log (`ncl tasks resume` revives it). A deliberate `wakeAgent:false` gate is a normal run and never backs off. Also fixed: an explicitly-addressed `<message to>` in a task fire's final text now delivers as a deliberate send (previously suppressed as a turn-reply echo → zero delivery when the agent skipped the MCP tool); identical echoes of an MCP send are dropped in the runner, where the duplication originates.
- [BREAKING] **Scheduled tasks moved from MCP tools to `ncl tasks`.** The six scheduling MCP tools are no longer exposed to agent containers; agents and operators manage tasks with `ncl tasks list/get/create/update/cancel/pause/resume/delete`. New tasks run from a per-agent-group system session rather than waking the chat session that created them, and task writes are not approval-gated inside the owning group. **Migration:** [docs/ncl-tasks-migration.md](docs/ncl-tasks-migration.md).
Expand Down
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,12 @@ For ad-hoc queries from skills or scripts, use the in-tree wrapper rather than t
| `src/index.ts` | Entry point: init DB, migrations, channel adapters, delivery polls, sweep, shutdown |
| `src/router.ts` | Inbound routing: messaging group → agent group → session → `inbound.db` → wake |
| `src/delivery.ts` | Polls `outbound.db`, delivers via adapter, handles system actions (schedule, approvals, etc.) |
| `src/delivery-guard.ts` | `DeliveryGuardSpec` + `runGuarded` — the precheck → guard → deny/hold/allow consult path for privileged delivery actions; the registry itself stays in `delivery.ts` |
| `src/host-sweep.ts` | 60s sweep: `processing_ack` sync, stale detection, due-message wake, recurrence |
| `src/session-manager.ts` | Resolves sessions; opens `inbound.db` / `outbound.db`; manages heartbeat path |
| `src/container-runner.ts` | Spawns per-agent-group Docker containers with session DB + outbox mounts, OneCLI `ensureAgent` |
| `src/container-runtime.ts` | Docker CLI wrapper (runtime binary, host-gateway args, mount args), orphan cleanup |
| `src/guard/` | Privileged-action decision seam: `guard(action, input)` → allow \| hold \| deny. Domain-free leaf; domain decisions are `defineGuardedAction` values exported from module-edge `guard.ts` adapters (cli, agent-to-agent, self-mod, permissions) — consults hold the value, so a missing/typo'd wiring is a compile error, never a fail-open. The keyed registries (ncl commands, delivery actions) demand a guard at registration (derived spec or explicit `unguarded(<reason>)`); broadcast hooks stay plain registrations, and the privileged click path — the channel-registration card handler — consults the guard inline, like the a2a route and the unknown-sender gate (the free-text name reply is deliberately not re-authorized; the click is the auth, as on main). Approved replays carry the approval row as a grant and re-run the structural checks. Policy-as-data (a runtime rules table) is deliberately deferred. Conformance test: `src/guard/conformance.test.ts` |
| `src/modules/permissions/access.ts` | `canAccessAgentGroup` — owner / global admin / scoped admin / member resolution against `user_roles` + `agent_group_members` |
| `src/modules/approvals/primitive.ts` | `pickApprover`, `pickApprovalDelivery`, `requestApproval`, approval-handler registry |
| `src/command-gate.ts` | Router-side admin command gate — queries `user_roles` directly (no env var, no container-side check) |
Expand Down
6 changes: 6 additions & 0 deletions src/cli/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ export function registerResource(def: ResourceDef): void {
if (def.operations.list) {
register({
name: `${def.plural}-list`,
action: `${def.plural}.list`,
description: `List all ${def.plural}.`,
access: def.operations.list,
resource: def.plural,
Expand All @@ -414,6 +415,7 @@ export function registerResource(def: ResourceDef): void {
if (def.operations.get) {
register({
name: `${def.plural}-get`,
action: `${def.plural}.get`,
description: `Get a ${def.name} by ID.`,
access: def.operations.get,
resource: def.plural,
Expand All @@ -426,6 +428,7 @@ export function registerResource(def: ResourceDef): void {
if (def.operations.create) {
register({
name: `${def.plural}-create`,
action: `${def.plural}.create`,
description: `Create a new ${def.name}.`,
access: def.operations.create,
resource: def.plural,
Expand All @@ -437,6 +440,7 @@ export function registerResource(def: ResourceDef): void {
if (def.operations.update) {
register({
name: `${def.plural}-update`,
action: `${def.plural}.update`,
description: `Update a ${def.name}.`,
access: def.operations.update,
resource: def.plural,
Expand All @@ -448,6 +452,7 @@ export function registerResource(def: ResourceDef): void {
if (def.operations.delete) {
register({
name: `${def.plural}-delete`,
action: `${def.plural}.delete`,
description: `Delete a ${def.name}.`,
access: def.operations.delete,
resource: def.plural,
Expand All @@ -464,6 +469,7 @@ export function registerResource(def: ResourceDef): void {
const declared = op.args;
register({
name: `${def.plural}-${verb.replace(/ /g, '-')}`,
action: `${def.plural}.${verb.replace(/ /g, '.')}`,
description: op.description,
access: op.access,
resource: def.plural,
Expand Down
91 changes: 48 additions & 43 deletions src/cli/delivery-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,52 +8,57 @@
import type Database from 'better-sqlite3';

import { registerDeliveryAction } from '../delivery.js';
import { unguarded } from '../guard/index.js';
import { insertMessage } from '../db/session-db.js';
import { log } from '../log.js';
import { dispatch } from './dispatch.js';
import type { RequestFrame } from './frame.js';
import type { Session } from '../types.js';

registerDeliveryAction('cli_request', async (content, session, inDb) => {
const requestId = content.requestId as string;
const command = content.command as string;
const args = (content.args as Record<string, unknown>) ?? {};

if (!requestId || !command) {
log.warn('cli_request missing requestId or command', { sessionId: session.id });
return;
}

const req: RequestFrame = { id: requestId, command, args };
const ctx = {
caller: 'agent' as const,
sessionId: session.id,
agentGroupId: session.agent_group_id,
messagingGroupId: session.messaging_group_id ?? '',
};

log.info('CLI request from agent', { requestId, command, sessionId: session.id });

const response = await dispatch(req, ctx);

// Write response to inbound.db so the container can read it.
// trigger=0: don't wake the agent — this is an inline response to a tool call.
insertMessage(inDb, {
id: `cli-resp-${requestId}`,
kind: 'system',
timestamp: new Date().toISOString(),
platformId: null,
channelType: null,
threadId: null,
content: JSON.stringify({
type: 'cli_response',
requestId,
frame: response,
}),
processAfter: null,
recurrence: null,
trigger: 0,
});

log.info('CLI response written', { requestId, ok: response.ok, sessionId: session.id });
});
registerDeliveryAction(
'cli_request',
async (content, session, inDb) => {
const requestId = content.requestId as string;
const command = content.command as string;
const args = (content.args as Record<string, unknown>) ?? {};

if (!requestId || !command) {
log.warn('cli_request missing requestId or command', { sessionId: session.id });
return;
}

const req: RequestFrame = { id: requestId, command, args };
const ctx = {
caller: 'agent' as const,
sessionId: session.id,
agentGroupId: session.agent_group_id,
messagingGroupId: session.messaging_group_id ?? '',
};

log.info('CLI request from agent', { requestId, command, sessionId: session.id });

const response = await dispatch(req, ctx);

// Write response to inbound.db so the container can read it.
// trigger=0: don't wake the agent — this is an inline response to a tool call.
insertMessage(inDb, {
id: `cli-resp-${requestId}`,
kind: 'system',
timestamp: new Date().toISOString(),
platformId: null,
channelType: null,
threadId: null,
content: JSON.stringify({
type: 'cli_response',
requestId,
frame: response,
}),
processAfter: null,
recurrence: null,
trigger: 0,
});

log.info('CLI response written', { requestId, ok: response.ok, sessionId: session.id });
},
unguarded('transport envelope — every inner command is guarded at dispatch'),
);
82 changes: 82 additions & 0 deletions src/cli/dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const approvalState = vi.hoisted(() => ({
| ((args: {
session: unknown;
payload: Record<string, unknown>;
approval: Record<string, unknown>;
userId: string;
notify: (text: string) => void;
}) => Promise<void>),
Expand All @@ -18,6 +19,7 @@ const approvalState = vi.hoisted(() => ({
handler: (args: {
session: unknown;
payload: Record<string, unknown>;
approval: Record<string, unknown>;
userId: string;
notify: (text: string) => void;
}) => Promise<void>,
Expand All @@ -43,8 +45,11 @@ vi.mock('../db/agent-groups.js', () => ({
}));

const mockGetSession = vi.fn();
// The guard's grant check re-fetches the approval row to prove it's live.
const mockGetPendingApproval = vi.fn();
vi.mock('../db/sessions.js', () => ({
getSession: (...args: unknown[]) => mockGetSession(...args),
getPendingApproval: (...args: unknown[]) => mockGetPendingApproval(...args),
}));

// dispatch's post-handler looks up the resource's `scopeField` via getResource.
Expand Down Expand Up @@ -495,10 +500,20 @@ describe('CLI scope enforcement', () => {
callerContext: ctx,
});

// The approve path hands the handler the live approval row — the grant
// the replay carries back into dispatch.
const grantRow = {
approval_id: 'appr-t1',
action: 'cli_command',
payload: JSON.stringify(approval.payload),
};
mockGetPendingApproval.mockReturnValue(grantRow);

expect(approvalState.approvalHandler).toBeTypeOf('function');
await approvalState.approvalHandler!({
session: { id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' },
payload: approval.payload,
approval: grantRow,
userId: 'telegram:admin',
notify: vi.fn(),
});
Expand All @@ -507,6 +522,73 @@ describe('CLI scope enforcement', () => {
expect(approvalState.requestApproval).toHaveBeenCalledTimes(1);
});

// --- Grant-carrying replay (the `approved: true` boolean no longer exists) ---

it('replay with a dead grant (row deleted) refuses instead of re-holding', async () => {
mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' });
mockGetSession.mockReturnValue({ id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' });
mockGetAgentGroup.mockReturnValue({ id: 'g1', name: 'Group One' });

const ctx = agentCtx();
await dispatch({ id: '1', command: 'approval-context-command', args: {} }, ctx);
const approval = approvalState.requestApproval.mock.calls[0][0] as { payload: Record<string, unknown> };

mockGetPendingApproval.mockReturnValue(undefined); // resolution already deleted the row
const notify = vi.fn();
await approvalState.approvalHandler!({
session: { id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' },
payload: approval.payload,
approval: { approval_id: 'appr-dead', action: 'cli_command', payload: JSON.stringify(approval.payload) },
userId: 'telegram:admin',
notify,
});

expect(approvalState.observedContexts).toHaveLength(0); // handler never ran
expect(approvalState.requestApproval).toHaveBeenCalledTimes(1); // no second card
expect(notify.mock.calls[0][0]).toContain('failed');
});

it("a grant approved for one command doesn't transfer to another", async () => {
mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' });

// A live cli_command row, but held for a DIFFERENT command.
const grantRow = {
approval_id: 'appr-other',
action: 'cli_command',
payload: JSON.stringify({ frame: { command: 'members-add' } }),
};
mockGetPendingApproval.mockReturnValue(grantRow);

const resp = await dispatch({ id: '1', command: 'approval-context-command', args: {} }, agentCtx(), {
grant: grantRow as never,
});

expect(resp.ok).toBe(false);
if (!resp.ok) {
expect(resp.error.code).toBe('forbidden');
expect(resp.error.message).toContain('grant');
}
expect(approvalState.observedContexts).toHaveLength(0);
});

it('a fabricated grant object without a live row is refused', async () => {
mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' });
mockGetPendingApproval.mockReturnValue(undefined);

const forged = {
approval_id: 'appr-forged',
action: 'cli_command',
payload: JSON.stringify({ frame: { command: 'approval-context-command' } }),
};
const resp = await dispatch({ id: '1', command: 'approval-context-command', args: {} }, agentCtx(), {
grant: forged as never,
});

expect(resp.ok).toBe(false);
if (!resp.ok) expect(resp.error.code).toBe('forbidden');
expect(approvalState.requestApproval).not.toHaveBeenCalled(); // refusal, not a fresh hold
});

// --- Post-handler filtering ---

it('group: groups list filters out other groups', async () => {
Expand Down
Loading
Loading