diff --git a/CHANGELOG.md b/CHANGELOG.md index 78e6344..bda325c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Added +- PAM 0.6.4 authenticated metadata-only review notification scanner and an + owner-only, retryable OpenClaw/Discord relay with stable-marker reconciliation. + - PAM 0.6.3 bounded Fabric proposal drain, immutable proposal/digest binding, authenticated HTTPS decision/apply receipts with separate credentials, atomic record-index refresh, and verifier-only apply receipt checks. diff --git a/deploy/systemd/amf-review-discord-relay b/deploy/systemd/amf-review-discord-relay new file mode 100755 index 0000000..f966592 --- /dev/null +++ b/deploy/systemd/amf-review-discord-relay @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +umask 077 + +CONFIG=${AMF_REVIEW_RELAY_CONFIG:-/etc/default/amf-review-discord-relay} +. "$CONFIG" +mkdir -p "$AMF_REVIEW_STATE_DIR" +chmod 700 "$AMF_REVIEW_STATE_DIR" +INPUT=$(mktemp "$AMF_REVIEW_STATE_DIR/.scan.XXXXXX") +trap 'rm -f "$INPUT"' EXIT HUP INT TERM + +/usr/bin/ssh -o BatchMode=yes -o ConnectTimeout=10 "$AMF_REVIEW_REMOTE" -- "$AMF_REVIEW_REMOTE_COMMAND" >"$INPUT" +chmod 600 "$INPUT" +/usr/bin/node "$AMF_REVIEW_TOOL" relay \ + --input "$INPUT" \ + --state-dir "$AMF_REVIEW_STATE_DIR" \ + --target-file "$AMF_REVIEW_TARGET_FILE" \ + --openclaw-bin "$AMF_REVIEW_OPENCLAW_BIN" diff --git a/deploy/systemd/amf-review-discord-relay.service b/deploy/systemd/amf-review-discord-relay.service new file mode 100644 index 0000000..7cb66ac --- /dev/null +++ b/deploy/systemd/amf-review-discord-relay.service @@ -0,0 +1,18 @@ +[Unit] +Description=PAM metadata-only review notification relay +After=network-online.target openclaw-gateway.service +Wants=network-online.target + +[Service] +Type=oneshot +User= +Group= +ExecStart=/usr/local/sbin/amf-review-discord-relay +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths= +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +LockPersonality=true +RestrictSUIDSGID=true diff --git a/deploy/systemd/amf-review-discord-relay.timer b/deploy/systemd/amf-review-discord-relay.timer new file mode 100644 index 0000000..e24b3d5 --- /dev/null +++ b/deploy/systemd/amf-review-discord-relay.timer @@ -0,0 +1,13 @@ +[Unit] +Description=Run the PAM review notification relay + +[Timer] +OnBootSec=2min +OnUnitActiveSec=2min +RandomizedDelaySec=15s +AccuracySec=5s +Persistent=true +Unit=amf-review-discord-relay.service + +[Install] +WantedBy=timers.target diff --git a/deploy/systemd/amf-review-notification-scan b/deploy/systemd/amf-review-notification-scan new file mode 100755 index 0000000..1436227 --- /dev/null +++ b/deploy/systemd/amf-review-notification-scan @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu +umask 077 + +CONFIG=${AMF_REVIEW_SCAN_CONFIG:-/etc/default/amf-review-notification-scan} +. "$CONFIG" +set -a +. "$PAM_REVIEW_WORKER_ENV" +set +a + +exec /usr/sbin/runuser -u "$PAM_REVIEW_USER" --preserve-environment -- \ + /usr/bin/node "$PAM_REVIEW_TOOL" scan \ + --workspace "$PAM_REVIEW_WORKSPACE" \ + --scope "$PAM_REVIEW_SCOPE" \ + --limit "$PAM_REVIEW_LIMIT" diff --git a/docs/amf-review-notifier.md b/docs/amf-review-notifier.md new file mode 100644 index 0000000..b195ab8 --- /dev/null +++ b/docs/amf-review-notifier.md @@ -0,0 +1,17 @@ +# AMF review notifier + +The notifier has two trust-separated steps: + +1. `scan` runs beside the PAM curator. It verifies the authenticated curator ledger, decision receipt, and Fabric ACK outbox before emitting a metadata-only event. +2. `relay` runs beside an already-authenticated OpenClaw gateway. It accepts only the exact event schema, reads the private channel target from an owner-only file, and keeps an owner-only delivery outbox. + +The event contains only opaque decision/proposal identifiers, canonical scope, confidence, reason codes, and creation time. Claims, provenance, subject identities, secrets, and channel identifiers are excluded. The relay places a stable decision marker in each private message and reads recent channel history before retrying an uncertain delivery. + +```sh +node tools/amf-review-notifier.mjs scan --workspace --scope room: --limit 50 > +node tools/amf-review-notifier.mjs relay --input --state-dir --target-file +``` + +Keep timer output aggregate-only. Do not log the scan JSON or OpenClaw command arguments. + +Linux systemd deployment templates live in `deploy/systemd/`. Keep the scanner beside the authenticated curator state and the relay beside OpenClaw. Put host-specific paths, the exact canonical scope, remote SSH target, and the Discord channel identifier only in owner-only `/etc/default` or user configuration files; never commit them. diff --git a/memory/pam.version.json b/memory/pam.version.json index 2e4cbf2..345eb37 100644 --- a/memory/pam.version.json +++ b/memory/pam.version.json @@ -1,5 +1,5 @@ { - "pamVersion": "0.6.3", + "pamVersion": "0.6.4", "memoryFormat": "graph-v1", "graphSchemaVersion": "pam-graph-v1", "features": { diff --git a/migrations/0.6.3-to-0.6.4-review-notifier.md b/migrations/0.6.3-to-0.6.4-review-notifier.md new file mode 100644 index 0000000..624c93a --- /dev/null +++ b/migrations/0.6.3-to-0.6.4-review-notifier.md @@ -0,0 +1,10 @@ +# PAM 0.6.3 to 0.6.4 — review notification relay + +PAM 0.6.4 adds an authenticated, metadata-only review notification scanner and a durable relay for `review_required` decisions. + +1. Keep the curator ledger and Fabric decision ACK outbox available to the scanner. +2. Run the scanner with one exact canonical scope; it emits no claim, provenance, subject, or secret material. +3. Store the Discord channel target in an owner-only file and use an already-authenticated OpenClaw gateway for delivery. +4. Run the relay from a timer. Its owner-only outbox and stable decision marker make retries recoverable without resending after an ambiguous success. + +No existing PAM memory record changes shape in this release. diff --git a/package.json b/package.json index 441c84c..2706a27 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "portable-agent-memory", - "version": "0.6.3", + "version": "0.6.4", "private": false, "description": "Markdown-first portable memory, wiki, and maintenance toolkit for AI agents.", "type": "module", @@ -23,6 +23,7 @@ "memory:synthesis": "node tools/memory-maintenance.mjs synthesis", "memory:curator": "node tools/memory-curator.mjs", "memory:fabric-worker": "node tools/amf-fabric-worker.mjs", + "memory:review-notifier": "node tools/amf-review-notifier.mjs", "memory:schedule:install": "node tools/install-memory-maintenance-schedule.mjs", "migrations:check": "node tools/check-migrations.mjs", "mcp:serve": "node tools/pam-mcp-server.mjs", diff --git a/tools/amf-review-notifier.mjs b/tools/amf-review-notifier.mjs new file mode 100644 index 0000000..787552b --- /dev/null +++ b/tools/amf-review-notifier.mjs @@ -0,0 +1,45 @@ +#!/usr/bin/env node +import path from "node:path"; + +import { relayReviewNotifications, scanReviewNotifications } from "./lib/amf-review-notifier.mjs"; +import { loadWorkspaceConfig } from "./lib/workspace.mjs"; +import { readOwnerOnlyFileSync } from "./lib/secure-fs.mjs"; + +function argument(name) { + const index = process.argv.indexOf(name); + return index < 0 ? null : process.argv[index + 1]; +} +function count(name, fallback) { + const raw = argument(name); + const value = raw === null ? fallback : Number(raw); + if (!Number.isSafeInteger(value)) throw new Error(`${name} is invalid`); + return value; +} + +async function main() { + const command = process.argv[2]; + if (command === "scan") { + const workspace = path.resolve(argument("--workspace") || process.cwd()); + const result = scanReviewNotifications(workspace, loadWorkspaceConfig(workspace), { + scope: argument("--scope"), limit: count("--limit", 50) + }); + process.stdout.write(`${JSON.stringify(result)}\n`); + return; + } + if (command === "relay") { + const scan = JSON.parse(readOwnerOnlyFileSync(argument("--input"), { label: "review scan input", maxBytes: 1024 * 1024 })); + const result = relayReviewNotifications(scan, { + stateDir: argument("--state-dir"), targetFile: argument("--target-file"), + openclawBin: argument("--openclaw-bin") || "/usr/local/bin/openclaw", + dryRun: process.argv.includes("--dry-run") + }, { execFileSync: (await import("node:child_process")).execFileSync }); + process.stdout.write(`${JSON.stringify(result)}\n`); + return; + } + throw new Error("usage: amf-review-notifier.mjs scan|relay"); +} + +main().catch(error => { + process.stderr.write(`amf-review-notifier: ${error.message}\n`); + process.exitCode = 1; +}); diff --git a/tools/lib/amf-review-notifier.mjs b/tools/lib/amf-review-notifier.mjs new file mode 100644 index 0000000..dca8f5d --- /dev/null +++ b/tools/lib/amf-review-notifier.mjs @@ -0,0 +1,202 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; + +import { canonicalize } from "./amf-memory-record.mjs"; +import { buildFabricDecisionReceipt, curatorPolicy, curatorStatus } from "./memory-curator.mjs"; +import { atomicWriteFileSync, readFileNoFollowSync, readOwnerOnlyFileSync } from "./secure-fs.mjs"; + +const SCAN_SCHEMA = "amf-review-notification-scan/v1"; +const ENVELOPE_SCHEMA = "amf-review-notification-envelope/v1"; +const HASH_RE = /^[a-f0-9]{64}$/; +const DECISION_RE = /^decision-[a-f0-9]{40}$/; +const SAFE_SCOPE_RE = /^(agent|person|relationship|room|domain|shared):[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/; +const SAFE_REASON_RE = /^[a-z][a-z0-9-]{0,63}$/; + +function object(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } +function exact(value, fields) { return object(value) && Object.keys(value).sort().join("\0") === [...fields].sort().join("\0"); } +function sha256(value) { return crypto.createHash("sha256").update(String(value), "utf8").digest("hex"); } +function artifactMac(key, value) { + const copy = { ...value }; delete copy.artifactMac; + return crypto.createHmac("sha256", key).update(canonicalize(copy), "utf8").digest("hex"); +} +function safeEqual(left, right) { + if (!HASH_RE.test(String(left)) || !HASH_RE.test(String(right))) return false; + return crypto.timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex")); +} +function ledgerKey(config, runtime = {}) { + const policy = curatorPolicy(config); + const envName = policy.ledgerKeyEnv || "PAM_CURATOR_LEDGER_KEY"; + const value = runtime.ledgerKey ?? (runtime.env || process.env)[envName]; + if (typeof value !== "string" || Buffer.byteLength(value, "utf8") < 32) throw new Error("review notifier ledger key is unavailable"); + return Buffer.from(value, "utf8"); +} + +function readAuthenticatedArtifact(workspaceRoot, absolute, key, label) { + const value = JSON.parse(readFileNoFollowSync(workspaceRoot, absolute)); + if (!safeEqual(value.artifactMac, artifactMac(key, value))) throw new Error(`${label} authentication failed`); + return value; +} + +function validateEvent(event) { + return exact(event, new Set(["decisionId", "decisionDigest", "proposalId", "scope", "confidence", "reasonCodes", "createdAt"])) + && DECISION_RE.test(String(event.decisionId)) && HASH_RE.test(String(event.decisionDigest)) + && /^[A-Za-z0-9][A-Za-z0-9-]{0,127}$/.test(String(event.proposalId)) + && SAFE_SCOPE_RE.test(String(event.scope)) + && typeof event.confidence === "number" && event.confidence >= 0 && event.confidence <= 1 + && Array.isArray(event.reasonCodes) && event.reasonCodes.length <= 16 + && new Set(event.reasonCodes).size === event.reasonCodes.length + && event.reasonCodes.every(reason => SAFE_REASON_RE.test(String(reason))) + && Number.isFinite(Date.parse(event.createdAt)); +} + +function scanReviewNotifications(workspaceRoot, config, input = {}, runtime = {}) { + const scope = String(input.scope || ""); + const limit = input.limit ?? 50; + if (!SAFE_SCOPE_RE.test(scope) || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("review notification scan input is invalid"); + const status = curatorStatus(workspaceRoot, config, {}, runtime); + if (!status.ok) throw new Error("curator ledger is not healthy"); + const key = ledgerKey(config, runtime); + const events = []; + for (const candidate of status.candidates) { + const decision = candidate.latestDecision; + if (decision?.outcome !== "review_required") continue; + const receiptPath = path.join(workspaceRoot, "memory/amf/curator/decision-receipts", `${decision.decisionId}.json`); + const outboxPath = path.join(workspaceRoot, "memory/amf/curator/fabric-outbox", `${decision.decisionId}.json`); + if (!fs.existsSync(receiptPath) || !fs.existsSync(outboxPath)) continue; + const receipt = readAuthenticatedArtifact(workspaceRoot, receiptPath, key, "decision receipt"); + if (receipt.fabricProposalScope !== scope) continue; + const outbox = readAuthenticatedArtifact(workspaceRoot, outboxPath, key, "Fabric decision ACK"); + const built = buildFabricDecisionReceipt(receipt); + if (!built.ok || outbox.phase !== "fabric_acked" || !object(outbox.ack) + || canonicalize(outbox.receipt) !== canonicalize(built.receipt) + || receipt.decisionDigest !== decision.decisionDigest || receipt.fabricProposalScope !== scope) { + throw new Error("review notification is not bound to an acknowledged Fabric decision"); + } + const event = { + decisionId: decision.decisionId, + decisionDigest: decision.decisionDigest, + proposalId: receipt.fabricProposalId, + scope, + confidence: decision.confidence, + reasonCodes: [...decision.reasonCodes], + createdAt: receipt.createdAt + }; + if (!validateEvent(event)) throw new Error("review notification metadata is invalid"); + events.push(event); + } + events.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.decisionId.localeCompare(right.decisionId)); + return { schema: SCAN_SCHEMA, events: events.slice(0, limit) }; +} + +function assertPrivateDirectory(directory) { + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + const stat = fs.lstatSync(directory); + if (!stat.isDirectory() || (stat.mode & 0o077) !== 0 + || (typeof process.geteuid === "function" && stat.uid !== process.geteuid())) { + throw new Error("review notifier state directory must be owner-only"); + } +} + +function envelopePath(stateDir, event) { + return path.join(stateDir, `${sha256(`review-notification\0${event.decisionId}`)}.json`); +} + +function writeEnvelope(stateDir, absolute, envelope) { + atomicWriteFileSync(stateDir, absolute, `${JSON.stringify(envelope, null, 2)}\n`, { mode: 0o600 }); + fs.chmodSync(absolute, 0o600); +} + +function readEnvelope(stateDir, absolute) { + const value = JSON.parse(readFileNoFollowSync(stateDir, absolute)); + if (!exact(value, new Set(["schema", "event", "status", "attempts", "lastErrorCode", "updatedAt"])) + || value.schema !== ENVELOPE_SCHEMA || !validateEvent(value.event) + || !["pending", "sent"].includes(value.status) || !Number.isSafeInteger(value.attempts) || value.attempts < 0 + || ![null, "delivery_failed", "history_unavailable"].includes(value.lastErrorCode) + || !Number.isFinite(Date.parse(value.updatedAt))) throw new Error("review notifier envelope is invalid"); + return value; +} + +function strings(value, output = []) { + if (typeof value === "string") output.push(value); + else if (Array.isArray(value)) for (const item of value) strings(item, output); + else if (object(value)) for (const item of Object.values(value)) strings(item, output); + return output; +} + +function renderMessage(event) { + const marker = `AMF-REVIEW:${event.decisionId}`; + return [ + "Memory review required", + `Marker: ${marker}`, + `Decision: ${event.decisionId}`, + `Proposal: ${event.proposalId}`, + `Scope: ${event.scope}`, + `Confidence: ${event.confidence.toFixed(3)}`, + `Reasons: ${event.reasonCodes.join(", ") || "manual-review"}`, + `Created: ${event.createdAt}`, + "Review: inspect the private PAM curation ledger, then record an authenticated approve or reject decision." + ].join("\n"); +} + +function relayReviewNotifications(scan, options, runtime = {}) { + if (!exact(scan, new Set(["schema", "events"])) || scan.schema !== SCAN_SCHEMA + || !Array.isArray(scan.events) || scan.events.length > 100 || scan.events.some(event => !validateEvent(event))) { + throw new Error("review notification scan payload is invalid"); + } + if (options.dryRun === true) return { ok: true, mode: "dry-run", discovered: scan.events.length, queued: 0, sent: 0, pending: scan.events.length }; + const stateDir = path.resolve(String(options.stateDir || "")); + assertPrivateDirectory(stateDir); + const target = readOwnerOnlyFileSync(options.targetFile, { label: "Discord target file", maxBytes: 128 }).trim(); + if (!/^[0-9]{16,24}$/.test(target)) throw new Error("Discord target file is invalid"); + const openclaw = path.resolve(String(options.openclawBin || "/usr/local/bin/openclaw")); + const exec = runtime.execFileSync; + if (typeof exec !== "function") throw new Error("review notifier dispatcher is unavailable"); + const now = runtime.now || (() => new Date()); + let queued = 0; let sent = 0; let pending = 0; + + for (const event of scan.events) { + const absolute = envelopePath(stateDir, event); + if (!fs.existsSync(absolute)) { + writeEnvelope(stateDir, absolute, { schema: ENVELOPE_SCHEMA, event, status: "pending", attempts: 0, lastErrorCode: null, updatedAt: now().toISOString() }); + queued += 1; + } else { + const existing = readEnvelope(stateDir, absolute); + if (canonicalize(existing.event) !== canonicalize(event)) throw new Error("review notifier envelope conflict"); + } + } + + let history = null; + try { + const result = exec(openclaw, ["message", "read", "--channel", "discord", "--target", `channel:${target}`, "--limit", "100", "--json"], { encoding: "utf8", maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); + history = strings(JSON.parse(result)).join("\n"); + } catch {} + + for (const event of scan.events) { + const absolute = envelopePath(stateDir, event); + let envelope = readEnvelope(stateDir, absolute); + if (envelope.status === "sent") continue; + const marker = `AMF-REVIEW:${event.decisionId}`; + if (history?.includes(marker)) { + envelope = { ...envelope, status: "sent", lastErrorCode: null, updatedAt: now().toISOString() }; + writeEnvelope(stateDir, absolute, envelope); sent += 1; continue; + } + if (envelope.attempts > 0 && history === null) { + envelope = { ...envelope, lastErrorCode: "history_unavailable", updatedAt: now().toISOString() }; + writeEnvelope(stateDir, absolute, envelope); pending += 1; continue; + } + envelope = { ...envelope, attempts: envelope.attempts + 1, lastErrorCode: null, updatedAt: now().toISOString() }; + writeEnvelope(stateDir, absolute, envelope); + try { + exec(openclaw, ["message", "send", "--channel", "discord", "--target", `channel:${target}`, "--message", renderMessage(event), "--silent", "--json"], { encoding: "utf8", maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); + envelope = { ...envelope, status: "sent", updatedAt: now().toISOString() }; + writeEnvelope(stateDir, absolute, envelope); sent += 1; + } catch { + envelope = { ...envelope, lastErrorCode: "delivery_failed", updatedAt: now().toISOString() }; + writeEnvelope(stateDir, absolute, envelope); pending += 1; + } + } + return { ok: pending === 0, mode: "relay", discovered: scan.events.length, queued, sent, pending }; +} + +export { ENVELOPE_SCHEMA, SCAN_SCHEMA, relayReviewNotifications, scanReviewNotifications }; diff --git a/tools/lib/memory-curator.mjs b/tools/lib/memory-curator.mjs index 611f635..5688a75 100644 --- a/tools/lib/memory-curator.mjs +++ b/tools/lib/memory-curator.mjs @@ -2031,6 +2031,8 @@ function curatorStatus(workspaceRoot, config, input = {}, runtime = {}) { action: latest.action, outcome: receipt.outcome, decisionDigest: receipt.decisionDigest, + confidence: latest.confidence, + reasonCodes: [...latest.reasons], actorIdSha256: sha256(latest.actorId), reviewerLabelSha256: sha256(latest.reviewerLabel) } : null diff --git a/tools/test-amf-review-notifier.mjs b/tools/test-amf-review-notifier.mjs new file mode 100644 index 0000000..4f9888e --- /dev/null +++ b/tools/test-amf-review-notifier.mjs @@ -0,0 +1,52 @@ +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { canonicalize } from "./lib/amf-memory-record.mjs"; +import { relayReviewNotifications, scanReviewNotifications, SCAN_SCHEMA } from "./lib/amf-review-notifier.mjs"; +import { submitCuratorCandidate } from "./lib/memory-curator.mjs"; + +const LEDGER_KEY = "review-notifier-ledger-key-0000000000000000000000001"; +const REVIEWER_TOKEN = "review-notifier-reviewer-token-0001"; +const SCOPE = "room:synthetic:review"; +function sha(value) { return crypto.createHash("sha256").update(String(value)).digest("hex"); } +function mac(value) { const copy = { ...value }; delete copy.artifactMac; return crypto.createHmac("sha256", LEDGER_KEY).update(canonicalize(copy)).digest("hex"); } +function workspace() { const root = fs.mkdtempSync(path.join(os.tmpdir(), "pam-review-notifier-")); fs.mkdirSync(path.join(root, "memory/graph"), { recursive: true }); for (const name of ["nodes.jsonl", "edges.jsonl", "aliases.jsonl"]) fs.writeFileSync(path.join(root, "memory/graph", name), ""); return root; } +function config() { return { protectedPaths: ["AGENTS.md", "memory/agent-memory", "memory/sources"], amfCurator: { version: "amf-curator-policy/v1", autoPromote: false, minimumConfidence: 0.98, autoScopes: ["room"], autoVisibilities: ["shared"], requireReviewForLifecycleChange: true, requireReviewForSupersession: true, rejectOnWarnings: true, ledgerKeyEnv: "PAM_CURATOR_LEDGER_KEY", stateDirEnv: "PAM_CURATOR_STATE_DIR", reviewerTokenEnv: "PAM_CURATOR_REVIEWER_TOKEN", reviewers: [{ tokenSha256: sha(REVIEWER_TOKEN), actorId: "service:synthetic-reviewer", capabilities: ["memory:curate"] }], gitWriter: { enabled: false, dryRunOnly: true, protectedBranches: ["main"] } } }; } +function record() { const timestamp = "2026-07-12T20:00:00Z"; return { schema: "amf-memory/v1", id: "mem_12345678-1234-4234-8234-123456789abc", revision: 1, claimType: "fact", scope: { type: "room", id: SCOPE }, visibility: "shared", confidence: { score: 0.81, basis: "inferred", assessedAt: timestamp }, subjects: [{ identityId: "agent:12345678-1234-4234-8234-123456789abc", role: "owner" }], claim: { encoding: "plain", text: "Private candidate text must never enter a notification." }, lifecycle: { status: "active", validFrom: timestamp, validTo: null, supersedes: [], revokedAt: null, revocationReason: null }, provenance: [{ sourceType: "synthetic-test", sourceId: "source-private", eventId: "event-review-0001", contentSha256: "a".repeat(64), capturedAt: timestamp }], createdAt: timestamp, updatedAt: timestamp }; } +function render(value) { return `---\n${Object.entries(value).map(([key, item]) => `${key}: ${item !== null && typeof item === "object" ? JSON.stringify(item) : String(item)}`).join("\n")}\n---\n`; } + +test("scanner emits only authenticated metadata after Fabric ACK", () => { + const root = workspace(); const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "pam-review-state-")); fs.chmodSync(stateDir, 0o700); + const proposalId = "proposal-review-0001"; const proposalDigest = "b".repeat(64); + const result = submitCuratorCandidate(root, config(), { content: render(record()), rationale: "synthetic", idempotencyKey: "review-notifier-0001", confidence: 0.81, source: { type: "fabric", id: proposalId }, fabricProposal: { proposalId, proposalDigest } }, { ledgerKey: LEDGER_KEY, reviewerToken: REVIEWER_TOKEN, stateDir }); + assert.equal(result.ok, true, result.error); assert.equal(result.status, "review_required"); + const outbox = { schema: "amf-fabric-transport/v1/decision-outbox", phase: "fabric_acked", receipt: result.fabricReceipt, ack: { ackId: "ack-review-0001", acknowledgedAt: "2026-07-12T20:01:00Z" } }; outbox.artifactMac = mac(outbox); + const outboxDir = path.join(root, "memory/amf/curator/fabric-outbox"); fs.mkdirSync(outboxDir, { recursive: true, mode: 0o700 }); fs.writeFileSync(path.join(outboxDir, `${result.decisionId}.json`), `${JSON.stringify(outbox)}\n`, { mode: 0o600 }); + const scan = scanReviewNotifications(root, config(), { scope: SCOPE }, { ledgerKey: LEDGER_KEY, reviewerToken: REVIEWER_TOKEN, stateDir }); + assert.equal(scan.events.length, 1); assert.equal(scan.events[0].proposalId, proposalId); assert.equal(scan.events[0].confidence, 0.81); assert.ok(scan.events[0].reasonCodes.includes("auto-promotion-disabled")); + const text = JSON.stringify(scan); assert.equal(text.includes("Private candidate"), false); assert.equal(text.includes("source-private"), false); + const tampered = { ...outbox, phase: "queued" }; fs.writeFileSync(path.join(outboxDir, `${result.decisionId}.json`), JSON.stringify(tampered)); assert.throws(() => scanReviewNotifications(root, config(), { scope: SCOPE }, { ledgerKey: LEDGER_KEY, reviewerToken: REVIEWER_TOKEN, stateDir }), /authentication failed/); +}); + +function event() { return { decisionId: `decision-${"c".repeat(40)}`, decisionDigest: "d".repeat(64), proposalId: "proposal-review-0002", scope: SCOPE, confidence: 0.72, reasonCodes: ["below-confidence-threshold"], createdAt: "2026-07-12T20:00:00Z" }; } +function relayFixture() { const root = fs.mkdtempSync(path.join(os.tmpdir(), "pam-review-relay-")); fs.chmodSync(root, 0o700); const secrets = fs.mkdtempSync(path.join(os.tmpdir(), "pam-review-target-")); fs.chmodSync(secrets, 0o700); const targetFile = path.join(secrets, "discord.target"); fs.writeFileSync(targetFile, "123456789012345678\n", { mode: 0o600 }); return { root, targetFile }; } + +test("relay is metadata-only, durable and idempotent", () => { + const fixture = relayFixture(); const calls = []; const exec = (_file, args) => { calls.push(args); return args[1] === "read" ? JSON.stringify({ messages: [] }) : JSON.stringify({ ok: true }); }; const scan = { schema: SCAN_SCHEMA, events: [event()] }; + const first = relayReviewNotifications(scan, { stateDir: fixture.root, targetFile: fixture.targetFile }, { execFileSync: exec }); assert.equal(first.sent, 1); assert.equal(first.pending, 0); + const sent = calls.find(args => args[1] === "send").join("\n"); assert.match(sent, /AMF-REVIEW:/); assert.match(sent, /below-confidence-threshold/); assert.doesNotMatch(sent, /claim|ciphertext|source-private/); + calls.length = 0; const retry = relayReviewNotifications(scan, { stateDir: fixture.root, targetFile: fixture.targetFile }, { execFileSync: exec }); assert.equal(retry.sent, 0); assert.equal(calls.some(args => args[1] === "send"), false); + assert.throws(() => relayReviewNotifications({ schema: SCAN_SCHEMA, events: [{ ...event(), payload: "private" }] }, { dryRun: true }, {}), /invalid/); +}); + +test("relay reconciles uncertain delivery through the stable marker", () => { + const fixture = relayFixture(); const scan = { schema: SCAN_SCHEMA, events: [event()] }; let phase = "fail"; let sends = 0; + const exec = (_file, args) => { if (args[1] === "read") { if (phase === "no-history") throw new Error("offline"); return JSON.stringify({ messages: phase === "delivered" ? [{ content: `AMF-REVIEW:${event().decisionId}` }] : [] }); } sends += 1; throw new Error("ambiguous delivery"); }; + const failed = relayReviewNotifications(scan, { stateDir: fixture.root, targetFile: fixture.targetFile }, { execFileSync: exec }); assert.equal(failed.pending, 1); assert.equal(sends, 1); + phase = "no-history"; const held = relayReviewNotifications(scan, { stateDir: fixture.root, targetFile: fixture.targetFile }, { execFileSync: exec }); assert.equal(held.pending, 1); assert.equal(sends, 1); + phase = "delivered"; const reconciled = relayReviewNotifications(scan, { stateDir: fixture.root, targetFile: fixture.targetFile }, { execFileSync: exec }); assert.equal(reconciled.sent, 1); assert.equal(reconciled.pending, 0); assert.equal(sends, 1); +});