diff --git a/AGENTS.md b/AGENTS.md index ae653f2..9e13926 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,10 @@ Then run `bun run test`, and name the version in the next `CHANGELOG.md` entry. 3. Commit, tag `vX.Y.Z`, push `main` and the tag. 4. `gh release create vX.Y.Z --title vX.Y.Z --notes-file `. +## Public contracts + +The `script_create` intent and its reply (README, "From a script") are a public API that scripts and other agents depend on. Add fields only as optional ones, never rename or remove a field or change what one means, and bump `format` only for a breaking change. `carly_create` and the other intent kinds are internal and may change freely. + ## Window budget Every window-half call has a 50 ms budget for the plugin's own Lua (native calls don't count, but one call may take at most ten budgets of wall time). A call over it raises `tern: exceeded ms` and Tern pauses that hook (every timer callback, say) for 5 s, doubling on repeats within 10 min, up to 5 min; `pcall` can't catch it. Keep timer passes far below it: the status and observer passes log anything over `const.WINDOW_SLOW_MS` (20 ms), and `window.luau` logs `budget` events and the status line shows *Agent Scheduler paused* while a hook is paused. diff --git a/README.md b/README.md index 08516f0..b3bba16 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ A job can also wait for something worth doing: new commits on a branch, working - [Install](#install) - [Create a job](#create-a-job): [Schedules](#schedules), [Only when](#only-when) -- [The manager](#the-manager): [Settings](#settings), [Carly](#carly) +- [The manager](#the-manager): [Settings](#settings), [Carly](#carly), [From a script](#from-a-script) - [Good to know](#good-to-know) - [Your data](#your-data) - [Develop](#develop) @@ -165,6 +165,47 @@ With each request, Agent Scheduler tells Carly to use it, rather than her own sc > [!NOTE] > Jobs Carly creates are active immediately with the default approval (Hands-off), and Carly can't edit or delete them; change or delete them in the manager. You get a toast and a desktop notification, and the manager marks them `by Carly`. +### From a script + +Scripts, CI jobs and other agents can create a job by dropping a request file into the data folder (see [Your data](#your-data)). Tern must be running. Agent Scheduler picks the request up on its next pass, usually within 2–3 seconds, deletes it, and answers in `replies/.json`. + +```sh +D="$HOME/Library/Application Support/Tern/plugin-data/tern-agent-scheduler" # macOS +# D="$HOME/.local/state/tern/plugin-data/tern-agent-scheduler" # Linux +ID=$(LC_ALL=C tr -dc 'a-z0-9' "$F.tmp" <` (`by script` without one). | +| `expires` | Optional unix seconds. A request still waiting after that is refused instead of applied late. | + +Any other field is refused, so a typo can't quietly make a job you didn't ask for. The job is active immediately with your default approval (**Hands-off** unless you've changed it in Settings); a request can't choose its approval. You get a toast and a desktop notification, as with Carly. + +The reply is `{"format":1,"ok":true,...}` with `job_id`, `name`, `when`, `next` (text), `next_at` (unix seconds; missing for manual-only jobs), `folder`, `role`, `approval`, `only_when`, `quiet_ok` and `source`, or `{"format":1,"ok":false,"error":"..."}` with the message the form would show. Replies are deleted after about five minutes. + +Name request files `--.json` (they're applied in name order), and write them under another name first and rename them into place, as above, so a half-written file is never read. Files over 16 KiB are deleted without a reply, and so is a file that still isn't valid JSON after a minute. A request without a valid `reply` is dropped without a reply. + ## Good to know - **A run waiting for your approval** is only noticed while a desktop Tern window is open. diff --git a/lib/const.luau b/lib/const.luau index 407863e..69a8d9a 100644 --- a/lib/const.luau +++ b/lib/const.luau @@ -86,6 +86,7 @@ const.INTENT_KINDS = { ack_failed = true, focus_manager = true, carly_create = true, + script_create = true, check_conditions = true, } :: { [string]: boolean } diff --git a/lib/intents.luau b/lib/intents.luau index 788ef94..ef20aef 100644 --- a/lib/intents.luau +++ b/lib/intents.luau @@ -2,9 +2,10 @@ local timefmt = require("./timefmt") -- lib/intents.luau : host side of the window -> host protocol (EN §2.3 + plan overrides 8-9). -- Files `intents/--.json`, applied in name order inside a time budget and removed --- after applying. 15 allowlisted kinds (const.INTENT_KINDS); everything else (create/update/delete/ --- settings included) is dropped at once. `carly_create` makes a job directly and answers through --- `replies/.json`. +-- after applying. 16 allowlisted kinds (const.INTENT_KINDS); everything else (create/update/delete/ +-- settings included) is dropped at once. `carly_create` and `script_create` make a job directly and +-- answer through `replies/.json`. `script_create` is a public contract (README "From a script"): +-- add fields only as optional, never rename or remove one. local conditions = require("./conditions") local const = require("./const") local jobs = require("./jobs") @@ -54,7 +55,7 @@ local APPROVAL_LABEL: { [string]: string } = { -- Kinds with an `expires` stamp (unix seconds) are dropped once it has passed: the window told its -- caller they failed, so applying them later would duplicate or surprise. -local EXPIRING: { [string]: boolean } = { carly_create = true, run_now = true, check_conditions = true } +local EXPIRING: { [string]: boolean } = { carly_create = true, script_create = true, run_now = true, check_conditions = true } local function home(): string return ((tern :: any).getenv("HOME") :: string?) or "" @@ -70,6 +71,13 @@ local function str(v: any, max: number): string? return v end +local function reply_id(v: any): string? + if type(v) == "string" and #v == 12 and v:match("^[a-z0-9]+$") then + return v + end + return nil +end + -- ---------- replies ---------- local function write_reply(id: string, tbl: { [string]: any }) @@ -93,7 +101,7 @@ local function first_error(errs: { [string]: string }): string return "Couldn't create the job." end --- ---------- carly_create ---------- +-- ---------- carly_create / script_create ---------- -- name derived from the prompt: first 5 words, lowercased, joined by "-", ≤ 40 chars, unique. local function derive_name(prompt: string): string @@ -123,42 +131,42 @@ local function derive_name(prompt: string): string return name end -local function carly_create(p: { [string]: any }, h: Handlers) - local reply = p.reply - if type(reply) ~= "string" or not reply:match("^[a-z0-9]+$") or #reply ~= 12 then - log_warn("intents: carly_create without a valid reply id") - return +-- Who asked for a job: the stored creator, a script's own name, and how the notification names it. +type Origin = { created_by: string, source: string?, who: string } + +-- The creation both kinds share. f: name, prompt, when, folder, role (strings, may be ""), only_when, +-- quiet_ok (raw request values). Always answers `reply`, now or once the folder check returns. +local function create_job(reply: string, f: { [string]: any }, origin: Origin, h: Handlers) + local function failed(err: any) + log_warn("intents: " .. origin.created_by .. "_create failed", tostring(err)) + pcall(reply_error, reply, "Agent Scheduler couldn't create the job.") end local ok, err = pcall(function() - local prompt = type(p.prompt) == "string" and p.prompt or "" - if #prompt > const.CARLY_PROMPT_MAX then - return reply_error(reply, "That prompt is too long for Carly. Use the manager.") - end - local name = str(p.name, 200) or "" - name = name:gsub("^%s+", ""):gsub("%s+$", "") + local prompt = f.prompt :: string + local name = (f.name :: string):gsub("^%s+", ""):gsub("%s+$", "") if name == "" then name = derive_name(prompt) end - local role = (str(p.role, 100) or ""):gsub("^%s+", ""):gsub("%s+$", ""):gsub("^@", "") + local role = (f.role :: string):gsub("^%s+", ""):gsub("%s+$", ""):gsub("^@", "") if role == "" then role = "default" end - local folder = str(p.folder, 1100) or "" - local when = str(p.when, 200) or "" + local folder = f.folder :: string + local when = f.when :: string local now = os.time() local input: { [string]: any } = { name = name, prompt = prompt, when = when, role = role, cwd = folder } - if p.only_when ~= nil then - local ow, owerr = conditions.from_fields(p.only_when) + if f.only_when ~= nil then + local ow, owerr = conditions.from_fields(f.only_when) if ow == nil then return reply_error(reply, owerr or "only_when must be a table of fields.") end input.only_when = ow end - if p.quiet_ok ~= nil then - if type(p.quiet_ok) ~= "boolean" then + if f.quiet_ok ~= nil then + if type(f.quiet_ok) ~= "boolean" then return reply_error(reply, "quiet_ok must be true or false.") end - input.quiet_ok = p.quiet_ok + input.quiet_ok = f.quiet_ok end local vok, errs, norm = validate.job(input, { jobs = jobs.list(), @@ -194,7 +202,7 @@ local function carly_create(p: { [string]: any }, h: Handlers) return reply_error(reply, string.format("No role @%s here. Roles: %s", role, table.concat(list, ", "))) end end - local job, cerrs = jobs.create(input, prompt, "carly", os.time()) + local job, cerrs = jobs.create(input, prompt, origin.created_by, os.time(), origin.source) if job == nil then return reply_error(reply, first_error(cerrs or {})) end @@ -212,23 +220,24 @@ local function carly_create(p: { [string]: any }, h: Handlers) local folder_label = validate.tilde(job.cwd, home()) local approval = APPROVAL_LABEL[tostring(job.approval)] or tostring(job.approval) -- a banner works without any window open; the job is live and may run commands - pcall(notify.plain, "Agent Scheduler", string.format("Carly scheduled %s · %s · %s", tostring(job.name), approval, folder_label)) + pcall(notify.plain, "Agent Scheduler", string.format("%s scheduled %s · %s · %s", origin.who, tostring(job.name), approval, folder_label)) write_reply(reply, { ok = true, job_id = job.id, name = job.name, when = jobs.describe(job), next = nxt, + next_at = if type(st.next_run) == "number" then st.next_run else nil, folder = folder_label, role = "@" .. tostring(job.role), approval = approval, only_when = if #conditions.describe(job.conditions) > 0 then conditions.describe(job.conditions) else "always", quiet_ok = job.quiet_ok == true, + source = origin.source, }) end) if not cok then - log_warn("intents: carly_create failed", tostring(cerr)) - pcall(reply_error, reply, "Agent Scheduler couldn't create the job.") + failed(cerr) end end) end) @@ -237,9 +246,91 @@ local function carly_create(p: { [string]: any }, h: Handlers) end end) if not ok then - log_warn("intents: carly_create failed", tostring(err)) + failed(err) + end +end + +-- Carly's internal message: lenient (over-long text is cut), with Carly's own prompt cap. +local function carly_create(p: { [string]: any }, h: Handlers) + local reply = reply_id(p.reply) + if reply == nil then + log_warn("intents: carly_create without a valid reply id") + return + end + local prompt = type(p.prompt) == "string" and p.prompt or "" + if #prompt > const.CARLY_PROMPT_MAX then + pcall(reply_error, reply, "That prompt is too long for Carly. Use the manager.") + return + end + create_job(reply, { + name = str(p.name, 200) or "", + prompt = prompt, + when = str(p.when, 200) or "", + folder = str(p.folder, 1100) or "", + role = str(p.role, 100) or "", + only_when = p.only_when, + quiet_ok = p.quiet_ok, + }, { created_by = "carly", who = "Carly" }, h) +end + +-- The public request (README "From a script"): strict, so a misspelt or unsupported field (approval, +-- cwd, …) fails loudly instead of quietly making a job the caller didn't ask for. +local SCRIPT_FIELDS: { [string]: boolean } = { + format = true, kind = true, reply = true, expires = true, source = true, + name = true, prompt = true, when = true, folder = true, role = true, quiet_ok = true, only_when = true, +} +local SCRIPT_TEXT = { "name", "prompt", "when", "folder", "role", "source" } + +local function script_problem(p: { [string]: any }): string? + local keys: { string } = {} + for k in pairs(p) do + table.insert(keys, tostring(k)) + end + table.sort(keys) + for _, k in ipairs(keys) do + if not SCRIPT_FIELDS[k] then + return string.format("Unknown field “%s”.", k) + end + end + for _, k in ipairs(SCRIPT_TEXT) do + if p[k] ~= nil and type(p[k]) ~= "string" then + return k .. " must be text." + end + end + if p.expires ~= nil and type(p.expires) ~= "number" then + return "expires must be a number (unix seconds)." + end + if p.source ~= nil and validate.source(p.source) == nil then + return "source: use 1 to 24 letters, digits, - or _." + end + return nil +end + +local function script_create(p: { [string]: any }, h: Handlers) + local reply = reply_id(p.reply) + if reply == nil then + log_warn("intents: script_create without a valid reply id") + return + end + local ok, problem = pcall(script_problem, p) + if not ok then + log_warn("intents: script_create failed", tostring(problem)) pcall(reply_error, reply, "Agent Scheduler couldn't create the job.") + return + elseif problem ~= nil then + pcall(reply_error, reply, problem) + return end + local source: string? = p.source + create_job(reply, { + name = p.name or "", + prompt = p.prompt or "", + when = p.when or "", + folder = p.folder or "", + role = p.role or "", + only_when = p.only_when, + quiet_ok = p.quiet_ok, + }, { created_by = "script", source = source, who = source or "A script" }, h) end -- ---------- the other kinds ---------- @@ -347,9 +438,11 @@ local function apply(kind: string, p: { [string]: any }, h: Handlers) h.session_ended() elseif kind == "carly_create" then carly_create(p, h) + elseif kind == "script_create" then + script_create(p, h) elseif kind == "check_conditions" then - local reply = p.reply - if type(reply) ~= "string" or not reply:match("^[a-z0-9]+$") or #reply ~= 12 then + local reply = reply_id(p.reply) + if reply == nil then log_warn("intents: check_conditions without a valid reply id") return end @@ -413,8 +506,8 @@ function intents.drain(deadline_ms: number, h: Handlers): number log_warn("intents: dropping intent", name, tostring(kind)) elseif EXPIRING[kind] and type(p.expires) == "number" and p.expires < os.time() then log_warn("intents: dropping expired intent", name, kind) - local reply = p.reply - if kind == "carly_create" and type(reply) == "string" and reply:match("^[a-z0-9]+$") and #reply == 12 then + local reply = reply_id(p.reply) + if (kind == "carly_create" or kind == "script_create") and reply ~= nil then pcall(reply_error, reply, "Timed out before Agent Scheduler could create it.") end else diff --git a/lib/jobs.luau b/lib/jobs.luau index 445e680..132892e 100644 --- a/lib/jobs.luau +++ b/lib/jobs.luau @@ -200,7 +200,8 @@ local function materialize(job: Job, d: { [string]: any }, now: number) if job.unattended_note == nil then job.unattended_note = true end if job.enabled == nil then job.enabled = true end if job.allow_home == nil then job.allow_home = false end - if job.created_by ~= "carly" then job.created_by = "user" end + if job.created_by ~= "carly" and job.created_by ~= "script" then job.created_by = "user" end + job.created_source = if job.created_by == "script" then validate.source(job.created_source) else nil if job.created_at == nil then job.created_at = now end if job.updated_at == nil then job.updated_at = now end if job.tz == nil then job.tz = tz_record() end @@ -615,7 +616,7 @@ local function save_both(): boolean return ok end -function jobs.create(input: validate.JobInput, prompt: string, created_by: string, now: number): (Job?, { [string]: string }?) +function jobs.create(input: validate.JobInput, prompt: string, created_by: string, now: number, source: string?): (Job?, { [string]: string }?) if data_blocked() then return nil, { name = SAVE_FAILED_COPY } end @@ -634,7 +635,8 @@ function jobs.create(input: validate.JobInput, prompt: string, created_by: strin local id = ids.job_id(id_taken) local job: Job = norm job.id = id - job.created_by = created_by == "carly" and "carly" or "user" + job.created_by = if created_by == "carly" or created_by == "script" then created_by else "user" + job.created_source = if job.created_by == "script" then source else nil job.created_at = now job.updated_at = now materialize(job, settings_tbl.defaults, now) diff --git a/lib/mgr_common.luau b/lib/mgr_common.luau index 008fa21..7241568 100644 --- a/lib/mgr_common.luau +++ b/lib/mgr_common.luau @@ -209,6 +209,20 @@ function C.short_label(label: string): string return SHORT_LABELS[label] or label end +-- Who made a job, for list and live rows; nil for the user's own. wide=false gives a one-glyph mark. +function C.creator_mark(job: any, wide: boolean): string? + if job.created_by == "carly" then + return if wide then "by Carly" else "✦" + elseif job.created_by == "script" then + if not wide then + return "⚙" + end + local src = job.created_source + return "by " .. (if type(src) == "string" and src ~= "" then src else "script") + end + return nil +end + function C.text(spans: Spans, key: string): Node return C.with(ui.text(spans), { key = key }) end diff --git a/lib/mgr_list.luau b/lib/mgr_list.luau index e92b5ed..35d2570 100644 --- a/lib/mgr_list.luau +++ b/lib/mgr_list.luau @@ -298,15 +298,16 @@ local function clip(text: string, max: number): string return string.sub(first, 1, (utf8.offset(first, max) or max + 1) - 1) .. "…" end --- `by Carly` is the only marker of a job Carly created, so it stays at every width: the role chip goes first, and --- below tier 3 the mark shrinks to a glyph. +-- The creator mark (`by Carly`, `by `, `by script`) is the only sign a job wasn't made in the manager, so it +-- stays at every width: the role chip goes first, and below tier 3 the mark shrinks to a glyph. local function job_label(job: any, tier: number): Spans local spans: { Span | string } = { ui.span(job.name, "strong") } if tier >= 3 then table.insert(spans, ui.span(" @" .. tostring(job.role), "muted")) end - if job.created_by == "carly" then - table.insert(spans, ui.span(if tier >= 3 then " by Carly" else " ✦", "muted")) + local mark = C.creator_mark(job, tier >= 3) + if mark ~= nil then + table.insert(spans, ui.span(" " .. mark, "muted")) end return spans end diff --git a/lib/mgr_live.luau b/lib/mgr_live.luau index af0e14f..06e32f5 100644 --- a/lib/mgr_live.luau +++ b/lib/mgr_live.luau @@ -82,8 +82,9 @@ function M.agent_row(row: Row, now: number, tier: number, selected: boolean): No if tier >= 3 then table.insert(badges, { text = "@" .. tostring(job.role) }) end - if job.created_by == "carly" then - table.insert(badges, { text = if tier >= 3 then "by Carly" else "✦" }) + local mark = C.creator_mark(job, tier >= 3) + if mark ~= nil then + table.insert(badges, { text = mark }) end local stats: { [string]: any } = { age = ms_since(now, since) } diff --git a/lib/snapshot.luau b/lib/snapshot.luau index fdc71d5..e2615ef 100644 --- a/lib/snapshot.luau +++ b/lib/snapshot.luau @@ -73,6 +73,7 @@ local function job_entries(paused_all: boolean, home: string): ({ any }, { id: s paused_reason = (not enabled) and st.paused_reason or nil, only_when = if type(j.conditions) == "table" and #j.conditions > 0 then conditions.describe(j.conditions) else nil, created_by = j.created_by or "user", + created_source = j.created_source, last = last_of(st), }) if not paused_all and next_run ~= nil and (nxt == nil or next_run < nxt.at) then diff --git a/lib/status.luau b/lib/status.luau index 187a2fc..d90b3c4 100644 --- a/lib/status.luau +++ b/lib/status.luau @@ -239,7 +239,7 @@ type Memo = { needs_toasted: { [string]: boolean }, had_history: boolean, setup_ok: boolean, - carly_toasted: { [string]: boolean }, + created_toasted: { [string]: boolean }, } local memo: Memo = { @@ -250,7 +250,7 @@ local memo: Memo = { needs_toasted = {}, had_history = false, setup_ok = true, - carly_toasted = {}, + created_toasted = {}, } local function clip(s: string, max: number): string @@ -335,11 +335,14 @@ function status.diff(snap: { [string]: any }, hot: { [string]: any }?, now: numb local id = tostring(j.id) local before = memo.jobs[id] if before == nil then - if j.created_by == "carly" and not memo.carly_toasted[id] then - memo.carly_toasted[id] = true + if (j.created_by == "carly" or j.created_by == "script") and not memo.created_toasted[id] then + memo.created_toasted[id] = true + local who = if j.created_by == "carly" then "Carly" + elseif type(j.created_source) == "string" and j.created_source ~= "" then j.created_source + else "A script" table.insert(out, { level = "success", - text = "Carly scheduled " .. tostring(j.name), + text = who .. " scheduled " .. tostring(j.name), sub = tostring(j.when) .. " · next " .. next_text(j.next_run), }) end @@ -383,7 +386,7 @@ function status.reset() needs_toasted = {}, had_history = false, setup_ok = true, - carly_toasted = {}, + created_toasted = {}, } view = { seg = nil, stalled = false, stall_age = 0, setup_bad = false, needs = {}, context = nil } end diff --git a/lib/validate.luau b/lib/validate.luau index 6002c92..fe7736e 100644 --- a/lib/validate.luau +++ b/lib/validate.luau @@ -54,6 +54,14 @@ function validate.slug(name: string): string return s end +-- A script_create `source`: 1..24 letters, digits, - or _; else nil. +function validate.source(v: any): string? + if type(v) == "string" and #v >= 1 and #v <= 24 and v:match("^[%w_%-]+$") then + return v + end + return nil +end + -- LA §2.3: ' " \ $ ` ! and control characters (newline included). function validate.unsafe_path(p: string): boolean return p:find("['\"\\%$`!%c]") ~= nil diff --git a/test/golden/runner_intents.txt b/test/golden/runner_intents.txt index 5187484..9dc5144 100644 --- a/test/golden/runner_intents.txt +++ b/test/golden/runner_intents.txt @@ -8,5 +8,10 @@ PASS carly_create name derivation PASS carly_create folder, prompt cap, schedule errors PASS carly_create quiet_ok PASS carly_create cached role check +PASS script_create success (source, default approval, snapshot, notification) +PASS script_create without source +PASS script_create refuses unknown and mistyped fields +PASS script_create expired +PASS carly_create still marked by Carly PASS replies pruned PASS no errors diff --git a/test/golden/runner_window.txt b/test/golden/runner_window.txt index 36dac86..dad855c 100644 --- a/test/golden/runner_window.txt +++ b/test/golden/runner_window.txt @@ -2,4 +2,5 @@ PASS agent_state sends the run's new state at once PASS agent_state ignores exits and other panes PASS session_ended sends one intent only while runs are in flight PASS paused hooks show in the status line until all resume +PASS creator toasts name Carly, the source, or a script PASS no errors diff --git a/test/runner_intents.luau b/test/runner_intents.luau index 3c0dd02..39b9110 100644 --- a/test/runner_intents.luau +++ b/test/runner_intents.luau @@ -1,4 +1,4 @@ --- The allowlist (15 kinds), dropped kinds, retry of undecodable files, carly_create and its replies. +-- The allowlist (16 kinds), dropped kinds, retry of undecodable files, carly_create, script_create and their replies. local jobs, runner, intents = __mods.jobs, __mods.runner, __mods.intents fake.dirs["/home/u/proj"] = true @@ -143,6 +143,74 @@ local r9 = carly("iiiiiiiiiiii", { name = "badrole", prompt = "p", when = "daily assert(r9 and r9.ok == false and r9.error == "No role @nope here. Roles: @default, @smol, @task, @plan, @slow, @commit, @advisor, @tiny, @memory, @vision", "role copy: " .. tostring(r9 and r9.error)) print("PASS carly_create cached role check") +-- 5. script_create: the public contract +local function script(reply, fields) + local p = { format = 1, kind = "script_create", reply = reply } + for k, v in pairs(fields) do + p[k] = v + end + send(p) + settle() + return fake.reply(reply) +end +local function last_notice() + local osa = fake.calls_of("osascript") + local argv = osa[#osa] + return argv and argv[#argv - 1] +end +local function snap_entry(id) + for _, j in ipairs(tern.json.decode(fake.read("/d/snapshot.json")).jobs) do + if j.id == id then + return j + end + end + return nil +end + +local s1 = script("sssssssssss1", { source = "ci-bot", name = "nightly-ci", prompt = "p", when = "daily 09:00", folder = "~/proj" }) +assert(s1 and s1.ok == true, "script_create ok: " .. tern.json.encode(s1)) +assert(s1.source == "ci-bot" and type(s1.next_at) == "number" and s1.approval == "Hands-off", "reply fields: " .. tern.json.encode(s1)) +local sj = jobs.get(s1.job_id) +assert(sj and sj.created_by == "script" and sj.created_source == "ci-bot" and sj.approval == "yolo", "job fields") +local se = snap_entry(sj.id) +assert(se and se.created_by == "script" and se.created_source == "ci-bot", "snapshot carries the creator") +assert(last_notice() == "ci-bot scheduled nightly-ci \u{00B7} Hands-off \u{00B7} ~/proj", "notification: " .. tostring(last_notice())) +print("PASS script_create success (source, default approval, snapshot, notification)") + +local s2 = script("sssssssssss2", { name = "plain-script", prompt = "p", when = "daily 10:00", folder = "/home/u/proj" }) +assert(s2 and s2.ok == true and s2.source == nil, "no source in reply: " .. tern.json.encode(s2)) +local sj2 = jobs.get(s2.job_id) +assert(sj2.created_by == "script" and sj2.created_source == nil, "script job without source") +assert(tostring(last_notice()):sub(1, #"A script scheduled plain-script") == "A script scheduled plain-script", "notification: " .. tostring(last_notice())) +print("PASS script_create without source") + +local count_s = #jobs.list() +local bad = { + { "sssssssssss3", { approval = "always_ask", name = "x1", prompt = "p", when = "daily 09:00", folder = "/home/u/proj" }, "Unknown field \u{201C}approval\u{201D}." }, + { "sssssssssss4", { name = "x2", prompt = "p", when = "daily 09:00", cwd = "/home/u/proj" }, "Unknown field \u{201C}cwd\u{201D}." }, + { "sssssssssss5", { name = 5, prompt = "p", when = "daily 09:00", folder = "/home/u/proj" }, "name must be text." }, + { "sssssssssss6", { source = "ci bot", name = "x3", prompt = "p", when = "daily 09:00", folder = "/home/u/proj" }, "source: use 1 to 24 letters, digits, - or _." }, + { "sssssssssss7", { expires = "soon", name = "x4", prompt = "p", when = "daily 09:00", folder = "/home/u/proj" }, "expires must be a number (unix seconds)." }, +} +for _, c in ipairs(bad) do + local r = script(c[1], c[2]) + assert(r and r.ok == false and r.error == c[3], "refused " .. c[1] .. ": " .. tern.json.encode(r)) +end +assert(#jobs.list() == count_s, "no job made from a refused request") +print("PASS script_create refuses unknown and mistyped fields") + +local s8 = script("sssssssssss8", { expires = os.time() - 1, name = "late", prompt = "p", when = "daily 09:00", folder = "/home/u/proj" }) +assert(s8 and s8.ok == false and s8.error == "Timed out before Agent Scheduler could create it.", "expired copy: " .. tern.json.encode(s8)) +assert(#jobs.list() == count_s, "no job from an expired request") +print("PASS script_create expired") + +local rc = carly("llllllllllll", { name = "carly-again", prompt = "p", when = "daily 11:00", folder = "/home/u/proj" }) +assert(rc and rc.ok == true and rc.source == nil, "carly ok: " .. tern.json.encode(rc)) +local cj = jobs.get(rc.job_id) +assert(cj.created_by == "carly" and cj.created_source == nil, "carly job marked by Carly") +assert(tostring(last_notice()):sub(1, #"Carly scheduled ") == "Carly scheduled ", "carly notification: " .. tostring(last_notice())) +print("PASS carly_create still marked by Carly") + -- replies are pruned after REPLY_TTL_S assert(#tern.fs.list("/d/replies") > 0, "replies exist") intents.prune(os.time()) diff --git a/test/runner_window.luau b/test/runner_window.luau index 4729bd4..3da5474 100644 --- a/test/runner_window.luau +++ b/test/runner_window.luau @@ -79,5 +79,24 @@ seg = status.view().seg assert(seg == nil or seg.text ~= PAUSED, "cleared once all resume") print("PASS paused hooks show in the status line until all resume") +status.reset() +status.diff({ jobs = {} }, nil, os.time()) +local made = { + jobs = { + { id = "j_a", name = "n1", when = "Daily at 09:00", created_by = "script", created_source = "ci-bot" }, + { id = "j_b", name = "n2", when = "Daily", created_by = "script" }, + { id = "j_c", name = "n3", when = "Daily", created_by = "carly" }, + }, +} +local texts = {} +for _, t in status.diff(made, nil, os.time()) do + texts[t.text] = true +end +assert(texts["ci-bot scheduled n1"] and texts["A script scheduled n2"] and texts["Carly scheduled n3"], "creator toasts") +for _, t in status.diff(made, nil, os.time()) do + assert(not t.text:find("scheduled", 1, true), "toasted once: " .. t.text) +end +print("PASS creator toasts name Carly, the source, or a script") + assert(#fake.errors == 0, "no error logs: " .. table.concat(fake.errors, "; ")) print("PASS no errors")