Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e6f197c34 | ||
|
|
910a16a998 |
@@ -0,0 +1,3 @@
|
||||
"""Canonical AIOS V2R1 runtime package."""
|
||||
|
||||
__version__ = "2.1.0-rc.1"
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import sys
|
||||
|
||||
from .cell_manager import CellManager
|
||||
from .ingress_service import serve
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
@@ -29,8 +30,20 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
return parser
|
||||
|
||||
|
||||
def build_serve_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="aios-cell serve")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=18792)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
values = list(sys.argv[1:] if argv is None else argv)
|
||||
if values and values[0] == "serve":
|
||||
serve_args = build_serve_parser().parse_args(values[1:])
|
||||
serve(serve_args.host, serve_args.port)
|
||||
return 0
|
||||
args = build_parser().parse_args(values)
|
||||
manager = CellManager(args.registry)
|
||||
if args.command == "create":
|
||||
result = manager.create(args.tenant_id, args.cell_id, args.version, args.digest)
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Fail-closed loopback HTTP shell for V2R1 ingress processors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
from collections.abc import Callable, Mapping
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
MAX_REQUEST_BYTES = 1024 * 1024
|
||||
MAX_RESPONSE_BYTES = 4096
|
||||
MUTATION_ROUTES = frozenset(
|
||||
{"/v1/ingress", "/v1/receipts/status", "/v1/outbound-receipts"}
|
||||
)
|
||||
Processor = Callable[[str, bytes], tuple[int, Mapping[str, Any]]]
|
||||
|
||||
|
||||
class IngressHTTPServer(ThreadingHTTPServer):
|
||||
"""Threaded loopback server with an optional externally supplied processor."""
|
||||
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
address: tuple[str, int],
|
||||
handler: type[BaseHTTPRequestHandler],
|
||||
processor: Processor | None,
|
||||
) -> None:
|
||||
self.processor = processor
|
||||
super().__init__(address, handler)
|
||||
|
||||
|
||||
class IngressRequestHandler(BaseHTTPRequestHandler):
|
||||
"""Bounded JSON transport; application processing is injected later."""
|
||||
|
||||
server: IngressHTTPServer
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
return
|
||||
|
||||
def _path(self) -> str:
|
||||
return urlsplit(self.path).path
|
||||
|
||||
def _send(self, status: int, payload: Mapping[str, Any]) -> None:
|
||||
body = json.dumps(
|
||||
dict(payload), ensure_ascii=False, separators=(",", ":"), sort_keys=True
|
||||
).encode("utf-8")
|
||||
if len(body) > MAX_RESPONSE_BYTES:
|
||||
status = 500
|
||||
body = b'{"status":"INTERNAL_ERROR"}'
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
if self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
|
||||
def _method_not_allowed(self) -> None:
|
||||
self._send(405, {"status": "METHOD_NOT_ALLOWED"})
|
||||
|
||||
def do_GET(self) -> None:
|
||||
path = self._path()
|
||||
if path == "/health/live":
|
||||
self._send(200, {"status": "LIVE"})
|
||||
elif path == "/health/ready":
|
||||
if self.server.processor is None:
|
||||
self._send(503, {"status": "SERVICE_NOT_CONFIGURED"})
|
||||
else:
|
||||
self._send(200, {"status": "READY"})
|
||||
elif path in MUTATION_ROUTES:
|
||||
self._method_not_allowed()
|
||||
else:
|
||||
self._send(404, {"status": "NOT_FOUND"})
|
||||
|
||||
def do_POST(self) -> None:
|
||||
path = self._path()
|
||||
if path not in MUTATION_ROUTES:
|
||||
if path in {"/health/live", "/health/ready"}:
|
||||
self._method_not_allowed()
|
||||
else:
|
||||
self._send(404, {"status": "NOT_FOUND"})
|
||||
return
|
||||
processor = self.server.processor
|
||||
if processor is None:
|
||||
self._send(503, {"status": "SERVICE_NOT_CONFIGURED"})
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if length < 0 or length > MAX_REQUEST_BYTES:
|
||||
self._send(413, {"status": "REQUEST_TOO_LARGE"})
|
||||
return
|
||||
body = self.rfile.read(length)
|
||||
status, payload = processor(path, body)
|
||||
if not isinstance(status, int) or not isinstance(payload, Mapping):
|
||||
raise TypeError("invalid processor response")
|
||||
self._send(status, payload)
|
||||
except Exception:
|
||||
self._send(500, {"status": "INTERNAL_ERROR"})
|
||||
|
||||
do_DELETE = _method_not_allowed
|
||||
do_HEAD = _method_not_allowed
|
||||
do_OPTIONS = _method_not_allowed
|
||||
do_PATCH = _method_not_allowed
|
||||
do_PUT = _method_not_allowed
|
||||
|
||||
|
||||
def build_server(
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 18792,
|
||||
*,
|
||||
processor: Processor | None = None,
|
||||
) -> IngressHTTPServer:
|
||||
"""Build a loopback-only HTTP server without starting it."""
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError as exc:
|
||||
raise ValueError("host must be a loopback IP address") from exc
|
||||
if not address.is_loopback:
|
||||
raise ValueError("host must be a loopback IP address")
|
||||
return IngressHTTPServer((host, port), IngressRequestHandler, processor)
|
||||
|
||||
|
||||
def serve(host: str = "127.0.0.1", port: int = 18792) -> None:
|
||||
"""Run the unconfigured loopback shell until interrupted."""
|
||||
server = build_server(host, port)
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
server.server_close()
|
||||
@@ -0,0 +1,17 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "aios-v2r1-runtime"
|
||||
version = "2.1.0rc1"
|
||||
description = "AIOS V2R1 canonical runtime package"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = []
|
||||
|
||||
[project.scripts]
|
||||
aios-cell = "aios_v2r1.cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
package-dir = {"" = "app"}
|
||||
packages = ["aios_v2r1"]
|
||||
+35
-10
@@ -1,31 +1,48 @@
|
||||
import {
|
||||
classifyRun,
|
||||
decideToolCall,
|
||||
resolveSenderId,
|
||||
runKey,
|
||||
} from "./policy.js";
|
||||
|
||||
const activeRuns = new Map();
|
||||
const MAX_RUN_AGE_MS = 60 * 60 * 1000;
|
||||
|
||||
function prune(now = Date.now()) {
|
||||
function prune(activeRuns, now = Date.now()) {
|
||||
for (const [key, value] of activeRuns.entries()) {
|
||||
if (now - value.recordedAt > MAX_RUN_AGE_MS) activeRuns.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
function approvalTimeout(config) {
|
||||
const value = config.approvalTimeoutMs;
|
||||
return Number.isInteger(value) && value >= 1000 && value <= 300000
|
||||
? value
|
||||
: 60000;
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "aios-tenant-boundary",
|
||||
name: "AIOS Tenant Boundary",
|
||||
description: "Fail-closed user-origin and side-effect policy for Tenant Cells.",
|
||||
|
||||
register(api) {
|
||||
const activeRuns = new Map();
|
||||
|
||||
api.on(
|
||||
"before_agent_run",
|
||||
async (event, ctx) => {
|
||||
prune();
|
||||
prune(activeRuns);
|
||||
const config = event.context?.pluginConfig ?? api.pluginConfig ?? {};
|
||||
const trust = classifyRun(ctx, config);
|
||||
const key = runKey(event, ctx);
|
||||
const existing = key ? activeRuns.get(key) : undefined;
|
||||
if (existing && existing.senderId !== trust.senderId) {
|
||||
return {
|
||||
outcome: "block",
|
||||
reason: "run_scope_sender_conflict",
|
||||
message: "This run scope is already bound to a different authenticated sender.",
|
||||
};
|
||||
}
|
||||
if (key) {
|
||||
activeRuns.set(key, { ...trust, recordedAt: Date.now() });
|
||||
}
|
||||
@@ -49,10 +66,14 @@ export default {
|
||||
api.on(
|
||||
"before_tool_call",
|
||||
async (event, ctx) => {
|
||||
prune();
|
||||
prune(activeRuns);
|
||||
const config = event.context?.pluginConfig ?? api.pluginConfig ?? {};
|
||||
const key = runKey(event, ctx);
|
||||
const trust = key ? activeRuns.get(key) : undefined;
|
||||
let trust = key ? activeRuns.get(key) : undefined;
|
||||
const senderId = resolveSenderId(ctx);
|
||||
if (trust && senderId && trust.senderId !== senderId) {
|
||||
trust = { trusted: false, reason: "run_scope_sender_conflict" };
|
||||
}
|
||||
const decision = decideToolCall(event.toolName, trust, config);
|
||||
|
||||
if (decision.action === "block") {
|
||||
@@ -67,7 +88,7 @@ export default {
|
||||
title: `Approve ${String(event.toolName)}`,
|
||||
description: "Authenticated user requested a side-effecting tool call in this Tenant Cell.",
|
||||
severity: "warning",
|
||||
timeoutMs: Number(config.approvalTimeoutMs ?? 60000),
|
||||
timeoutMs: approvalTimeout(config),
|
||||
allowedDecisions: ["allow-once", "deny"],
|
||||
pluginId: "aios-tenant-boundary",
|
||||
},
|
||||
@@ -78,9 +99,13 @@ export default {
|
||||
{ priority: 100 },
|
||||
);
|
||||
|
||||
api.on("agent_end", async (event, ctx) => {
|
||||
const key = runKey(event, ctx);
|
||||
if (key) activeRuns.delete(key);
|
||||
});
|
||||
api.on(
|
||||
"agent_end",
|
||||
async (event, ctx) => {
|
||||
const key = runKey(event, ctx);
|
||||
if (key) activeRuns.delete(key);
|
||||
},
|
||||
{ priority: 100 },
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
+22
-2
@@ -66,6 +66,26 @@ export function decideToolCall(toolName, runTrust, config = {}) {
|
||||
}
|
||||
|
||||
export function runKey(event = {}, ctx = {}) {
|
||||
const key = event.runId || ctx.runId;
|
||||
return typeof key === "string" && key.trim() ? key.trim() : undefined;
|
||||
const normalize = (value) => typeof value === "string" && value.trim()
|
||||
? value.trim()
|
||||
: undefined;
|
||||
const sameField = (eventValue, contextValue) => {
|
||||
const fromEvent = normalize(eventValue);
|
||||
const fromContext = normalize(contextValue);
|
||||
return {
|
||||
valid: !(fromEvent && fromContext && fromEvent !== fromContext),
|
||||
value: fromEvent || fromContext,
|
||||
};
|
||||
};
|
||||
const runId = sameField(event.runId, ctx.runId);
|
||||
const agentId = sameField(event.agentId, ctx.agentId);
|
||||
const sessionId = sameField(event.sessionId, ctx.sessionId);
|
||||
const sessionKey = sameField(event.sessionKey, ctx.sessionKey);
|
||||
if (!runId.valid || !agentId.valid || !sessionId.valid || !sessionKey.valid) {
|
||||
return undefined;
|
||||
}
|
||||
const selectedSession = sessionId.value || sessionKey.value;
|
||||
return runId.value && agentId.value && selectedSession
|
||||
? JSON.stringify([runId.value, agentId.value, selectedSession])
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "aios-tenant-boundary",
|
||||
"name": "AIOS Tenant Boundary",
|
||||
"description": "Enforces AIOS V2R1 tenant provenance and tool policy boundaries.",
|
||||
"version": "2.1.0-rc1",
|
||||
"version": "2.1.0-rc.1",
|
||||
"entry": "dist/index.js",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
@@ -12,7 +12,14 @@
|
||||
"trustedSenderIds": { "type": "array", "items": { "type": "string" }, "default": [] },
|
||||
"blockedSenderIds": { "type": "array", "items": { "type": "string" }, "default": [] },
|
||||
"readOnlyTools": { "type": "array", "items": { "type": "string" } },
|
||||
"requireApprovalForHumanSideEffects": { "type": "boolean", "default": true }
|
||||
"requireApprovalForHumanSideEffects": { "type": "boolean", "default": true },
|
||||
"blockUnknownAgentRuns": { "type": "boolean", "default": false },
|
||||
"approvalTimeoutMs": {
|
||||
"type": "integer",
|
||||
"minimum": 1000,
|
||||
"maximum": 300000,
|
||||
"default": 60000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
|
||||
import plugin from "../dist/index.js";
|
||||
|
||||
const packageJson = JSON.parse(
|
||||
await readFile(new URL("../package.json", import.meta.url), "utf8"),
|
||||
);
|
||||
const manifest = JSON.parse(
|
||||
await readFile(new URL("../openclaw.plugin.json", import.meta.url), "utf8"),
|
||||
);
|
||||
|
||||
function registrations(config = {}) {
|
||||
const seen = [];
|
||||
plugin.register({
|
||||
pluginConfig: config,
|
||||
on(name, handler, options) {
|
||||
seen.push({ name, handler, options });
|
||||
},
|
||||
});
|
||||
return seen;
|
||||
}
|
||||
|
||||
test("package, manifest, and executable test command are release compatible", () => {
|
||||
assert.equal(packageJson.version, "2.1.0-rc.1");
|
||||
assert.equal(manifest.version, "2.1.0-rc.1");
|
||||
assert.equal(packageJson.scripts.test, "node --test test/*.test.js");
|
||||
});
|
||||
|
||||
test("schema declares every runtime-read property and exact B1 bounds", () => {
|
||||
const properties = manifest.configSchema.properties;
|
||||
const runtimeKeys = [
|
||||
"approvalTimeoutMs",
|
||||
"blockUnknownAgentRuns",
|
||||
"blockedSenderIds",
|
||||
"readOnlyTools",
|
||||
"requireApprovalForHumanSideEffects",
|
||||
"requireExplicitTrustedSenders",
|
||||
"trustedSenderIds",
|
||||
];
|
||||
assert.deepEqual(Object.keys(properties).sort(), runtimeKeys);
|
||||
assert.deepEqual(properties.blockUnknownAgentRuns, {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
});
|
||||
assert.deepEqual(properties.approvalTimeoutMs, {
|
||||
type: "integer",
|
||||
minimum: 1000,
|
||||
maximum: 300000,
|
||||
default: 60000,
|
||||
});
|
||||
});
|
||||
|
||||
test("all three hooks register exactly once at priority 100", () => {
|
||||
const seen = registrations();
|
||||
assert.deepEqual(
|
||||
seen.map(({ name }) => name).sort(),
|
||||
["agent_end", "before_agent_run", "before_tool_call"],
|
||||
);
|
||||
for (const registration of seen) {
|
||||
assert.deepEqual(registration.options, { priority: 100 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
const [mode, inspectPath] = process.argv.slice(2);
|
||||
assert.ok(["default", "opt-in"].includes(mode), `unsupported mode: ${mode}`);
|
||||
assert.ok(inspectPath, "inspect JSON path is required");
|
||||
|
||||
const data = JSON.parse(await readFile(inspectPath, "utf8"));
|
||||
const plugin = data.plugin;
|
||||
assert.equal(plugin.id, "aios-tenant-boundary");
|
||||
assert.equal(plugin.version, "2.1.0-rc.1");
|
||||
assert.equal(plugin.status, "loaded");
|
||||
assert.equal(plugin.activated, true);
|
||||
assert.equal(await realpath(plugin.rootDir), await realpath(new URL("..", import.meta.url)));
|
||||
assert.equal(await realpath(plugin.source), await realpath(new URL("../dist/index.js", import.meta.url)));
|
||||
assert.equal(data.install.source, "path");
|
||||
assert.equal(await realpath(data.install.installPath), await realpath(plugin.rootDir));
|
||||
|
||||
const hooks = data.typedHooks
|
||||
.map(({ name, priority }) => ({ name, priority }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
const expectedNames = mode === "default"
|
||||
? ["before_tool_call"]
|
||||
: ["agent_end", "before_agent_run", "before_tool_call"];
|
||||
assert.deepEqual(hooks.map(({ name }) => name), expectedNames);
|
||||
assert.ok(hooks.every(({ priority }) => priority === 100));
|
||||
|
||||
const diagnostics = data.diagnostics ?? [];
|
||||
assert.equal(
|
||||
diagnostics.filter(({ level, severity }) =>
|
||||
["error", "fatal"].includes(String(level ?? severity).toLowerCase())).length,
|
||||
0,
|
||||
);
|
||||
if (mode === "default") {
|
||||
assert.deepEqual(
|
||||
diagnostics.map(({ level, message }) => ({ level, message })).sort((a, b) => a.message.localeCompare(b.message)),
|
||||
["agent_end", "before_agent_run"].map((hook) => ({
|
||||
level: "warn",
|
||||
message: `typed hook "${hook}" blocked because non-bundled plugins must set plugins.entries.aios-tenant-boundary.hooks.allowConversationAccess=true`,
|
||||
})).sort((a, b) => a.message.localeCompare(b.message)),
|
||||
);
|
||||
} else {
|
||||
assert.deepEqual(diagnostics, []);
|
||||
}
|
||||
|
||||
const properties = plugin.configJsonSchema?.properties ?? {};
|
||||
for (const key of ["approvalTimeoutMs", "blockUnknownAgentRuns"]) {
|
||||
assert.ok(Object.hasOwn(properties, key), `missing runtime schema property: ${key}`);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import plugin from "../dist/index.js";
|
||||
import {
|
||||
classifyRun,
|
||||
decideToolCall,
|
||||
resolveSenderId,
|
||||
runKey,
|
||||
} from "../dist/policy.js";
|
||||
|
||||
function registration(config = {}) {
|
||||
const handlers = new Map();
|
||||
plugin.register({
|
||||
pluginConfig: config,
|
||||
on(name, handler) {
|
||||
handlers.set(name, handler);
|
||||
},
|
||||
});
|
||||
return {
|
||||
beforeAgentRun: handlers.get("before_agent_run"),
|
||||
beforeToolCall: handlers.get("before_tool_call"),
|
||||
agentEnd: handlers.get("agent_end"),
|
||||
};
|
||||
}
|
||||
|
||||
function agentContext(id, senderId) {
|
||||
return {
|
||||
runId: `run-${id}`,
|
||||
agentId: "agent-main",
|
||||
sessionId: "session-uuid-123",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
...(senderId ? { senderId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toolContext(id, extra = {}) {
|
||||
return {
|
||||
runId: `run-${id}`,
|
||||
agentId: "agent-main",
|
||||
sessionId: "session-uuid-123",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
test("sender classification covers missing, blocked, allowlisted, and automation", () => {
|
||||
assert.equal(resolveSenderId({ channelContext: { sender: { id: " nested " } } }), "nested");
|
||||
assert.deepEqual(classifyRun({}, {}), {
|
||||
trusted: false,
|
||||
origin: "system_or_unknown",
|
||||
reason: "sender_id_missing",
|
||||
});
|
||||
assert.equal(
|
||||
classifyRun({ senderId: "blocked" }, { blockedSenderIds: ["blocked"] }).reason,
|
||||
"sender_blocked",
|
||||
);
|
||||
assert.equal(
|
||||
classifyRun(
|
||||
{ senderId: "alice" },
|
||||
{ requireExplicitTrustedSenders: true, trustedSenderIds: ["alice"] },
|
||||
).trusted,
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(classifyRun({ jobId: "job-1" }, {}), {
|
||||
trusted: false,
|
||||
origin: "automation",
|
||||
reason: "job_id_present",
|
||||
});
|
||||
});
|
||||
|
||||
test("unknown agent runs default to pass but fail closed when explicitly enabled", async () => {
|
||||
const defaultHandlers = registration();
|
||||
assert.deepEqual(
|
||||
await defaultHandlers.beforeAgentRun({}, agentContext("default")),
|
||||
{ outcome: "pass" },
|
||||
);
|
||||
|
||||
const enforced = registration({ blockUnknownAgentRuns: true });
|
||||
const denied = await enforced.beforeAgentRun({}, agentContext("denied"));
|
||||
assert.equal(denied.outcome, "block");
|
||||
assert.equal(denied.reason, "sender_id_missing");
|
||||
assert.doesNotMatch(denied.reason + denied.message, /undefined|\r|\n/);
|
||||
|
||||
assert.deepEqual(
|
||||
await enforced.beforeAgentRun({}, { ...agentContext("job"), jobId: "job-1" }),
|
||||
{ outcome: "pass" },
|
||||
);
|
||||
});
|
||||
|
||||
test("read-only tools pass without provenance and side effects fail with a stable reason", async () => {
|
||||
assert.deepEqual(decideToolCall("read", undefined, {}), {
|
||||
action: "allow",
|
||||
code: "read_only",
|
||||
});
|
||||
assert.deepEqual(decideToolCall("shell", undefined, {}), {
|
||||
action: "block",
|
||||
code: "run_provenance_missing",
|
||||
});
|
||||
|
||||
const handlers = registration();
|
||||
assert.equal(await handlers.beforeToolCall({ toolName: "read" }, {}), undefined);
|
||||
const blocked = await handlers.beforeToolCall({ toolName: "shell" }, {});
|
||||
assert.equal(blocked.block, true);
|
||||
assert.equal(
|
||||
blocked.blockReason,
|
||||
"AIOS V2R1 origin policy denied tool call: run_provenance_missing",
|
||||
);
|
||||
});
|
||||
|
||||
test("trusted human side effects request approval with exact timeout validation", async () => {
|
||||
for (const [configured, expected] of [
|
||||
[undefined, 60000],
|
||||
[1000, 1000],
|
||||
[300000, 300000],
|
||||
[999, 60000],
|
||||
[300001, 60000],
|
||||
[60000.5, 60000],
|
||||
["1000", 60000],
|
||||
[null, 60000],
|
||||
]) {
|
||||
const config = {
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice"],
|
||||
};
|
||||
if (configured !== undefined) config.approvalTimeoutMs = configured;
|
||||
const handlers = registration(config);
|
||||
const id = `approval-${String(configured)}`;
|
||||
await handlers.beforeAgentRun({}, agentContext(id, "alice"));
|
||||
const result = await handlers.beforeToolCall({ toolName: "shell" }, toolContext(id));
|
||||
assert.equal(result.requireApproval.timeoutMs, expected, String(configured));
|
||||
assert.deepEqual(result.requireApproval.allowedDecisions, ["allow-once", "deny"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("active run provenance is isolated by registration, run, and sender", async () => {
|
||||
const config = {
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice", "bob"],
|
||||
};
|
||||
const first = registration(config);
|
||||
const second = registration(config);
|
||||
await first.beforeAgentRun({}, agentContext("shared", "alice"));
|
||||
|
||||
const otherSender = await first.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("shared", { senderId: "bob" }),
|
||||
);
|
||||
assert.equal(otherSender.block, true);
|
||||
assert.match(otherSender.blockReason, /run_scope_sender_conflict$/);
|
||||
|
||||
const otherRegistration = await second.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("shared"),
|
||||
);
|
||||
assert.equal(otherRegistration.block, true);
|
||||
assert.match(otherRegistration.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
|
||||
test("agent_end cleanup removes only the matching shared scope", async () => {
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice", "bob"],
|
||||
});
|
||||
await handlers.beforeAgentRun({}, agentContext("alice-scope", "alice"));
|
||||
await handlers.beforeAgentRun({}, agentContext("bob-scope", "bob"));
|
||||
await handlers.agentEnd({}, toolContext("alice-scope"));
|
||||
|
||||
const alice = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("alice-scope"),
|
||||
);
|
||||
assert.equal(alice.block, true);
|
||||
|
||||
const bob = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("bob-scope"),
|
||||
);
|
||||
assert.ok(bob.requireApproval);
|
||||
});
|
||||
|
||||
test("run provenance expires after the bounded age", async (t) => {
|
||||
const originalNow = Date.now;
|
||||
t.after(() => { Date.now = originalNow; });
|
||||
let now = 1_000_000;
|
||||
Date.now = () => now;
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice"],
|
||||
});
|
||||
await handlers.beforeAgentRun({}, agentContext("expiring", "alice"));
|
||||
now += 60 * 60 * 1000 + 1;
|
||||
const result = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("expiring"),
|
||||
);
|
||||
assert.equal(result.block, true);
|
||||
assert.match(result.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
|
||||
test("host-shaped lifecycle keeps distinct sessionId and sessionKey across all hooks", async () => {
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice"],
|
||||
});
|
||||
const before = agentContext("host-shape", "alice");
|
||||
const tool = toolContext("host-shape");
|
||||
const end = toolContext("host-shape");
|
||||
for (const ctx of [before, tool, end]) {
|
||||
assert.equal(ctx.sessionId, "session-uuid-123");
|
||||
assert.equal(ctx.sessionKey, "agent:main:weixin:direct:user");
|
||||
assert.equal(ctx.runId, "run-host-shape");
|
||||
assert.equal(ctx.agentId, "agent-main");
|
||||
}
|
||||
|
||||
await handlers.beforeAgentRun({}, before);
|
||||
const result = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
tool,
|
||||
);
|
||||
assert.ok(result.requireApproval);
|
||||
assert.equal(result.block, undefined);
|
||||
await handlers.agentEnd({}, end);
|
||||
const cleaned = await handlers.beforeToolCall({ toolName: "shell" }, tool);
|
||||
assert.equal(cleaned.block, true);
|
||||
assert.match(cleaned.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
|
||||
test("shared scope collision fails closed without overwriting original sender", async () => {
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice", "bob"],
|
||||
});
|
||||
assert.deepEqual(
|
||||
await handlers.beforeAgentRun({}, agentContext("collision", "alice")),
|
||||
{ outcome: "pass" },
|
||||
);
|
||||
const collision = await handlers.beforeAgentRun(
|
||||
{},
|
||||
agentContext("collision", "bob"),
|
||||
);
|
||||
assert.equal(collision.outcome, "block");
|
||||
assert.equal(collision.reason, "run_scope_sender_conflict");
|
||||
assert.doesNotMatch(collision.message, /alice|bob/);
|
||||
|
||||
const original = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
toolContext("collision"),
|
||||
);
|
||||
assert.ok(original.requireApproval);
|
||||
});
|
||||
|
||||
test("shared scope normalization is exact and incomplete scope fails closed", async () => {
|
||||
const bothAliases = runKey({}, {
|
||||
runId: " run-1 ",
|
||||
agentId: " agent-1 ",
|
||||
sessionId: " session-uuid-123 ",
|
||||
sessionKey: " agent:main:weixin:direct:user ",
|
||||
});
|
||||
assert.equal(
|
||||
bothAliases,
|
||||
JSON.stringify(["run-1", "agent-1", "session-uuid-123"]),
|
||||
);
|
||||
|
||||
const fallback = runKey(
|
||||
{ sessionKey: " agent:main:weixin:direct:user " },
|
||||
{
|
||||
runId: "run-1",
|
||||
agentId: "agent-1",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
fallback,
|
||||
JSON.stringify(["run-1", "agent-1", "agent:main:weixin:direct:user"]),
|
||||
);
|
||||
assert.equal(runKey(
|
||||
{ sessionId: "event-session" },
|
||||
{
|
||||
runId: "run-1",
|
||||
agentId: "agent-1",
|
||||
sessionId: "context-session",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
},
|
||||
), undefined);
|
||||
assert.equal(runKey({}, {
|
||||
runId: "run-1",
|
||||
agentId: "agent-1",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
sessionId: "session-uuid-123",
|
||||
}), bothAliases);
|
||||
assert.equal(runKey({}, {
|
||||
runId: "run-1",
|
||||
agentId: "agent-1",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
}), fallback);
|
||||
assert.equal(runKey({}, {
|
||||
agentId: "agent-1", sessionId: "session-uuid-123",
|
||||
}), undefined);
|
||||
|
||||
const handlers = registration();
|
||||
const missing = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
{ agentId: "agent-1", sessionId: "session-uuid-123" },
|
||||
);
|
||||
assert.equal(missing.block, true);
|
||||
assert.match(missing.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
|
||||
test("sessionKey fallback requires sessionId absent from both hook contexts", async () => {
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice"],
|
||||
});
|
||||
const before = {
|
||||
runId: "run-fallback",
|
||||
agentId: "agent-main",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
senderId: "alice",
|
||||
};
|
||||
const tool = {
|
||||
runId: "run-fallback",
|
||||
agentId: "agent-main",
|
||||
sessionKey: "agent:main:weixin:direct:user",
|
||||
};
|
||||
await handlers.beforeAgentRun({}, before);
|
||||
assert.ok((await handlers.beforeToolCall({ toolName: "shell" }, tool)).requireApproval);
|
||||
|
||||
const mismatchedSelection = await handlers.beforeToolCall(
|
||||
{ toolName: "shell" },
|
||||
{ ...tool, sessionId: "session-uuid-123" },
|
||||
);
|
||||
assert.equal(mismatchedSelection.block, true);
|
||||
assert.match(mismatchedSelection.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
|
||||
test("same-named event and context sessionId mismatch fails closed", async () => {
|
||||
const handlers = registration({
|
||||
requireExplicitTrustedSenders: true,
|
||||
trustedSenderIds: ["alice"],
|
||||
});
|
||||
await handlers.beforeAgentRun({}, agentContext("event-mismatch", "alice"));
|
||||
const result = await handlers.beforeToolCall(
|
||||
{ toolName: "shell", sessionId: "different-session" },
|
||||
toolContext("event-mismatch"),
|
||||
);
|
||||
assert.equal(result.block, true);
|
||||
assert.match(result.blockReason, /run_provenance_missing$/);
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
from active_runtime.app.agent_event_bus import AgentEventBus
|
||||
from active_runtime.app.agent_event_dashboard import AgentEventDashboard
|
||||
from app.agent_event_bus import AgentEventBus
|
||||
from app.agent_event_dashboard import AgentEventDashboard
|
||||
|
||||
|
||||
def test_unified_event_flow():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.agent_observability_hooks import AgentObservabilityHooks
|
||||
from app.agent_observability_hooks import AgentObservabilityHooks
|
||||
|
||||
|
||||
def test_agent_observability_closed_loop():
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from active_runtime.app.architect_governance_agent import ArchitectGovernanceAgent
|
||||
from active_runtime.app.architect_governance_dashboard import ArchitectGovernanceDashboard
|
||||
from app.architect_governance_agent import ArchitectGovernanceAgent
|
||||
from app.architect_governance_dashboard import ArchitectGovernanceDashboard
|
||||
|
||||
|
||||
def test_architect_agent_decides_release_level():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.architect_research_timeline import ArchitectResearchTimeline
|
||||
from app.architect_research_timeline import ArchitectResearchTimeline
|
||||
|
||||
|
||||
def test_research_timeline_tracks_version_decision():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.architect_weekly_research_agent import ArchitectWeeklyResearchAgent
|
||||
from app.architect_weekly_research_agent import ArchitectWeeklyResearchAgent
|
||||
|
||||
|
||||
def test_architect_research_decides_release_type():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.architecture_change_classifier import ArchitectureChangeClassifier
|
||||
from app.architecture_change_classifier import ArchitectureChangeClassifier
|
||||
|
||||
|
||||
def test_small_change_can_auto_process():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.architecture_owner_gate import ArchitectureOwnerGate
|
||||
from app.architecture_owner_gate import ArchitectureOwnerGate
|
||||
|
||||
|
||||
def test_architecture_change_blocks_without_owner():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.change_governance_dashboard import ChangeGovernanceDashboard
|
||||
from app.change_governance_dashboard import ChangeGovernanceDashboard
|
||||
|
||||
|
||||
def test_change_governance_blocks_missing_evidence():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.governance_event_bridge import GovernanceEventBridge
|
||||
from app.governance_event_bridge import GovernanceEventBridge
|
||||
|
||||
|
||||
def test_governance_events_are_published():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.governance_timeline_dashboard import GovernanceTimelineDashboard
|
||||
from app.governance_timeline_dashboard import GovernanceTimelineDashboard
|
||||
|
||||
|
||||
def test_governance_timeline_detects_ready_flow():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.search_agent_adapter import AgentSearchContext, OpenClawSearchClient
|
||||
from app.search_agent_adapter import AgentSearchContext, OpenClawSearchClient
|
||||
|
||||
|
||||
class FakeOrchestrator:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.search_architect_integration import SearchArchitectIntegration
|
||||
from app.search_architect_integration import SearchArchitectIntegration
|
||||
|
||||
|
||||
def test_search_architect_recommends_release_for_new_capability():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.search_gateway import (
|
||||
from app.search_gateway import (
|
||||
SearchEvidence,
|
||||
SearchGateway,
|
||||
SearchProviderAttempt,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.search_gateway_dashboard import SearchGatewayDashboard
|
||||
from app.search_gateway_dashboard import SearchGatewayDashboard
|
||||
|
||||
|
||||
def test_search_gateway_dashboard_reports_provider_failures():
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from active_runtime.app.search_gateway import SearchEvidence, SearchGateway, SearchProviderAttempt, SearchRequest
|
||||
from active_runtime.app.search_profile_resolver import SearchProfileResolver
|
||||
from app.search_gateway import SearchEvidence, SearchGateway, SearchProviderAttempt, SearchRequest
|
||||
from app.search_profile_resolver import SearchProfileResolver
|
||||
|
||||
|
||||
class FailingProvider:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.search_gateway_orchestrator import SearchGatewayOrchestrator
|
||||
from app.search_gateway_orchestrator import SearchGatewayOrchestrator
|
||||
|
||||
|
||||
def test_search_orchestrator_has_audit_registry_event_layers():
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from active_runtime.app.search_provider_registry import SearchProviderRegistry, StaticArchiveProvider
|
||||
from active_runtime.app.search_gateway import SearchGateway, SearchRequest
|
||||
from app.search_provider_registry import SearchProviderRegistry, StaticArchiveProvider
|
||||
from app.search_gateway import SearchGateway, SearchRequest
|
||||
|
||||
|
||||
def test_provider_registry_has_default_layers():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.task_center import AIOSTaskRecord, TaskCenter, TaskNotificationStatus, TaskProgress
|
||||
from app.task_center import AIOSTaskRecord, TaskCenter, TaskNotificationStatus, TaskProgress
|
||||
|
||||
|
||||
def test_task_center_tracks_progress_and_notification():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.task_dashboard_view import TaskDashboardView
|
||||
from app.task_dashboard_view import TaskDashboardView
|
||||
|
||||
|
||||
def test_task_dashboard_contains_operations_views():
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from active_runtime.app.task_event_bridge import TaskEventBridge
|
||||
from active_runtime.app.task_statistics import TaskStatistics
|
||||
from app.task_event_bridge import TaskEventBridge
|
||||
from app.task_statistics import TaskStatistics
|
||||
|
||||
|
||||
def test_task_event_bridge_creates_events():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.task_lifecycle import TaskLifecycle
|
||||
from app.task_lifecycle import TaskLifecycle
|
||||
|
||||
|
||||
def test_owner_approval_button_appears_for_waiting_task():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.task_orchestrator import TaskOrchestrator
|
||||
from app.task_orchestrator import TaskOrchestrator
|
||||
|
||||
|
||||
def test_command_creates_task():
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from active_runtime.app.git_repo_locator import GitRepoLocator
|
||||
from app.git_repo_locator import GitRepoLocator
|
||||
|
||||
|
||||
def test_repo_locator_uses_configurable_root():
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import aios_v2r1
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_canonical_package_has_one_identity_and_no_compatibility_shim() -> None:
|
||||
assert aios_v2r1.__name__ == "aios_v2r1"
|
||||
assert aios_v2r1.__package__ == "aios_v2r1"
|
||||
assert aios_v2r1.__version__ == "2.1.0-rc.1"
|
||||
assert importlib.util.find_spec("active_runtime") is None
|
||||
assert not (ROOT / "active_runtime").exists()
|
||||
|
||||
|
||||
def test_packaging_metadata_declares_only_the_canonical_app_package() -> None:
|
||||
metadata = (ROOT / "active-runtime" / "pyproject.toml").read_text()
|
||||
assert 'packages = ["aios_v2r1"]' in metadata
|
||||
assert 'package-dir = {"" = "app"}' in metadata
|
||||
assert "active_runtime" not in metadata
|
||||
assert 'aios-cell = "aios_v2r1.cli:main"' in metadata
|
||||
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import pytest
|
||||
|
||||
from aios_v2r1 import cli
|
||||
from aios_v2r1.ingress_service import build_server
|
||||
|
||||
|
||||
@contextmanager
|
||||
def running_server(processor: Callable[[str, bytes], tuple[int, dict[str, object]]] | None = None) -> Iterator[tuple[str, int]]:
|
||||
server = build_server("127.0.0.1", 0, processor=processor)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
host, port = server.server_address
|
||||
yield str(host), int(port)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
def request(
|
||||
address: tuple[str, int],
|
||||
method: str,
|
||||
path: str,
|
||||
body: bytes | None = None,
|
||||
) -> tuple[int, bytes, dict[str, str]]:
|
||||
connection = http.client.HTTPConnection(*address, timeout=5)
|
||||
try:
|
||||
connection.request(method, path, body=body)
|
||||
response = connection.getresponse()
|
||||
payload = response.read()
|
||||
return response.status, payload, {key.lower(): value for key, value in response.getheaders()}
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def test_live_and_unconfigured_readiness_are_exact_and_bounded() -> None:
|
||||
with running_server() as address:
|
||||
live = request(address, "GET", "/health/live")
|
||||
ready = request(address, "GET", "/health/ready")
|
||||
|
||||
assert live[:2] == (200, b'{"status":"LIVE"}')
|
||||
assert ready[:2] == (503, b'{"status":"SERVICE_NOT_CONFIGURED"}')
|
||||
assert live[2]["content-type"] == "application/json"
|
||||
assert ready[2]["content-length"] == str(len(ready[1]))
|
||||
assert len(live[1]) <= 4096
|
||||
assert len(ready[1]) <= 4096
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"route",
|
||||
["/v1/ingress", "/v1/receipts/status", "/v1/outbound-receipts"],
|
||||
)
|
||||
def test_mutation_routes_fail_closed_without_reading_or_mutating(route: str) -> None:
|
||||
with running_server() as address:
|
||||
status, payload, _ = request(
|
||||
address,
|
||||
"POST",
|
||||
route,
|
||||
b'{"sender":"do-not-log","body":"do-not-log"}',
|
||||
)
|
||||
assert status == 503
|
||||
assert payload == b'{"status":"SERVICE_NOT_CONFIGURED"}'
|
||||
|
||||
|
||||
def test_unknown_routes_and_wrong_methods_use_bounded_sanitized_codes() -> None:
|
||||
with running_server() as address:
|
||||
missing = request(address, "GET", "/missing")
|
||||
wrong_method = request(address, "GET", "/v1/ingress")
|
||||
unsupported = request(address, "PUT", "/health/live")
|
||||
|
||||
assert missing[:2] == (404, b'{"status":"NOT_FOUND"}')
|
||||
assert wrong_method[:2] == (405, b'{"status":"METHOD_NOT_ALLOWED"}')
|
||||
assert unsupported[:2] == (405, b'{"status":"METHOD_NOT_ALLOWED"}')
|
||||
assert all(len(result[1]) <= 4096 for result in (missing, wrong_method, unsupported))
|
||||
|
||||
|
||||
def test_processor_is_injected_and_exceptions_are_not_disclosed(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
secret = "sender-secret-body-token"
|
||||
|
||||
def exploding_processor(route: str, body: bytes) -> tuple[int, dict[str, object]]:
|
||||
assert route == "/v1/ingress"
|
||||
assert json.loads(body) == {"value": secret}
|
||||
raise RuntimeError(secret)
|
||||
|
||||
with running_server(exploding_processor) as address:
|
||||
ready = request(address, "GET", "/health/ready")
|
||||
failed = request(
|
||||
address,
|
||||
"POST",
|
||||
"/v1/ingress",
|
||||
json.dumps({"value": secret}).encode(),
|
||||
)
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert ready[:2] == (200, b'{"status":"READY"}')
|
||||
assert failed[:2] == (500, b'{"status":"INTERNAL_ERROR"}')
|
||||
assert secret not in failed[1].decode()
|
||||
assert secret not in captured.out
|
||||
assert secret not in captured.err
|
||||
|
||||
|
||||
def test_server_rejects_non_loopback_bind() -> None:
|
||||
with pytest.raises(ValueError, match="loopback"):
|
||||
build_server("0.0.0.0", 0)
|
||||
|
||||
|
||||
def test_cli_preserves_registry_commands_and_dispatches_top_level_serve(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
parsed = cli.build_parser().parse_args(["registry.sqlite", "status", "tenant-a"])
|
||||
assert parsed.registry == "registry.sqlite"
|
||||
assert parsed.command == "status"
|
||||
|
||||
called: list[tuple[str, int]] = []
|
||||
monkeypatch.setattr(cli, "serve", lambda host, port: called.append((host, port)))
|
||||
assert cli.main(["serve", "--host", "127.0.0.1", "--port", "19001"]) == 0
|
||||
assert called == [("127.0.0.1", 19001)]
|
||||
Reference in New Issue
Block a user