Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions deploy/systemd/amf-review-discord-relay
Original file line number Diff line number Diff line change
@@ -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"
18 changes: 18 additions & 0 deletions deploy/systemd/amf-review-discord-relay.service
Original file line number Diff line number Diff line change
@@ -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=<relay-user>
Group=<relay-group>
ExecStart=/usr/local/sbin/amf-review-discord-relay
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=<owner-only-state-dir>
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
LockPersonality=true
RestrictSUIDSGID=true
13 changes: 13 additions & 0 deletions deploy/systemd/amf-review-discord-relay.timer
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions deploy/systemd/amf-review-notification-scan
Original file line number Diff line number Diff line change
@@ -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"
17 changes: 17 additions & 0 deletions docs/amf-review-notifier.md
Original file line number Diff line number Diff line change
@@ -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 <workspace-root> --scope room:<canonical-room> --limit 50 > <owner-only-scan-file>
node tools/amf-review-notifier.mjs relay --input <owner-only-scan-file> --state-dir <owner-only-state-dir> --target-file <owner-only-discord-channel-id-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.
2 changes: 1 addition & 1 deletion memory/pam.version.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"pamVersion": "0.6.3",
"pamVersion": "0.6.4",
"memoryFormat": "graph-v1",
"graphSchemaVersion": "pam-graph-v1",
"features": {
Expand Down
10 changes: 10 additions & 0 deletions migrations/0.6.3-to-0.6.4-review-notifier.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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",
Expand Down
45 changes: 45 additions & 0 deletions tools/amf-review-notifier.mjs
Original file line number Diff line number Diff line change
@@ -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;
});
202 changes: 202 additions & 0 deletions tools/lib/amf-review-notifier.mjs
Original file line number Diff line number Diff line change
@@ -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 };
2 changes: 2 additions & 0 deletions tools/lib/memory-curator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading