Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6c93dcb5c | ||
|
|
7f0408d417 | ||
|
|
cfd2a19bd7 | ||
|
|
d2a9e26395 | ||
|
|
0734b1f3a5 | ||
|
|
ce6420f3de | ||
|
|
81f58b15c8 | ||
|
|
0c2113f710 | ||
|
|
900a506c1f | ||
|
|
c3d29e796a |
@@ -106,4 +106,61 @@ No credentials are recorded in this file.
|
||||
|
||||
All 11 acceptance criteria demonstrated. The real model request passed.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Configuration-driven Hello World (M1)
|
||||
|
||||
### Entry 5.1 — before
|
||||
|
||||
- Timestamp: 2026-09-03
|
||||
- Intended action: Make the container POC configuration-driven. Baseline committed and tagged `poc-container-hello-v0`. Milestone M1 tracked in Gitea (issues #1-#4): (T1) config module with idempotent bootstrap and strict v1 validation; (T2) wire scripts and compose to config.json with fail-closed behavior; (T3) sandboxed config selftests; (T4) E2E verification and documentation.
|
||||
- Reason: Per docs/plans/2026-09-02_atomic-mosaic-foundation.md — config.json must be the sole discovery entry point; updates and runs must never corrupt or invent configuration.
|
||||
- Expected result: All M1 acceptance criteria pass; Hello World reproducible from configuration alone.
|
||||
|
||||
### Entry 5.2 — after
|
||||
|
||||
- Timestamp: 2026-09-03
|
||||
- Commands run: `scripts/test-config.sh` (20 cases); fail-closed checks (compose without launcher env, verify/reset with missing config); `scripts/bootstrap.sh`; config-driven `scripts/hello.sh`, `scripts/verify.sh`, negative marker test, sandboxed reset symlink refusal (canary survived), real reset + bootstrap + build + verify; config checksum comparison across the entire flow.
|
||||
- Observed result:
|
||||
- Config selftests: 20 passed, 0 failed.
|
||||
- Fail-closed confirmed: compose exits 1 without launcher env; verify/reset exit 1 on missing config before any mutation.
|
||||
- Bootstrap created `~/.config/mosaic-dev/config.json` exclusively; second run validated without rewriting (content + mtime unchanged).
|
||||
- Config-driven hello/verify returned exactly `MOSAIC_HELLO_OK`; verify exit 0; negative marker test exit 1.
|
||||
- Reset refused symlinked dataRoot; canary file survived; real reset removed only the configured data root.
|
||||
- config.json checksum unchanged across hello/verify/reset/bootstrap/build/verify.
|
||||
- Failure or correction:
|
||||
1. Selftest harness bug: `cfg` helper invoked without a body for the symlink case (`$2: unbound variable`). Fixed in the harness; product code unaffected.
|
||||
2. E2E rerun-after-reset failure: `verify.sh` did not ensure the configured data root existed before the container mount. With the data root absent, Docker auto-created the host path as root:root, and the container's uid-1000 user could not write the generated system prompt. Fixed by calling `bootstrap_runtime_dir` in `verify.sh`; also hardened it to fail with a clear message when the data root exists but is not writable (root-owned leftover). Clean-slate E2E rerun: all steps green.
|
||||
- Credential check: no credential material in config, scripts, logs, or test output.
|
||||
|
||||
## Result (M1)
|
||||
|
||||
Configuration-driven Hello World verified. `main` merged with M1 and tagged `config-hello-v1`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Mission and task abstraction (M2)
|
||||
|
||||
### Entry 6.1 — before
|
||||
|
||||
- Timestamp: 2026-09-03
|
||||
- Intended action: Add the first mission/task layer, host-side only (Gitea milestone M2, issues #6-#9): strict v1 schemas for missions and tasks, a task runner executing through the proven config-driven container path, immutable write-once run records under `<dataRoot>/runs/`, `expectExact` gating, timeouts, selftests, fixtures, and docs.
|
||||
- Reason: The foundation plan's following layer — mission (objective + directives), task (bounded unit), run (one attempt), result (immutable evidence) — must exist as data and records before any policy or multi-agent work.
|
||||
- Expected result: `scripts/run-task.sh tasks/hello-marker.json` succeeds with exactly `MOSAIC_HELLO_OK`; wrong expectations fail; every run leaves an immutable record; configuration remains untouched.
|
||||
|
||||
### Entry 6.2 — after
|
||||
|
||||
- Timestamp: 2026-09-03
|
||||
- Commands run: `scripts/test-task.sh` (18 cases incl. live runs); `scripts/run-task.sh validate` / `run` on committed fixtures; `node scripts/mosaic-task.mjs list`; config checksum comparison across runs.
|
||||
- Observed result:
|
||||
- Selftests: 18 passed, 0 failed (schema negatives; live exact-marker success; wrong expectExact fails; distinct run dirs; result.json contents; list).
|
||||
- Fixture run: status `succeeded`, response exactly `MOSAIC_HELLO_OK`, mission snapshot recorded.
|
||||
- Run records written once under `<dataRoot>/runs/r-<utcstamp>-<rand>/`; reruns never clobber.
|
||||
- Failure or correction: none this phase.
|
||||
- Credential check: no credential material in task data, run records, or logs.
|
||||
|
||||
## Result (M2)
|
||||
|
||||
Mission/task layer verified end-to-end. `main` merged with M2 and tagged `mission-task-v1`.
|
||||
|
||||
|
||||
|
||||
@@ -9,24 +9,87 @@ to return exactly `MOSAIC_HELLO_OK`.
|
||||
## Layout
|
||||
|
||||
```text
|
||||
BRIEF.md requirements for this experiment
|
||||
BRIEF.md requirements for the original container proof
|
||||
BUILD-LOG.md append-only build/verification log
|
||||
LAYERS.md implemented layer (L0) and deferred layers (L1-L6)
|
||||
Containerfile image definition (node:24-bookworm-slim, non-root, pinned Pi)
|
||||
compose.yaml one service: mosaic-agent (one-shot)
|
||||
compose.yaml one service: mosaic-agent (one-shot; configured via env)
|
||||
package.json pins @earendil-works/pi-coding-agent at exactly 0.84.4
|
||||
package-lock.json resolved lockfile used by npm ci in the image
|
||||
.env.example non-secret settings only (provider, model)
|
||||
.env.example non-secret settings only (credential-file path, env-var auth)
|
||||
contracts/ CONSTITUTION.md, STANDARDS.md, SOUL.md, USER.md (immutable fixtures)
|
||||
scripts/ build.sh, hello.sh, verify.sh, reset.sh (+ shared common.sh)
|
||||
scripts/ bootstrap/build/hello/verify/reset + config tooling
|
||||
src/ load-contracts.sh, run-agent.sh (run inside the container)
|
||||
docs/plans/ architecture and milestone plans
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The sole discovery entry point is:
|
||||
|
||||
```text
|
||||
~/.config/mosaic-dev/config.json
|
||||
```
|
||||
|
||||
Created only by the explicit, idempotent bootstrap:
|
||||
|
||||
```bash
|
||||
scripts/bootstrap.sh # create-if-absent; validates existing config, never rewrites
|
||||
```
|
||||
|
||||
Minimal shape (`configVersion` 1):
|
||||
|
||||
```json
|
||||
{
|
||||
"configVersion": 1,
|
||||
"environment": "development",
|
||||
"dataRoot": "/home/jwoltje/.mosaic-dev",
|
||||
"execution": {
|
||||
"backend": "docker",
|
||||
"provider": "zai",
|
||||
"model": "glm-5.3-flash"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Rules enforced by `scripts/mosaic-config.mjs`:
|
||||
|
||||
- Unknown keys, unsupported versions/backends, and malformed JSON exit nonzero; nothing is modified.
|
||||
- `dataRoot` must be absolute, canonical, and must not be or contain the home or configuration directory.
|
||||
- Validation failures never touch config, state, or images.
|
||||
- `scripts/test-config.sh` runs the sandboxed config selftests (no Docker required).
|
||||
|
||||
Run paths (`build/hello/verify/reset`) fail closed when configuration is missing or invalid; they never invent it.
|
||||
|
||||
## Missions & tasks (M2)
|
||||
|
||||
Missions and tasks are validated JSON data (strict schemas, version-pinned). The M2 layer is host-side only: mission directives are recorded for provenance but do not yet reach the runtime system prompt (capability/policy layer comes later).
|
||||
|
||||
```text
|
||||
missions/hello.json objective + directives (missionVersion 1)
|
||||
tasks/hello-marker.json prompt + optional mission ref + expectExact + timeout
|
||||
<dataRoot>/runs/r-<id>/ immutable run record: task.json, mission.json,
|
||||
stderr.txt, result.json (all write-once)
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
scripts/run-task.sh validate tasks/hello-marker.json # strict validation, writes nothing
|
||||
scripts/run-task.sh run tasks/hello-marker.json # execute; result recorded under dataRoot/runs
|
||||
scripts/mosaic-task.mjs list # list runs and statuses
|
||||
scripts/test-task.sh # selftests (schema negatives + live runs)
|
||||
```
|
||||
|
||||
A run exits 0 only when its expectation is met (`expectExact` match); mismatches, nonzero agent exits, and timeouts record `status: failed` in `result.json` and exit 1. Each run gets a unique directory — rerunning never rewrites history.
|
||||
|
||||
See `docs/plans/2026-09-02_atomic-mosaic-foundation.md` for the full plan.
|
||||
|
||||
Inside the container:
|
||||
|
||||
```text
|
||||
/opt/mosaic/contracts immutable contract files
|
||||
/var/lib/mosaic generated runtime state (mounted from /home/jwoltje/.mosaic-dev)
|
||||
/var/lib/mosaic generated runtime state (mounted from configured dataRoot)
|
||||
/workspace agent workspace
|
||||
```
|
||||
|
||||
@@ -48,10 +111,14 @@ Inside the container:
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
scripts/build.sh # build the image
|
||||
scripts/hello.sh # one-shot request; prints the model response
|
||||
scripts/verify.sh # full gated test; exit 0 only on exact MOSAIC_HELLO_OK
|
||||
scripts/reset.sh # delete /home/jwoltje/.mosaic-dev (safety-checked)
|
||||
scripts/bootstrap.sh # create config.json if absent (idempotent)
|
||||
scripts/build.sh # build the image
|
||||
scripts/hello.sh # one-shot request; prints the model response
|
||||
scripts/verify.sh # full gated test; exit 0 only on exact MOSAIC_HELLO_OK
|
||||
scripts/run-task.sh # run a mission/task file (see Missions & tasks)
|
||||
scripts/test-config.sh # fast config-layer selftests (no Docker)
|
||||
scripts/test-task.sh # mission/task selftests (schema + live runs)
|
||||
scripts/reset.sh # delete the configured data root (safety-checked)
|
||||
```
|
||||
|
||||
Prove the failure path (acceptance criterion 9):
|
||||
|
||||
+6
-5
@@ -6,17 +6,18 @@ services:
|
||||
image: mosaic-poc-agent:0.84.4
|
||||
user: "1000:1000"
|
||||
environment:
|
||||
# Non-secret settings (see .env.example)
|
||||
PI_PROVIDER: ${PI_PROVIDER:-zai}
|
||||
PI_MODEL: ${PI_MODEL:-glm-5.3-flash}
|
||||
# Resolved from config.json by scripts/common.sh (load_config).
|
||||
# Required: compose fails fast when the launcher did not supply them.
|
||||
PI_PROVIDER: ${MOSAIC_PROVIDER:?MOSAIC_PROVIDER must be set by scripts/load_config (run via scripts/*.sh)}
|
||||
PI_MODEL: ${MOSAIC_MODEL:?MOSAIC_MODEL must be set by scripts/load_config (run via scripts/*.sh)}
|
||||
# Documented container auth alternative: provider API key via
|
||||
# runtime environment variable. Empty by default; when empty Pi
|
||||
# falls back to the read-only mounted auth.json credential file.
|
||||
ZAI_API_KEY: ${ZAI_API_KEY:-}
|
||||
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
|
||||
volumes:
|
||||
# Generated runtime state (host dir per brief)
|
||||
- /home/jwoltje/.mosaic-dev:/var/lib/mosaic
|
||||
# Configured runtime state root (from config.json dataRoot).
|
||||
- ${MOSAIC_DATA_ROOT:?MOSAIC_DATA_ROOT must be set by scripts/load_config (run via scripts/*.sh)}:/var/lib/mosaic
|
||||
# Runtime credential only: pi auth file mounted READ-ONLY.
|
||||
# Never copied into the image.
|
||||
- ${PI_AUTH_FILE:-/home/jwoltje/.pi/agent/auth.json}:/home/node/.pi/agent/auth.json:ro
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"missionVersion": 1,
|
||||
"id": "m-hello",
|
||||
"objective": "Prove the startup marker path of the mosaic-poc-agent.",
|
||||
"directives": [
|
||||
"Startup verification requests are answered with the marker only.",
|
||||
"No explanation, no formatting."
|
||||
]
|
||||
}
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# Explicit, idempotent configuration bootstrap.
|
||||
#
|
||||
# Creates ~/.config/mosaic-dev/config.json (or $MOSAIC_CONFIG) only when
|
||||
# absent. An existing configuration is validated, never modified.
|
||||
# Normal run paths (build/hello/verify) deliberately do NOT auto-bootstrap:
|
||||
# missing configuration is an error there, not something to invent.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
exec node scripts/mosaic-config.mjs bootstrap
|
||||
@@ -5,6 +5,8 @@ cd "$(dirname "$0")/.."
|
||||
# shellcheck source=common.sh
|
||||
source scripts/common.sh
|
||||
|
||||
load_config
|
||||
|
||||
bootstrap_runtime_dir
|
||||
|
||||
docker compose build
|
||||
|
||||
+29
-6
@@ -1,13 +1,36 @@
|
||||
# Shared helpers for the POC host scripts. Not a documented entry point.
|
||||
# Shared helpers for the Mosaic host scripts. Not a documented entry point.
|
||||
|
||||
MOSAIC_DEV_DIR="/home/jwoltje/.mosaic-dev"
|
||||
POC_ROOT_MARKER=".mosaic-poc-root"
|
||||
|
||||
# Ensure the runtime state directory exists and carries this project's
|
||||
# ownership marker. The marker is what scripts/reset.sh requires before
|
||||
# it will delete anything.
|
||||
# Load and validate the Mosaic configuration (config.json), exporting
|
||||
# MOSAIC_DATA_ROOT, MOSAIC_PROVIDER, and MOSAIC_MODEL.
|
||||
#
|
||||
# Fails closed: a missing or invalid configuration aborts the calling
|
||||
# script before any container or filesystem mutation. Run paths never
|
||||
# auto-bootstrap; use scripts/bootstrap.sh explicitly.
|
||||
load_config() {
|
||||
local config_env
|
||||
if ! config_env="$(node scripts/mosaic-config.mjs env)"; then
|
||||
echo "common: configuration load failed" >&2
|
||||
exit 1
|
||||
fi
|
||||
eval "$config_env"
|
||||
export MOSAIC_DATA_ROOT MOSAIC_PROVIDER MOSAIC_MODEL
|
||||
MOSAIC_DEV_DIR="$MOSAIC_DATA_ROOT"
|
||||
}
|
||||
|
||||
# Ensure the configured runtime data directory exists and carries this
|
||||
# project's ownership marker. The marker is what scripts/reset.sh requires
|
||||
# before it will delete anything.
|
||||
bootstrap_runtime_dir() {
|
||||
if [ ! -d "$MOSAIC_DEV_DIR" ]; then
|
||||
if [ -d "$MOSAIC_DEV_DIR" ]; then
|
||||
if [ ! -w "$MOSAIC_DEV_DIR" ] || [ ! -x "$MOSAIC_DEV_DIR" ]; then
|
||||
echo "bootstrap: $MOSAIC_DEV_DIR exists but is not writable by $(id -un)" >&2
|
||||
echo "bootstrap: a root-owned directory here is usually leftover from a" >&2
|
||||
echo "bootstrap: Docker-created mount source; remove it and rerun." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
mkdir -p "$MOSAIC_DEV_DIR"
|
||||
echo "bootstrap: created $MOSAIC_DEV_DIR"
|
||||
fi
|
||||
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bash
|
||||
# Minimal Gitea API client for this repository.
|
||||
#
|
||||
# Usage: scripts/gitea-api.sh METHOD api/path [json-body]
|
||||
# e.g. scripts/gitea-api.sh GET repos/mosaicstack/stack-v2/issues
|
||||
#
|
||||
# Security:
|
||||
# - Reads credentials from ~/secrets/mosaic.gitea.json (or
|
||||
# MOSAIC_GITEA_CREDENTIAL_FILE); file must be 0600, non-symlink.
|
||||
# - Token is passed to curl via a config stream (never argv, never disk,
|
||||
# never stdout/stderr).
|
||||
# - Prints the response body on stdout and "HTTP <code>" on stderr.
|
||||
# Exits nonzero when the API reports an error.
|
||||
set -euo pipefail
|
||||
|
||||
METHOD="${1:?usage: gitea-api.sh METHOD api/path [json-body]}"
|
||||
API_PATH="${2:?missing api/path}"
|
||||
API_PATH="${API_PATH#/}"
|
||||
BODY="${3:-}"
|
||||
|
||||
command -v curl >/dev/null || { echo "gitea-api: curl not found" >&2; exit 1; }
|
||||
command -v node >/dev/null || { echo "gitea-api: node not found" >&2; exit 1; }
|
||||
|
||||
export MOSAIC_GITEA_CREDENTIAL_FILE="${MOSAIC_GITEA_CREDENTIAL_FILE:-$HOME/secrets/mosaic.gitea.json}"
|
||||
|
||||
# Validate credential file; emit only the non-secret base URL on stdout.
|
||||
BASE="$(node -e '
|
||||
const fs = require("fs");
|
||||
const p = process.env.MOSAIC_GITEA_CREDENTIAL_FILE;
|
||||
let s;
|
||||
try { s = fs.lstatSync(p); } catch { process.exit(3); }
|
||||
if (!s.isFile() || s.isSymbolicLink() || (s.mode & 0o077) !== 0) process.exit(3);
|
||||
let e;
|
||||
try { e = JSON.parse(fs.readFileSync(p, "utf8")).mosaicstack || {}; } catch { process.exit(3); }
|
||||
const base = String(e.url || "").replace(/\/+$/, "");
|
||||
if (!/^https:\/\/git\.mosaicstack\.dev$/.test(base)) process.exit(3);
|
||||
if (typeof e.api_token !== "string" || e.api_token.length === 0) process.exit(3);
|
||||
process.stdout.write(base);
|
||||
')"
|
||||
|
||||
# Repo path from the configured origin remote (never from credentials).
|
||||
REMOTE_URL="$(git remote get-url origin)"
|
||||
REPO_PATH="${REMOTE_URL#https://git.mosaicstack.dev/}"
|
||||
REPO_PATH="${REPO_PATH%.git}"
|
||||
|
||||
# curl config stream: auth header via fd, never argv.
|
||||
gen_curl_cfg() {
|
||||
node -e '
|
||||
const fs = require("fs");
|
||||
const e = JSON.parse(fs.readFileSync(process.env.MOSAIC_GITEA_CREDENTIAL_FILE, "utf8")).mosaicstack || {};
|
||||
process.stdout.write("header = \"Authorization: token " + e.api_token + "\"\n");
|
||||
process.stdout.write("header = \"Content-Type: application/json\"\n");
|
||||
'
|
||||
}
|
||||
|
||||
BODY_FILE=""
|
||||
cleanup() { [ -n "$BODY_FILE" ] && rm -f "$BODY_FILE"; }
|
||||
trap cleanup EXIT
|
||||
if [ -n "$BODY" ]; then
|
||||
BODY_FILE="$(mktemp)"
|
||||
chmod 600 "$BODY_FILE"
|
||||
printf '%s' "$BODY" > "$BODY_FILE"
|
||||
fi
|
||||
|
||||
URL="$BASE/api/v1/$API_PATH"
|
||||
if [ -n "$BODY_FILE" ]; then
|
||||
HTTP_CODE="$(curl -sS -K <(gen_curl_cfg) -o /tmp/gitea-api-response.$$ \
|
||||
-w '%{http_code}' -X "$METHOD" "$URL" --data-binary @"$BODY_FILE")" || {
|
||||
echo "gitea-api: request failed" >&2; exit 1; }
|
||||
else
|
||||
HTTP_CODE="$(curl -sS -K <(gen_curl_cfg) -o /tmp/gitea-api-response.$$ \
|
||||
-w '%{http_code}' -X "$METHOD" "$URL")" || {
|
||||
echo "gitea-api: request failed" >&2; exit 1; }
|
||||
fi
|
||||
|
||||
cat /tmp/gitea-api-response.$$ 2>/dev/null || true
|
||||
rm -f /tmp/gitea-api-response.$$
|
||||
echo "HTTP $HTTP_CODE" >&2
|
||||
|
||||
case "$HTTP_CODE" in
|
||||
2*) exit 0 ;;
|
||||
*) echo "gitea-api: $METHOD $API_PATH failed (HTTP $HTTP_CODE)" >&2; exit 1 ;;
|
||||
esac
|
||||
+6
-1
@@ -10,8 +10,13 @@ cd "$(dirname "$0")/.."
|
||||
# shellcheck source=common.sh
|
||||
source scripts/common.sh
|
||||
|
||||
load_config
|
||||
|
||||
bootstrap_runtime_dir
|
||||
|
||||
# -T: no pseudo-TTY, so stdout is clean model output.
|
||||
# </dev/null: detach stdin. Pi's print mode reads piped stdin until EOF;
|
||||
# an interactive terminal would otherwise block it forever. The request
|
||||
# text comes from the compose command, not stdin, so nothing is lost.
|
||||
# Errors, if any, go to stderr for diagnostics.
|
||||
docker compose run --rm -T mosaic-agent
|
||||
docker compose run --rm -T mosaic-agent < /dev/null
|
||||
|
||||
Executable
+233
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Mosaic development configuration: bootstrap, validate, resolve.
|
||||
*
|
||||
* Operations:
|
||||
* bootstrap Create the default config ONLY if absent; otherwise validate
|
||||
* the existing file without writing (idempotent).
|
||||
* validate Load and strictly validate; print resolved config on stdout.
|
||||
* env Print shell-safe exports for launcher scripts:
|
||||
* MOSAIC_DATA_ROOT, MOSAIC_PROVIDER, MOSAIC_MODEL.
|
||||
*
|
||||
* Config location: $MOSAIC_CONFIG or ~/.config/mosaic-dev/config.json
|
||||
*
|
||||
* Exit codes:
|
||||
* 0 success
|
||||
* 2 configuration exists but is invalid (never modified by this tool)
|
||||
* 3 configuration is missing for a read operation (validate/env)
|
||||
*
|
||||
* Invariants (docs/plans/2026-09-02_atomic-mosaic-foundation.md):
|
||||
* - Existing configuration is never overwritten.
|
||||
* - Validation failure modifies nothing.
|
||||
* - Secrets are never stored in configuration.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const SUPPORTED_CONFIG_VERSION = 1;
|
||||
const SUPPORTED_ENVIRONMENTS = new Set(["development", "production"]);
|
||||
const SUPPORTED_BACKENDS = new Set(["docker"]);
|
||||
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
|
||||
|
||||
function fail(exitCode, message) {
|
||||
process.stderr.write(`mosaic-config: ${message}\n`);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
function configPath() {
|
||||
return process.env.MOSAIC_CONFIG
|
||||
? path.resolve(process.env.MOSAIC_CONFIG)
|
||||
: path.join(os.homedir(), ".config", "mosaic-dev", "config.json");
|
||||
}
|
||||
|
||||
function readRaw(file) {
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.lstatSync(file);
|
||||
} catch {
|
||||
return null; // missing
|
||||
}
|
||||
if (!stat.isFile() || stat.isSymbolicLink()) {
|
||||
fail(2, `configuration path must be a regular, non-symbolic-link file: ${file}`);
|
||||
}
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
fail(2, `configuration file is not readable: ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
function rejectUnknownKeys(object, allowed, where) {
|
||||
for (const key of Object.keys(object)) {
|
||||
if (!allowed.includes(key)) {
|
||||
fail(2, `unsupported ${where} key: "${key}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function validateDataRoot(value, file) {
|
||||
if (typeof value !== "string" || value.length === 0) {
|
||||
fail(2, 'execution "dataRoot" must be a non-empty string');
|
||||
}
|
||||
if (value.includes("\0")) {
|
||||
fail(2, 'execution "dataRoot" contains a NUL byte');
|
||||
}
|
||||
if (!path.isAbsolute(value)) {
|
||||
fail(2, `execution "dataRoot" must be an absolute path (got "${value}")`);
|
||||
}
|
||||
const resolved = path.resolve(value);
|
||||
if (resolved !== value) {
|
||||
fail(2, `execution "dataRoot" must be canonical without ".", "..", trailing slashes, or redundant separators (got "${value}")`);
|
||||
}
|
||||
if (resolved === path.parse(resolved).root) {
|
||||
fail(2, 'execution "dataRoot" must not be the filesystem root');
|
||||
}
|
||||
const home = path.resolve(os.homedir());
|
||||
if (resolved === home || isAncestorOf(resolved, home)) {
|
||||
fail(2, `execution "dataRoot" must not be or contain the home directory (${home})`);
|
||||
}
|
||||
const configDir = path.dirname(path.resolve(file));
|
||||
if (resolved === configDir || isAncestorOf(resolved, configDir)) {
|
||||
fail(2, `execution "dataRoot" must not be or contain the configuration directory (${configDir})`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function isAncestorOf(ancestor, candidate) {
|
||||
const rel = path.relative(ancestor, candidate);
|
||||
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
||||
}
|
||||
|
||||
function validate(document, file) {
|
||||
if (!isPlainObject(document)) {
|
||||
fail(2, "configuration must be a JSON object");
|
||||
}
|
||||
rejectUnknownKeys(
|
||||
document,
|
||||
["configVersion", "environment", "dataRoot", "execution"],
|
||||
"configuration",
|
||||
);
|
||||
|
||||
if (document.configVersion !== SUPPORTED_CONFIG_VERSION) {
|
||||
fail(2, `unsupported configVersion: ${JSON.stringify(document.configVersion)} (supported: ${SUPPORTED_CONFIG_VERSION})`);
|
||||
}
|
||||
if (!SUPPORTED_ENVIRONMENTS.has(document.environment)) {
|
||||
fail(2, `unsupported environment: ${JSON.stringify(document.environment)} (supported: ${[...SUPPORTED_ENVIRONMENTS].join(", ")})`);
|
||||
}
|
||||
|
||||
const dataRoot = validateDataRoot(document.dataRoot, file);
|
||||
|
||||
if (!isPlainObject(document.execution)) {
|
||||
fail(2, '"execution" must be a JSON object');
|
||||
}
|
||||
rejectUnknownKeys(document.execution, ["backend", "provider", "model"], '"execution"');
|
||||
if (!SUPPORTED_BACKENDS.has(document.execution.backend)) {
|
||||
fail(2, `unsupported execution.backend: ${JSON.stringify(document.execution.backend)} (supported: ${[...SUPPORTED_BACKENDS].join(", ")})`);
|
||||
}
|
||||
for (const key of ["provider", "model"]) {
|
||||
const value = document.execution[key];
|
||||
if (typeof value !== "string" || !NAME_PATTERN.test(value)) {
|
||||
fail(2, `execution.${key} must match ${NAME_PATTERN} (got ${JSON.stringify(value)})`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
configVersion: document.configVersion,
|
||||
environment: document.environment,
|
||||
dataRoot,
|
||||
execution: {
|
||||
backend: document.execution.backend,
|
||||
provider: document.execution.provider,
|
||||
model: document.execution.model,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function load(file) {
|
||||
const raw = readRaw(file);
|
||||
if (raw === null) {
|
||||
fail(3, `configuration not found: ${file} (run scripts/bootstrap.sh to create it)`);
|
||||
}
|
||||
let document;
|
||||
try {
|
||||
document = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
fail(2, `configuration is not valid JSON (${file}): ${error.message}`);
|
||||
}
|
||||
return validate(document, file);
|
||||
}
|
||||
|
||||
function shellQuote(value) {
|
||||
return `'${String(value).replaceAll("'", `'\\''`)}'`;
|
||||
}
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
configVersion: 1,
|
||||
environment: "development",
|
||||
dataRoot: path.join(os.homedir(), ".mosaic-dev"),
|
||||
execution: {
|
||||
backend: "docker",
|
||||
provider: "zai",
|
||||
model: "glm-5.3-flash",
|
||||
},
|
||||
};
|
||||
|
||||
const operation = process.argv[2];
|
||||
const file = configPath();
|
||||
|
||||
switch (operation) {
|
||||
case "bootstrap": {
|
||||
if (fs.existsSync(file)) {
|
||||
load(file); // validate only; never rewrite
|
||||
process.stderr.write(`mosaic-config: configuration already present, validated without changes: ${file}\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
let fd;
|
||||
try {
|
||||
// 'wx': creation is exclusive; an existing file is never overwritten.
|
||||
fd = fs.openSync(file, "wx", 0o644);
|
||||
fs.writeFileSync(fd, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`);
|
||||
} catch (error) {
|
||||
if (error.code === "EEXIST") {
|
||||
load(file);
|
||||
process.exit(0);
|
||||
}
|
||||
fail(1, `unable to create configuration: ${error.message}`);
|
||||
} finally {
|
||||
if (fd !== undefined) fs.closeSync(fd);
|
||||
}
|
||||
load(file);
|
||||
process.stderr.write(`mosaic-config: created default configuration: ${file}\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
case "validate": {
|
||||
const resolved = load(file);
|
||||
process.stdout.write(`${JSON.stringify(resolved, null, 2)}\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
case "env": {
|
||||
const resolved = load(file);
|
||||
process.stdout.write(
|
||||
[
|
||||
`MOSAIC_DATA_ROOT=${shellQuote(resolved.dataRoot)}`,
|
||||
`MOSAIC_PROVIDER=${shellQuote(resolved.execution.provider)}`,
|
||||
`MOSAIC_MODEL=${shellQuote(resolved.execution.model)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
default:
|
||||
fail(1, `unknown operation: ${JSON.stringify(operation ?? "")} (expected bootstrap | validate | env)`);
|
||||
}
|
||||
Executable
+318
@@ -0,0 +1,318 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Mosaic mission/task layer (M2, host-side only).
|
||||
*
|
||||
* Operations:
|
||||
* validate <file> Strictly validate a task (and its referenced mission);
|
||||
* print the resolved task on success. Writes nothing.
|
||||
* run <taskFile> Execute the task through the config-driven container
|
||||
* path; record an immutable run under <dataRoot>/runs/.
|
||||
* list List runs recorded under <dataRoot>/runs/.
|
||||
*
|
||||
* Exit codes:
|
||||
* 0 success (run: status "succeeded")
|
||||
* 1 run failed (mismatch, nonzero exit, timeout) — result.json still written
|
||||
* 2 invalid task/mission data
|
||||
* 3 configuration problem
|
||||
* 4 file/environment problem
|
||||
*
|
||||
* M2 scope: mission directives are validated and snapshotted into run
|
||||
* records for provenance; they are NOT yet injected into the runtime
|
||||
* system prompt (capability/policy layer comes later).
|
||||
*
|
||||
* Invariants carried over from the configuration layer:
|
||||
* - Strict schemas; unknown keys rejected; versions pinned at 1.
|
||||
* - Validation never writes.
|
||||
* - Run records are write-once and never rewritten by a later run.
|
||||
* - No secrets in mission/task data or run records.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const PROJECT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const RUNS_DIRNAME = "runs";
|
||||
const ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const DEFAULT_TIMEOUT_SECONDS = 120;
|
||||
|
||||
function fail(exitCode, message) {
|
||||
process.stderr.write(`mosaic-task: ${message}\n`);
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
function isPlainObject(value) {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function rejectUnknownKeys(object, allowed, where) {
|
||||
for (const key of Object.keys(object)) {
|
||||
if (!allowed.includes(key)) fail(2, `unsupported ${where} key: "${key}"`);
|
||||
}
|
||||
}
|
||||
|
||||
function readJsonFile(file, what) {
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.lstatSync(file);
|
||||
} catch {
|
||||
fail(4, `${what} not found: ${file}`);
|
||||
}
|
||||
if (!stat.isFile() || stat.isSymbolicLink()) {
|
||||
fail(4, `${what} must be a regular, non-symbolic-link file: ${file}`);
|
||||
}
|
||||
let document;
|
||||
try {
|
||||
document = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
fail(2, `${what} is not valid JSON (${file}): ${error.message}`);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
function validateId(value, what) {
|
||||
if (typeof value !== "string" || !ID_PATTERN.test(value)) {
|
||||
fail(2, `${what} must match ${ID_PATTERN} (got ${JSON.stringify(value)})`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateMission(document, file) {
|
||||
if (!isPlainObject(document)) fail(2, "mission must be a JSON object");
|
||||
rejectUnknownKeys(document, ["missionVersion", "id", "objective", "directives"], "mission");
|
||||
if (document.missionVersion !== 1) {
|
||||
fail(2, `unsupported missionVersion: ${JSON.stringify(document.missionVersion)} (supported: 1)`);
|
||||
}
|
||||
validateId(document.id, "mission id");
|
||||
if (typeof document.objective !== "string" || document.objective.trim().length === 0 || document.objective.length > 4000) {
|
||||
fail(2, "mission objective must be a non-empty string of at most 4000 characters");
|
||||
}
|
||||
let directives = [];
|
||||
if (document.directives !== undefined) {
|
||||
if (!Array.isArray(document.directives)) fail(2, "mission directives must be an array of strings");
|
||||
directives = document.directives.map((d, i) => {
|
||||
if (typeof d !== "string" || d.trim().length === 0 || d.length > 2000 || d.includes("\0")) {
|
||||
fail(2, `mission directive ${i} must be a non-empty string of at most 2000 characters`);
|
||||
}
|
||||
return d;
|
||||
});
|
||||
}
|
||||
return { missionVersion: document.missionVersion, id: document.id, objective: document.objective, directives };
|
||||
}
|
||||
|
||||
function validateTask(document, file) {
|
||||
if (!isPlainObject(document)) fail(2, "task must be a JSON object");
|
||||
rejectUnknownKeys(document, ["taskVersion", "id", "prompt", "mission", "expectExact", "timeoutSeconds"], "task");
|
||||
if (document.taskVersion !== 1) {
|
||||
fail(2, `unsupported taskVersion: ${JSON.stringify(document.taskVersion)} (supported: 1)`);
|
||||
}
|
||||
validateId(document.id, "task id");
|
||||
|
||||
if (typeof document.prompt !== "string" || document.prompt.length === 0 || document.prompt.length > 20000 || document.prompt.includes("\0")) {
|
||||
fail(2, "task prompt must be a non-empty string of at most 20000 characters");
|
||||
}
|
||||
|
||||
let mission = null;
|
||||
let missionId = null;
|
||||
let missionSnapshot = null;
|
||||
if (document.mission !== undefined && document.mission !== null) {
|
||||
if (typeof document.mission !== "string" || document.mission.length === 0) {
|
||||
fail(2, 'task "mission" must be a path string when present');
|
||||
}
|
||||
const missionPath = path.resolve(path.dirname(path.resolve(file)), document.mission);
|
||||
missionSnapshot = validateMission(readJsonFile(missionPath, "mission file"), missionPath);
|
||||
mission = document.mission;
|
||||
missionId = missionSnapshot.id;
|
||||
}
|
||||
|
||||
let expectExact = null;
|
||||
if (document.expectExact !== undefined && document.expectExact !== null) {
|
||||
if (typeof document.expectExact !== "string" || document.expectExact.length === 0 || document.expectExact.length > 500 || /[^\P{C}\t\n]/u.test(document.expectExact)) {
|
||||
fail(2, "task expectExact must be a non-empty string of at most 500 characters without control characters (tab/newline allowed)");
|
||||
}
|
||||
expectExact = document.expectExact;
|
||||
}
|
||||
|
||||
let timeoutSeconds = DEFAULT_TIMEOUT_SECONDS;
|
||||
if (document.timeoutSeconds !== undefined && document.timeoutSeconds !== null) {
|
||||
if (!Number.isInteger(document.timeoutSeconds) || document.timeoutSeconds < 5 || document.timeoutSeconds > 600) {
|
||||
fail(2, "task timeoutSeconds must be an integer between 5 and 600");
|
||||
}
|
||||
timeoutSeconds = document.timeoutSeconds;
|
||||
}
|
||||
|
||||
return {
|
||||
taskVersion: document.taskVersion,
|
||||
id: document.id,
|
||||
prompt: document.prompt,
|
||||
mission,
|
||||
missionId,
|
||||
missionSnapshot,
|
||||
expectExact,
|
||||
timeoutSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
const proc = spawnSync(process.execPath, [path.join(PROJECT_ROOT, "scripts", "mosaic-config.mjs"), "validate"], {
|
||||
cwd: PROJECT_ROOT,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
if (proc.status !== 0) {
|
||||
fail(3, `configuration problem (exit ${proc.status}); run scripts/bootstrap.sh or fix config.json`);
|
||||
}
|
||||
return JSON.parse(proc.stdout);
|
||||
}
|
||||
|
||||
function runsRoot(resolvedConfig) {
|
||||
return path.join(resolvedConfig.dataRoot, RUNS_DIRNAME);
|
||||
}
|
||||
|
||||
function utcStamp() {
|
||||
return new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
||||
}
|
||||
|
||||
function writeOnce(file, content) {
|
||||
const fd = fs.openSync(file, "wx", 0o644); // exclusive: never overwrite
|
||||
try {
|
||||
fs.writeFileSync(fd, content);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function runTask(taskFile) {
|
||||
const resolved = JSON.parse(
|
||||
spawnSync(process.execPath, [path.join(PROJECT_ROOT, "scripts", "mosaic-config.mjs"), "validate"], {
|
||||
cwd: PROJECT_ROOT,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 1024 * 1024,
|
||||
}).stdout,
|
||||
);
|
||||
|
||||
const task = validateTask(readJsonFile(taskFile, "task file"), path.resolve(taskFile));
|
||||
const runId = `r-${utcStamp()}-${randomBytes(3).toString("hex")}`;
|
||||
const runDir = path.join(runsRoot(resolved), runId);
|
||||
|
||||
fs.mkdirSync(runDir, { recursive: true });
|
||||
|
||||
// Immutable input snapshots (evidence of exactly what was executed).
|
||||
const rawTask = fs.readFileSync(path.resolve(taskFile), "utf8");
|
||||
writeOnce(path.join(runDir, "task.json"), rawTask);
|
||||
if (task.missionSnapshot) {
|
||||
const missionPath = path.resolve(path.dirname(path.resolve(taskFile)), task.mission);
|
||||
writeOnce(path.join(runDir, "mission.json"), fs.readFileSync(missionPath, "utf8"));
|
||||
}
|
||||
|
||||
const startedAt = new Date();
|
||||
const stderrFile = path.join(runDir, "stderr.txt");
|
||||
const proc = spawnSync(
|
||||
"docker",
|
||||
["compose", "run", "--rm", "-T", "mosaic-agent", task.prompt],
|
||||
{
|
||||
cwd: PROJECT_ROOT,
|
||||
env: process.env, // MOSAIC_DATA_ROOT / MOSAIC_PROVIDER / MOSAIC_MODEL resolved by run-task.sh
|
||||
input: "", // stdin detached: print mode must never wait on a terminal (see issue #5)
|
||||
encoding: "utf8",
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
timeout: task.timeoutSeconds * 1000,
|
||||
killSignal: "SIGKILL",
|
||||
},
|
||||
);
|
||||
const finishedAt = new Date();
|
||||
|
||||
fs.writeFileSync(stderrFile, proc.stderr ?? "", { flag: "wx" });
|
||||
|
||||
const response = (proc.stdout ?? "").replace(/^[^\S\n]+/, "").replace(/[^\S\n]+$/, "").trim();
|
||||
let status = "succeeded";
|
||||
let reason = null;
|
||||
let expected = task.expectExact;
|
||||
|
||||
if (proc.error && proc.error.code === "ETIMEDOUT") {
|
||||
status = "failed";
|
||||
reason = "timeout";
|
||||
} else if (proc.error) {
|
||||
status = "failed";
|
||||
reason = `spawn-error: ${proc.error.code ?? proc.error.message}`;
|
||||
} else if (proc.status !== 0) {
|
||||
status = "failed";
|
||||
reason = "exit-nonzero";
|
||||
} else if (expected !== null && response !== expected) {
|
||||
status = "failed";
|
||||
reason = "expect-mismatch";
|
||||
}
|
||||
|
||||
const result = {
|
||||
runVersion: 1,
|
||||
runId,
|
||||
taskId: task.id,
|
||||
missionId: task.missionId,
|
||||
status,
|
||||
reason,
|
||||
request: task.prompt,
|
||||
response,
|
||||
expectedExact: expected,
|
||||
exitCode: proc.status,
|
||||
signal: proc.signal ?? null,
|
||||
provider: resolved.execution.provider,
|
||||
model: resolved.execution.model,
|
||||
startedAt: startedAt.toISOString(),
|
||||
finishedAt: finishedAt.toISOString(),
|
||||
durationMs: finishedAt.getTime() - startedAt.getTime(),
|
||||
};
|
||||
|
||||
writeOnce(path.join(runDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
||||
|
||||
process.stdout.write(`run: ${runId}\nstatus: ${status}${reason ? ` (${reason})` : ""}\nresponse: ${response}\n`);
|
||||
process.exit(status === "succeeded" ? 0 : 1);
|
||||
}
|
||||
|
||||
function listRuns() {
|
||||
const resolved = loadConfig();
|
||||
const root = runsRoot(resolved);
|
||||
let entries = [];
|
||||
try {
|
||||
entries = fs.readdirSync(root).filter((name) => name.startsWith("r-")).sort();
|
||||
} catch {
|
||||
// No runs yet.
|
||||
}
|
||||
for (const runId of entries) {
|
||||
let status = "unknown";
|
||||
let taskId = "-";
|
||||
try {
|
||||
const result = JSON.parse(fs.readFileSync(path.join(root, runId, "result.json"), "utf8"));
|
||||
status = result.status;
|
||||
taskId = result.taskId;
|
||||
} catch {
|
||||
// Incomplete run record; report as unknown.
|
||||
}
|
||||
process.stdout.write(`${runId} ${status.padEnd(9)} ${taskId}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
const operation = process.argv[2];
|
||||
const target = process.argv[3];
|
||||
|
||||
switch (operation) {
|
||||
case "validate": {
|
||||
if (!target) fail(4, "usage: mosaic-task.mjs validate <taskFile>");
|
||||
const file = path.resolve(target);
|
||||
const task = validateTask(readJsonFile(file, "task file"), file);
|
||||
const { missionSnapshot, ...rest } = task;
|
||||
process.stdout.write(`${JSON.stringify(rest, null, 2)}\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
case "run":
|
||||
if (!target) fail(4, "usage: mosaic-task.mjs run <taskFile>");
|
||||
runTask(path.resolve(target));
|
||||
break;
|
||||
case "list":
|
||||
listRuns();
|
||||
process.exit(0);
|
||||
default:
|
||||
fail(4, `unknown operation: ${JSON.stringify(operation ?? "")} (expected validate | run | list)`);
|
||||
}
|
||||
+8
-2
@@ -7,9 +7,15 @@
|
||||
# created by this project.
|
||||
# Any failed check aborts with nothing deleted.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
# shellcheck source=common.sh
|
||||
source scripts/common.sh
|
||||
|
||||
TARGET="/home/jwoltje/.mosaic-dev"
|
||||
MARKER=".mosaic-poc-root"
|
||||
# Reset operates on the CONFIGURED data root. Configuration itself is
|
||||
# never a reset target; a missing/invalid configuration aborts here.
|
||||
load_config
|
||||
TARGET="$MOSAIC_DATA_ROOT"
|
||||
MARKER="$POC_ROOT_MARKER"
|
||||
|
||||
fail() {
|
||||
echo "reset: refusing to delete: $*" >&2
|
||||
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run a mission/task file through the config-driven container path.
|
||||
#
|
||||
# Usage: scripts/run-task.sh run <task.json> (also: validate <task.json>, list)
|
||||
#
|
||||
# Ensures the configuration is valid and the data root carries the
|
||||
# ownership marker before any task executes.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
# shellcheck source=common.sh
|
||||
source scripts/common.sh
|
||||
|
||||
load_config
|
||||
bootstrap_runtime_dir
|
||||
|
||||
exec node scripts/mosaic-task.mjs "$@"
|
||||
Executable
+142
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fast, sandboxed selftests for the configuration layer.
|
||||
#
|
||||
# No Docker, no network, no credentials: every case runs against a
|
||||
# temporary config via MOSAIC_CONFIG. Suitable for frequent local runs.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
SANDBOX="$(mktemp -d)"
|
||||
trap 'rm -rf "$SANDBOX"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
# expect_exit NAME EXPECTED_RC -- command...
|
||||
expect_exit() {
|
||||
local name="$1" expected="$2"
|
||||
shift 3 # name, expected, "--"
|
||||
local rc
|
||||
"$@" >/dev/null 2>&1
|
||||
rc=$?
|
||||
if [ "$rc" -eq "$expected" ]; then
|
||||
PASS=$((PASS + 1))
|
||||
echo "ok $name (exit $rc)"
|
||||
else
|
||||
FAIL=$((FAIL + 1))
|
||||
echo "FAIL $name (exit $rc, expected $expected)"
|
||||
fi
|
||||
}
|
||||
|
||||
CONFIG_OP="node scripts/mosaic-config.mjs"
|
||||
|
||||
valid_body() {
|
||||
cat <<EOF
|
||||
{"configVersion":1,"environment":"development","dataRoot":"$1","execution":{"backend":"docker","provider":"zai","model":"glm-5.3-flash"}}
|
||||
EOF
|
||||
}
|
||||
|
||||
cfg() { printf '%s' "$2" > "$SANDBOX/$1"; }
|
||||
|
||||
DATA_ROOT="$SANDBOX/data"
|
||||
|
||||
# --- bootstrap ---
|
||||
rm -f "$SANDBOX/config.json"
|
||||
expect_exit "bootstrap creates default when absent" 0 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/config.json" $CONFIG_OP bootstrap
|
||||
[ -f "$SANDBOX/config.json" ] && { PASS=$((PASS+1)); echo "ok bootstrap wrote config file"; } \
|
||||
|| { FAIL=$((FAIL+1)); echo "FAIL bootstrap wrote config file"; }
|
||||
|
||||
SUM_BEFORE=$(sha256sum "$SANDBOX/config.json" | cut -d' ' -f1)
|
||||
MTIME_BEFORE=$(stat -c %Y "$SANDBOX/config.json")
|
||||
sleep 1.1
|
||||
expect_exit "bootstrap is idempotent on existing config" 0 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/config.json" $CONFIG_OP bootstrap
|
||||
SUM_AFTER=$(sha256sum "$SANDBOX/config.json" | cut -d' ' -f1)
|
||||
MTIME_AFTER=$(stat -c %Y "$SANDBOX/config.json")
|
||||
if [ "$SUM_BEFORE" = "$SUM_AFTER" ] && [ "$MTIME_BEFORE" = "$MTIME_AFTER" ]; then
|
||||
PASS=$((PASS+1)); echo "ok bootstrap did not rewrite existing config"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "FAIL bootstrap rewrote existing config"
|
||||
fi
|
||||
|
||||
# --- validate ---
|
||||
expect_exit "validate missing config exits 3" 3 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/absent.json" $CONFIG_OP validate
|
||||
|
||||
cfg invalid.json '{'
|
||||
expect_exit "malformed JSON exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/invalid.json" $CONFIG_OP validate
|
||||
|
||||
cfg badversion.json '{"configVersion":2,"environment":"development","dataRoot":"'$DATA_ROOT'","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "unsupported configVersion exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/badversion.json" $CONFIG_OP validate
|
||||
|
||||
cfg unknownkey.json '{"configVersion":1,"environment":"development","dataRoot":"'$DATA_ROOT'","extra":true,"execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "unknown top-level key exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/unknownkey.json" $CONFIG_OP validate
|
||||
|
||||
cfg unknownexec.json '{"configVersion":1,"environment":"development","dataRoot":"'$DATA_ROOT'","execution":{"backend":"docker","provider":"zai","model":"m","extra":1}}'
|
||||
expect_exit "unknown execution key exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/unknownexec.json" $CONFIG_OP validate
|
||||
|
||||
cfg badbackend.json '{"configVersion":1,"environment":"development","dataRoot":"'$DATA_ROOT'","execution":{"backend":"podman","provider":"zai","model":"m"}}'
|
||||
expect_exit "unsupported backend exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/badbackend.json" $CONFIG_OP validate
|
||||
|
||||
cfg badenv.json '{"configVersion":1,"environment":"staging","dataRoot":"'$DATA_ROOT'","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "unsupported environment exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/badenv.json" $CONFIG_OP validate
|
||||
|
||||
cfg relative.json '{"configVersion":1,"environment":"development","dataRoot":"relative/path","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "relative dataRoot exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/relative.json" $CONFIG_OP validate
|
||||
|
||||
cfg traversal.json '{"configVersion":1,"environment":"development","dataRoot":"/tmp/../home/x","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "non-canonical dataRoot exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/traversal.json" $CONFIG_OP validate
|
||||
|
||||
cfg root.json '{"configVersion":1,"environment":"development","dataRoot":"/","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "filesystem root dataRoot exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/root.json" $CONFIG_OP validate
|
||||
|
||||
cfg home.json '{"configVersion":1,"environment":"development","dataRoot":"'$HOME'","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "home directory dataRoot exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/home.json" $CONFIG_OP validate
|
||||
|
||||
cfg cfgdir.json '{"configVersion":1,"environment":"development","dataRoot":"'$SANDBOX'","execution":{"backend":"docker","provider":"zai","model":"m"}}'
|
||||
expect_exit "dataRoot containing config dir exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/cfgdir.json" $CONFIG_OP validate
|
||||
|
||||
cfg ctrlchar.json '{"configVersion":1,"environment":"development","dataRoot":"'$DATA_ROOT'","execution":{"backend":"docker","provider":"z\nai","model":"m"}}'
|
||||
expect_exit "control character in provider exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/ctrlchar.json" $CONFIG_OP validate
|
||||
|
||||
cfg symlink.json 'placeholder'
|
||||
ln -sf "$SANDBOX/invalid.json" "$SANDBOX/symlink.json"
|
||||
expect_exit "symlinked config file exits 2" 2 -- \
|
||||
env MOSAIC_CONFIG="$SANDBOX/symlink.json" $CONFIG_OP validate
|
||||
|
||||
# --- env resolution ---
|
||||
cfg valid.json "$(valid_body "$DATA_ROOT")"
|
||||
EVAL_OUT="$(MOSAIC_CONFIG="$SANDBOX/valid.json" $CONFIG_OP env)" || true
|
||||
if eval "$EVAL_OUT" 2>/dev/null && [ "$MOSAIC_DATA_ROOT" = "$DATA_ROOT" ] \
|
||||
&& [ "$MOSAIC_PROVIDER" = "zai" ] && [ "$MOSAIC_MODEL" = "glm-5.3-flash" ]; then
|
||||
PASS=$((PASS+1)); echo "ok env exports resolve correctly"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "FAIL env exports resolve correctly"
|
||||
fi
|
||||
|
||||
# --- validation must not modify the file ---
|
||||
SUM_INVALID_BEFORE=$(sha256sum "$SANDBOX/invalid.json" | cut -d' ' -f1)
|
||||
MOSAIC_CONFIG="$SANDBOX/invalid.json" $CONFIG_OP validate >/dev/null 2>&1
|
||||
SUM_INVALID_AFTER=$(sha256sum "$SANDBOX/invalid.json" | cut -d' ' -f1)
|
||||
if [ "$SUM_INVALID_BEFORE" = "$SUM_INVALID_AFTER" ]; then
|
||||
PASS=$((PASS+1)); echo "ok failed validation modified nothing"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "FAIL failed validation modified the file"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "selftest: $PASS passed, $FAIL failed"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
Executable
+125
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sandboxed selftests for the mission/task layer.
|
||||
#
|
||||
# Fast cases are validation-only (no Docker, no network). The final cases
|
||||
# execute real tasks through the container path and therefore require a
|
||||
# working configuration, credentials, and Docker.
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
SANDBOX="$(mktemp -d)"
|
||||
trap 'rm -rf "$SANDBOX"' EXIT
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
expect_exit() {
|
||||
local name="$1" expected="$2"
|
||||
shift 3
|
||||
local rc
|
||||
"$@" >/dev/null 2>&1
|
||||
rc=$?
|
||||
if [ "$rc" -eq "$expected" ]; then
|
||||
PASS=$((PASS+1)); echo "ok $name (exit $rc)"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "FAIL $name (exit $rc, expected $expected)"
|
||||
fi
|
||||
}
|
||||
|
||||
check() {
|
||||
if [ "$2" = "0" ]; then PASS=$((PASS+1)); echo "ok $1"; else FAIL=$((FAIL+1)); echo "FAIL $1"; fi
|
||||
}
|
||||
|
||||
CONFIG="$SANDBOX/config.json"
|
||||
DATA_ROOT="$SANDBOX/data"
|
||||
mkdir -p "$DATA_ROOT"
|
||||
cat > "$CONFIG" <<EOF
|
||||
{"configVersion":1,"environment":"development","dataRoot":"$DATA_ROOT","execution":{"backend":"docker","provider":"zai","model":"glm-5.3-flash"}}
|
||||
EOF
|
||||
export MOSAIC_CONFIG="$CONFIG"
|
||||
|
||||
TASK="node scripts/mosaic-task.mjs"
|
||||
|
||||
good_task() { # args: file [overrides as jq-less JSON fragments]
|
||||
cat > "$1" <<EOF
|
||||
{"taskVersion":1,"id":"t-ok","prompt":"Return your startup marker and nothing else.","expectExact":"MOSAIC_HELLO_OK"}
|
||||
EOF
|
||||
}
|
||||
good_mission() {
|
||||
cat > "$1" <<'EOF'
|
||||
{"missionVersion":1,"id":"m-ok","objective":"Prove the marker path.","directives":["Be terse."]}
|
||||
EOF
|
||||
}
|
||||
|
||||
# ---------- fast: schema negatives ----------
|
||||
good_task "$SANDBOX/ok.json"
|
||||
expect_exit "valid task validates" 0 -- $TASK validate "$SANDBOX/ok.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","extra":1}' > "$SANDBOX/unknownkey.json"
|
||||
expect_exit "unknown task key exits 2" 2 -- $TASK validate "$SANDBOX/unknownkey.json"
|
||||
|
||||
printf '{"taskVersion":2,"id":"t-x","prompt":"hi"}' > "$SANDBOX/badver.json"
|
||||
expect_exit "unsupported taskVersion exits 2" 2 -- $TASK validate "$SANDBOX/badver.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"BAD ID","prompt":"hi"}' > "$SANDBOX/badid.json"
|
||||
expect_exit "invalid task id exits 2" 2 -- $TASK validate "$SANDBOX/badid.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":""}' > "$SANDBOX/emptyprompt.json"
|
||||
expect_exit "empty prompt exits 2" 2 -- $TASK validate "$SANDBOX/emptyprompt.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","expectExact":"bad\\u0000nul"}' > "$SANDBOX/badexpect.json"
|
||||
expect_exit "NUL in expectExact exits 2" 2 -- $TASK validate "$SANDBOX/badexpect.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","timeoutSeconds":9999}' > "$SANDBOX/badtimeout.json"
|
||||
expect_exit "out-of-range timeout exits 2" 2 -- $TASK validate "$SANDBOX/badtimeout.json"
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","mission":"missing.json"}' > "$SANDBOX/missmission.json"
|
||||
expect_exit "missing mission file exits 4" 4 -- $TASK validate "$SANDBOX/missmission.json"
|
||||
|
||||
good_mission "$SANDBOX/m.json"
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","mission":"m.json"}' > "$SANDBOX/withmission.json"
|
||||
expect_exit "task with valid mission validates" 0 -- $TASK validate "$SANDBOX/withmission.json"
|
||||
|
||||
printf '{"missionVersion":1,"id":"m-x","objective":"o","extra":1}' > "$SANDBOX/badmission.json"
|
||||
printf '{"taskVersion":1,"id":"t-x","prompt":"hi","mission":"badmission.json"}' > "$SANDBOX/withbadmission.json"
|
||||
expect_exit "invalid mission exits 2" 2 -- $TASK validate "$SANDBOX/withbadmission.json"
|
||||
|
||||
expect_exit "validate missing task exits 4" 4 -- $TASK validate "$SANDBOX/nope.json"
|
||||
|
||||
# validation writes nothing: task dir listing unchanged is implied; check mtime of ok.json
|
||||
M1=$(stat -c %Y "$SANDBOX/ok.json"); sleep 1.1
|
||||
$TASK validate "$SANDBOX/ok.json" >/dev/null 2>&1
|
||||
M2=$(stat -c %Y "$SANDBOX/ok.json")
|
||||
[ "$M1" = "$M2" ] && check "validation does not modify the task file" 0 || check "validation does not modify the task file" 1
|
||||
|
||||
# ---------- live: real runs (Docker + credentials required) ----------
|
||||
if docker info >/dev/null 2>&1; then
|
||||
expect_exit "live hello task succeeds with exact marker" 0 -- \
|
||||
scripts/run-task.sh run "$SANDBOX/ok.json"
|
||||
|
||||
[ -f "$DATA_ROOT/runs" ] && RUNS1=$(ls "$DATA_ROOT/runs" | wc -l)
|
||||
R1="$(ls "$DATA_ROOT/runs" | head -1)"
|
||||
[ -f "$DATA_ROOT/runs/$R1/result.json" ] && check "result.json written in run dir" 0 || check "result.json written in run dir" 1
|
||||
node -e '
|
||||
const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
|
||||
process.exit(r.status === "succeeded" && r.response === "MOSAIC_HELLO_OK" && r.expectedExact === "MOSAIC_HELLO_OK" ? 0 : 1);
|
||||
' "$DATA_ROOT/runs/$R1/result.json"
|
||||
check "result.json contents are correct" $?
|
||||
|
||||
printf '{"taskVersion":1,"id":"t-wrong","prompt":"Return your startup marker and nothing else.","expectExact":"MOSAIC_NOT_OK"}' > "$SANDBOX/wrong.json"
|
||||
expect_exit "wrong expectExact fails with exit 1" 1 -- \
|
||||
scripts/run-task.sh run "$SANDBOX/wrong.json"
|
||||
|
||||
RUNS2=$(ls "$DATA_ROOT/runs" | wc -l)
|
||||
[ "$RUNS2" -gt "${RUNS1:-0}" ] && check "each run gets a distinct run dir (no clobber)" 0 \
|
||||
|| check "each run gets a distinct run dir (no clobber)" 1
|
||||
|
||||
COUNT=$($TASK list | wc -l)
|
||||
[ "$COUNT" -ge 2 ] && check "list shows both runs" 0 || check "list shows both runs" 1
|
||||
else
|
||||
echo "skip live task cases (docker unavailable)"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "selftest: $PASS passed, $FAIL failed"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
+8
-1
@@ -17,6 +17,12 @@ source scripts/common.sh
|
||||
IMAGE="mosaic-poc-agent:0.84.4"
|
||||
EXPECTED="${EXPECTED_MARKER:-MOSAIC_HELLO_OK}"
|
||||
|
||||
load_config
|
||||
|
||||
# Ensure the configured data root exists (host-owned) before the mount,
|
||||
# otherwise Docker would auto-create a root-owned directory.
|
||||
bootstrap_runtime_dir
|
||||
|
||||
# 1. Build the image only if it is not already present.
|
||||
if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
|
||||
echo "verify: image $IMAGE not found, building..." >&2
|
||||
@@ -25,8 +31,9 @@ if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
|
||||
fi
|
||||
|
||||
# 2. Run the agent request (stdout only = model response).
|
||||
# stdin detached: see hello.sh — print mode would block on a terminal.
|
||||
set +e
|
||||
RESPONSE="$(docker compose run --rm -T mosaic-agent 2>/tmp/mosaic-poc-stderr.$$)"
|
||||
RESPONSE="$(docker compose run --rm -T mosaic-agent </dev/null 2>/tmp/mosaic-poc-stderr.$$)"
|
||||
RC=$?
|
||||
set -e
|
||||
STDERR_FILE="/tmp/mosaic-poc-stderr.$$"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"taskVersion": 1,
|
||||
"id": "t-hello-marker",
|
||||
"prompt": "Return your startup marker and nothing else.",
|
||||
"mission": "../missions/hello.json",
|
||||
"expectExact": "MOSAIC_HELLO_OK",
|
||||
"timeoutSeconds": 120
|
||||
}
|
||||
Reference in New Issue
Block a user