Files
loki/scripts/test/standing-approval.ts
CatoandClaude Opus 5.5 a1b9d212b2 fix: no silent standing approvals for Loki's own ideas, and no dead-end stalls (#1168)
* fix(approvals): standing approvals cover what you ask for, never Loki's own ideas

The owner saw "✅ Done — Check in with Rajif Rao" on Telegram and feared Loki
had contacted someone without permission. Nothing was sent: a commitment is a
row in the operator's own list. But the path was still wrong. The check-in
producer writes its suggestions as create_commitment rows, so the "Record
commitments I mention" standing approval silently approved one nobody
mentioned, and the confirmation read as if the check-in had happened.

- standing-approval: RAIL 0. Every proposal now carries a required origin
  ("operator" | "loki"); only operator proposals may ride a standing rule.
- enqueueAction takes the origin from every caller and stamps it on the
  payload so the calendar drain's confirmation can say the same thing.
- Check-ins, the night plan and propose calls marked "not asked for" are
  origin "loki"; chat, the agent's propose tool and MCP are "operator".
- A commitment's confirmation now reads "📌 Added to your commitments —
  “Reach out to …”. A reminder for you. Nothing was sent to anyone."
- The Approvals setting says Loki's own suggestions still wait for a yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(control): a stalled queue always has a button, and names who holds it

On a phone the owner tapped "Run it in the cloud" under "Waiting for this
computer". The next refresh said "Stalled — 2 dispatches queued for 118m, the
builder is connected but not executing them. Restart the desktop app or check
the cloud builder if this persists", with no button, under a foot line that
read "This computer offline". Three things were wrong:

- The stall clock ran from created_at, so work the cloud had held for seconds
  was reported as 118 minutes stuck. A reroute now stamps reroutedAt and the
  detector measures from it.
- The sentence blamed a desktop app for work the cloud was holding. The stall
  query now counts cloud-held rows too, and the headline names the builder
  that actually has the work and whether it is connected.
- A genuine stall had no way forward. It now offers "Stop waiting"
  (POST /api/control/stop-waiting): the stuck rows close as failed dispatches,
  where Retry sends them again verbatim and Dismiss clears them, and their
  runs close so the project's lane is free. The consequence is stated in the
  headline before the tap.

Both hero queue buttons now report what they did ("Handed 2 dispatches to the
cloud builder.", or why a project stayed put) instead of firing and forgetting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(loki): a screenshot sent with "fix this" finds the project it shows

On a phone the owner opened a new chat, attached a screenshot of Loki's own
Control page and wrote "Fix this so it works properly". The thread read
"No project — answers only": the text named no project, so the screenshot
fast path could not dispatch, and the picture was only ever described,
never used to decide where the fix should go.

- The vision preflight now opens with one line, "Shown: <app or site, and
  any URL visible>".
- projectShownInScreenshot picks a project only when the evidence points at
  exactly one: a project's live host visible in the analysis (compared whole,
  so loki.orangecat.ch is Loki and not OrangeCat), else a single project
  named on the Shown line. Projects merely listed on the screen do not count,
  and two candidates stay a question for the person.
- When Loki chose the project this way the reply says so and how to pick a
  different one, so a guess never reads as the person's own choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

* fix(notify): a failed run's Telegram message links to where Retry is

"❌ loki: run error … choose another AI provider and Retry" arrived with
nothing to tap. Failed, partial and timed-out runs now carry one button,
"Open <project> in Control", which lands on the project card where Retry and
the provider switch live. Successes stay buttonless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XXM7KBHBym6au4L6sxShwz

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 06:40:51 -07:00

220 lines
7.7 KiB
TypeScript

// Pins the rails on standing approvals — the rule that lets Loki act without
// asking.
//
// Why it earns a test: this is the only code in the app that can turn a
// proposal into a real-world effect with no human in the loop. Every other
// guard in the action queue fails safe by doing nothing; this one fails by
// DOING something. The dangerous direction is a false `auto: true`, so the
// three rails are asserted from the side that hurts:
//
// 1. an ineligible type can never be authorised, even by a stored preference
// that names it — a database row must not be able to widen the set;
// 2. an event with guests goes back to the queue, because guests mean
// invitations, which are outbound and not undoable;
// 3. "we don't know when" is not "yes" — an unresolvable or past slot queues.
//
// The negative cases are the point. A test that only proved the happy path
// would pass just as happily on a version that returned `{auto:true}` for
// everything.
import {
STANDING_APPROVAL_ELIGIBLE,
isStandingApprovalEligible,
sanitizeStandingApprovals,
standingApprovalVerdict,
} from "@/lib/actions/standing-approval";
import { ACTION_TYPE } from "@/lib/constants/statuses";
const NOW = Date.parse("2026-09-17T10:00:00Z");
const SOON = { eventStart: "2026-09-19T14:00:00+02:00", eventEnd: "2026-09-19T15:00:00+02:00" };
const ALL = [ACTION_TYPE.CREATE_EVENT, ACTION_TYPE.CREATE_COMMITMENT];
let pass = 0;
const cases: Array<[string, boolean]> = [];
const check = (name: string, cond: boolean) => {
cases.push([name, cond]);
if (cond) pass++;
};
type VerdictArgs = Parameters<typeof standingApprovalVerdict>[0];
// Every case below is an operator request unless it says otherwise: RAIL 0 is
// asserted on its own, and the other rails must hold even for asked-for work.
const auto = (args: Omit<VerdictArgs, "origin"> & { origin?: VerdictArgs["origin"] }) =>
standingApprovalVerdict({ now: NOW, origin: "operator", ...args }).auto;
// ── RAIL 0: a rule covers what the operator asked for, never Loki's own ideas ─
// 2026-10-12: a "Check in with <name>" commitment from the check-in producer
// rode "Record commitments I mention" and was announced as "✅ Done".
check(
"Loki's own commitment (a check-in) ⇒ queues despite the rule",
!auto({
type: ACTION_TYPE.CREATE_COMMITMENT,
payload: { commitment: "Reach out to Rajif Rao", dueDate: "2026-10-15" },
standingApprovals: ALL,
origin: "loki",
}),
);
check(
"Loki's own calendar event ⇒ queues despite the rule",
!auto({ type: ACTION_TYPE.CREATE_EVENT, payload: SOON, standingApprovals: ALL, origin: "loki" }),
);
check(
"a declined Loki suggestion says why",
(() => {
const v = standingApprovalVerdict({
type: ACTION_TYPE.CREATE_COMMITMENT,
payload: { commitment: "x" },
standingApprovals: ALL,
origin: "loki",
now: NOW,
});
return !v.auto && v.reason.includes("Loki suggested");
})(),
);
// ── RAIL 1: eligibility is code, not data ───────────────────────────────────
check(
"eligible set is exactly create_event + create_commitment",
STANDING_APPROVAL_ELIGIBLE.length === 2 &&
STANDING_APPROVAL_ELIGIBLE.includes(ACTION_TYPE.CREATE_EVENT) &&
STANDING_APPROVAL_ELIGIBLE.includes(ACTION_TYPE.CREATE_COMMITMENT),
);
for (const type of [
ACTION_TYPE.SEND_EMAIL,
ACTION_TYPE.SEND_MESSAGE,
ACTION_TYPE.DISPATCH_PROMPT,
ACTION_TYPE.IMPORT_PERSON,
ACTION_TYPE.ENRICH_PERSON,
ACTION_TYPE.MERGE_PEOPLE,
ACTION_TYPE.FOLLOW_UP,
ACTION_TYPE.OTHER,
] as const) {
check(`${type} is NOT eligible`, !isStandingApprovalEligible(type));
// The nasty one: a preference row that explicitly names an outbound type.
check(
`${type} is refused even when the stored preference names it`,
!auto({ type, payload: { to: "someone@example.com", body: "hi" }, standingApprovals: [type] }),
);
}
check(
"sanitize drops ineligible and unknown values",
JSON.stringify(
sanitizeStandingApprovals(["send_email", "create_event", "nonsense", "merge_people"]),
) === JSON.stringify([ACTION_TYPE.CREATE_EVENT]),
);
check("sanitize of null is empty", sanitizeStandingApprovals(null).length === 0);
check(
"sanitize dedupes repeats",
sanitizeStandingApprovals(["create_event", "create_event"]).length === 1,
);
// ── The rule has to actually work, or it is just a stricter queue ───────────
check(
"event with a real slot and a rule ⇒ auto",
auto({ type: ACTION_TYPE.CREATE_EVENT, payload: SOON, standingApprovals: ALL }),
);
check(
"all-day event ⇒ auto",
auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { eventDate: "2026-09-20", allDay: true },
standingApprovals: ALL,
}),
);
check(
"commitment with a rule ⇒ auto",
auto({
type: ACTION_TYPE.CREATE_COMMITMENT,
payload: { commitment: "call the landlord" },
standingApprovals: ALL,
}),
);
check(
"no rule set ⇒ queues (this is the default for a user who never opted in)",
!auto({ type: ACTION_TYPE.CREATE_EVENT, payload: SOON, standingApprovals: [] }),
);
check(
"a rule for the OTHER eligible type does not cover this one",
!auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: SOON,
standingApprovals: [ACTION_TYPE.CREATE_COMMITMENT],
}),
);
// ── RAIL 2: guests mean invitations, which are outbound ─────────────────────
for (const [name, payload] of [
["attendees array", { ...SOON, attendees: ["ana@example.com"] }],
["attendees string", { ...SOON, attendees: "ana@example.com" }],
["guests field", { ...SOON, guests: ["ana@example.com"] }],
["invitees field", { ...SOON, invitees: ["ana@example.com"] }],
["eventAttendees field", { ...SOON, eventAttendees: ["ana@example.com"] }],
] as const) {
check(
`event with ${name} ⇒ queues despite the rule`,
!auto({ type: ACTION_TYPE.CREATE_EVENT, payload, standingApprovals: ALL }),
);
}
check(
"an EMPTY attendees array is not guests",
auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { ...SOON, attendees: [] },
standingApprovals: ALL,
}),
);
check(
"a blank attendees string is not guests",
auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { ...SOON, attendees: " " },
standingApprovals: ALL,
}),
);
// ── RAIL 3: unknown is not yes ──────────────────────────────────────────────
check(
"event with no resolvable time ⇒ queues",
!auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { body: "sometime next week probably" },
standingApprovals: ALL,
}),
);
check(
"event with an unparseable time ⇒ queues",
!auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { eventStart: "next tuesday" },
standingApprovals: ALL,
}),
);
check(
"null payload ⇒ queues",
!auto({ type: ACTION_TYPE.CREATE_EVENT, payload: null, standingApprovals: ALL }),
);
check(
"event whose slot already passed ⇒ queues (never books into the past)",
!auto({
type: ACTION_TYPE.CREATE_EVENT,
payload: { eventStart: "2026-09-16T09:00:00Z", eventEnd: "2026-09-16T10:00:00Z" },
standingApprovals: ALL,
}),
);
check(
"a declined event says WHY, so the rule never looks broken",
(() => {
const v = standingApprovalVerdict({
type: ACTION_TYPE.CREATE_EVENT,
payload: { ...SOON, attendees: ["ana@example.com"] },
standingApprovals: ALL,
origin: "operator",
now: NOW,
});
return !v.auto && v.reason.includes("guests");
})(),
);
for (const [name, ok] of cases) console.log(`${ok ? "✓" : "✗"} ${name}`);
console.log(`\n${pass}/${cases.length} passed`);
if (pass !== cases.length) process.exit(1);