Add turnover, project, retention, and year comparison pages from the supplied workbook, protected by named admin access. Include the local chart gallery, grouped monthly hover, smooth comparison toggle, and monthly income minus cost series.
Require named PocketBase sign-in in every environment and remove the shared PIN bypass. Update access documentation and business-route test fixtures.
Add per-site CSV and PDF matrix reports, editable sick-note date ranges, and weekend calendar styling. Preserve verified duplicate uploads for audit while excluding their entries from hours and costs, and prevent repeat files and overlapping daily imports.
Remove repeated Plant, Financial and Workforce shortcut cards. Add site-scoped Plant and Financial sidebar attention status with automatic refresh.
Include accumulated delivery processing, purchase order recovery, supplier reconciliation, plant data and user management changes and audit records.
Fresh duplicate check before posting, dismiss route sets stage, free accessory
lines no longer crash promotion, readiness treats only posted notes as terminal,
document-reference/usable-PO helpers, PO delivery reconciliation API + docs and
audit register.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Tick path
- Bump STALE_CLAIM_MS from 10 to 30 minutes. A 29-source OCR batch
hit ~29 min and was being reclaimed mid-run by the 10-minute cap,
leaving the batch in inbox with last_error='reclaimed after a
stalled run' even though nothing was stalled. MAX_ATTEMPTS still
bounds a truly stuck batch.
- After each dn_batch_pages create, the staged runner bumps
dn_batches.page_count in the same lease-fenced batch. Final
assembly write at run-staged.ts:223 still sets the authoritative
value, so any drift from a reclaim-then-restart cycle is corrected.
Inbox tiles now show live progress instead of 0 pages for the
entire reading window.
PocketBase batch transport
- sendRecordBatch chunks across pb.createBatch() calls at the
server 50-request cap. A 71-candidate assembly sent as one
request was returning Invalid batch request data. and 500ing —
the assembly route caught it and surfaced as the generic Grouping
could not be saved. 73 mutations now split into 50 + 23 and land.
Assembly save UX
- The dismiss dialog now renders directly under the open-pages alert
instead of at the bottom of the section (which was hidden behind 71
document tiles on big batches). Clicking Dismiss page opens the
reason input where the user is looking.
- saveGrouping surfaces the server-side error code
(stale_revision / posted_candidate / dismissed_candidate /
assembly_in_progress / invalid_page_coverage) instead of a generic
Try again. On success, the page now redirects to /inbox so the
documents land in their columns.
- The Technical details disclosure is gone from the grouping screen.
Open pages already surface their reason in the alert above; the
duplicate disclosure just competed with the decision UI.
Assembly route correctness
- After a successful manual save the route now writes
stage=complete, status=needs_attention, notes_detected,
processing_completed_at and clears claimed_at/last_error. The
runner advances stage on its own runs but a manual save was
never followed by a runner pass — without this the batch stayed
in Check page grouping forever even though assembly was done.
- For existing candidates the route only updates grouping metadata
(pages, page_from, page_to, assembly_revision, status, stage,
checks). OCR-derived fields (doc_number, supplier_name_raw,
items, raw_text) are preserved on the row — the runner only
re-fills those for batches in status=inbox, and post-save the
batch moves to needs_attention and never reaches the runner
again. New candidates still get a createdCandidateFields row
with the OCR fields blank, ready for the runner or operator
entry.
- A Re-run batch button was added to the document detail header
so the operator can refill the wiped OCR data (or re-resolve
checks after a manual override) without first navigating to the
batch detail page.
Customer identity check
- A Skip this check toggle on the document detail page records
manual_overrides.skip_customer_identity. run-staged reads the
override and turns the customer_identity check into passed=null
(skip) instead of passed=false (fail), so OCR false-positives
on the customer VAT no longer block posting while still
requiring an explicit operator decision.
- The PATCH route accepts skip_customer_identity as an editable
field so the toggle saves through the standard note route.
Tests
- 180 files / 1767 tests pass; typecheck clean.
- Ask's supplier loader didn't pass date_received, so supplier_balances
and the supplier_balance dataset crashed
- supplier_balances takes a period (thisMonth, thisWeek, month1-3) and
returns what was received from each supplier in it (payable)
- PocketBase's space-separated dates dropped deliveries on the 1st from
period filters, including the Suppliers page's Payable KPI
- The PDF route falls back to the answer text when a saved report has
no sections (older format), instead of a 500
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GET /api/ask/messages/[id]/pdf builds a PDF for one stored assistant
row: its structured make_pdf_report document when `parsed.pdf` is set,
otherwise its own markdown (headings/paragraphs/lists/GFM tables, with
[[chart:id]]/[[image:id]] tokens resolved against that message's own
stored charts and any referenced generated-image rows). 404s for a
missing message, a non-assistant row, or a thread owned by someone
else — same "not found, not forbidden" reasoning as the existing
thread routes, since there are no logins yet. Returns
application/pdf with Content-Disposition: attachment; filename="ask-<slug>-<date>.pdf".
The chat stream's "done" event now carries the persisted assistant
row's own id (messageId), which the browser needs to ask this route
for a PDF — see the next commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ask_threads/ask_messages/ask_log shipped with created/updated typed as
plain `date` fields, which PocketBase never populates — every row's
created has been empty since. pb-add-ask-collections.py now emits
autodate fields (onCreate, plus onUpdate for updated) and migrates the
three live collections in place under --apply, re-adding
idx_ask_messages_thread_created if PocketBase drops it with the field.
--backfill (apply-only) just reports affected row counts: PocketBase
can only set an autodate field to *now*, never a historical value, so
there's nothing safe to backfill.
Since old rows keep an empty created either way, the read side sorts
ask_messages by `created,id` instead of `created` alone, so tied
(all-empty) rows land in a stable, deterministic order rather than
whatever order PocketBase happens to return them in.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Follow-up to 7773ac8: those tests build a bare new Request(), which
(unlike a real HTTP request) has no Host header unless one is set
explicitly. isSameOrigin now checks Host, so all three routes' tests
started failing every non-cross-site case. Default a Host header
derived from the test's own ORIGIN, and set it explicitly (mismatched
against Origin) in the cross-site case so that test still exercises a
real mismatch rather than a merely-missing header.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Added mid-plan (docs/superpowers/plans/2026-09-26-ask-agent-actions.md,
new Task 9b — image generation from Task 9 is untouched): the user can
ask for any custom report and get a finished PDF, e.g. "give me a PDF
on fuel at The Hills for September", not just a manual export of
whatever is on screen (Task 8).
make_pdf_report({ title, subtitle?, filename? }) is the model's own
"this answer is a finished report" signal, called last once it has
already built the report (headings, narrative, KPI tables quoting tool
display strings, charts via make_chart). extractPdfMeta splits the
meta out the same way extractCharts/extractActionCard already do: the
model gets an ack, the browser gets the full meta via a new `event:
pdf`. The assistant's ask_messages row stores it in the existing
`parsed` json field, so reopening the thread still shows the report
cover and Download button — no schema change.
chat-view.tsx renders a report cover (wordmark, title, subtitle, date,
"Prepared by Ask for {name}") and a prominent "Download PDF · {title}"
button reusing Task 8's answerToPdf (same page-slicing, so a chart is
never cut across pages), and auto-downloads once per turn via
nextPdfTurnToDownload — a pure decision function, unit-tested directly
since this codebase's component tests use renderToStaticMarkup rather
than interactive DOM testing.
Live check skipped: needs a thread, which needs ask_threads (not yet
applied). Covered by unit tests (tool meta, the route's pdf event and
persistence, and the once-per-turn auto-download decision) instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
file_change_request (tools-actions.ts) logs an ask_log row
(type "request", status "open") for a change to the app itself — a new
page, column, button or report layout — distinct from propose_changes,
which changes data; the prompt now routes between the two.
list_change_requests (tools.ts, read-only) lists them, which the
existing MCP server picks up automatically since it iterates the whole
tools array. /dashboard/change-requests lists and re-statuses them
(open/planned/done/declined) via new GET/PATCH routes under
/api/ask/change-requests, linked from the sidebar under Ask.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
src/lib/agent/images.ts's generateImage posts MiniMax image-01's
documented request shape (verified against the installed mmx-cli SDK:
POST {baseUrl}/v1/image_generation with
{model, prompt, aspect_ratio, n, response_format}) and reads
data.image_base64[0]. A base_resp.status_code of 1028/1030/2061 (the
same codes the CLI itself maps to a "needs Plus plan" hint for this
endpoint) surfaces as a clear, non-retried error rather than a generic
failure. generate_image (tools-actions.ts) stores the result as its own
append-only ask_messages row (kind: "image") and returns its url.
extractGeneratedImages splits a tool result the way extractCharts
already splits chart numbers — the browser gets the full image, the
model keeps only imagesAvailable: [{id}] so it can place
[[image:<id>]] without ever seeing pixels or a URL. answer-parts.ts's
splitAnswer now takes an imageIds set alongside chartIds (existing
chart-only callers keep working via a default empty set), and
AnswerMarkdown renders the image inline.
The pb-files proxy (src/app/api/pb-files/.../route.ts) now also serves
ask_messages (previously only delivery_notes/purchase_orders): since
that collection's rules are all null by design (Task 1), this one
collection mints a short-lived admin file token server-side rather
than exposing the underlying PB rule.
Live check skipped (both the chat flow and MiniMax call): reaching
generate_image needs a thread, which needs ask_threads (not yet
applied). Covered by unit tests against the documented request/response
shape and error codes instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The gateway (src/lib/agent/gateway.ts) is now the one seam every write
goes through: authorize() (NEVER_WRITABLE + dn_batches lock_*/stage),
planOps (schema validation via schema-cache.ts's new validateOp,
before-snapshots, $ref cross-checks, relation-id existence, the
sites/employees duplicate rule, capped at 500 ops), createPendingAction,
applyAction and undoAction. propose_changes is a registered tool;
apply/reject/undo are confirm-card routes under
/api/agent/actions/[id]/, same-origin only.
/api/chat now streams a full action card (`event: action`) while the
model itself only ever sees {actionId, status, problems} — the same
split extractCharts already does for chart numbers (extractActionCard).
The next user turn gets the outcome of the prior turn's action(s)
prepended to what the model reads (ChatEntry has no system role, so
this is the pragmatic equivalent of a system note). chat-view.tsx
renders action-card.tsx per assistant turn, hydrating from
GET /api/agent/actions/[id] when a thread reopens.
Deviations, both noted for the smallest-sensible-adjustment reason:
- Batches run as sequential individual PocketBase calls, not
pb.createBatch() — that's what makes $ref resolution exact rather
than dependent on the batch API's own (version-sensitive) request-
chaining syntax.
- Re-applying a "failed" action isn't specially deduped against ops
that already partially succeeded; only the single-attempt path is
implemented in this session.
Live check skipped: ask_threads/ask_messages/ask_log still don't exist
in the target PocketBase (Task 1's --apply is the user's own step).
Covered by mocked unit tests instead — 17 gateway tests plus the
confirm-card routes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds src/lib/agent/attachments.ts (parseAttachment/previewForModel/
summarise for xlsx, xls, csv, pdf — text-layer or scanned, via
pdftotext — image and plain text) with fixtures under
src/lib/agent/__fixtures__/, POST /api/chat/attachments (multipart
upload into an append-only ask_messages row, rasterising a scanned
PDF's first pages so they ride along as vision images the same way a
photographed slip does), and the read_attachment / send_to_po_pipeline
tools in tools-actions.ts. send_to_po_pipeline mirrors
/api/purchase-orders/upload's own hash-dedupe-then-create logic
directly against PocketBase rather than a same-process HTTP call (no
reliable base URL to call itself with from a server-side tool handler).
chat-view.tsx gained a second attach control (FileUp icon) alongside
the existing PO-upload paperclip, wired to the new route; pending
attachment chips ride along on the next message the same way pending
photos already do.
Deviation: send_to_po_pipeline takes { id, site } (the plan's { id }
alone can't resolve which site's purchase_orders row to create,
since /api/purchase-orders/upload always required one).
Live browser check skipped: ask_messages doesn't exist yet in the
target PocketBase (pending the user's --apply of Task 1's schema).
Covered by mocked unit tests and real fixture files instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds src/lib/agent/memory.ts (remember/forget/listMemories, dedupe by
normalised text, formatMemoriesForPrompt) and wires it in: a
"## What you remember" system-prompt section, the remember/forget/
list_memories tools (src/lib/agent/tools-actions.ts, a per-request
factory since these need the actor unlike the static read-only tool
set), a REST view for the UI (/api/ask/memories), and a Memory drawer
in chat-view.tsx (Mine / Shared with everyone, add, delete).
Adjusted src/lib/agent/read-only.test.ts: its blanket "no mutation
calls under src/lib/agent" contract now allowlists the specific write
seams the plan designates (memory.ts here; tools-actions.ts, gateway.ts
and images.ts to follow) instead of forbidding every file, since
memories/requests are specified to bypass the gateway and write
directly.
Live browser check skipped: ask_log doesn't exist yet in the target
PocketBase (pending the user's --apply of Task 1's schema). Covered by
mocked unit tests instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds the "Who's using Ask?" picker (GET /api/ask/users), actor
resolution via x-ask-user (src/lib/agent/context.ts), and thread
persistence (src/lib/chat/threads.ts, /api/chat/threads routes).
/api/chat now accepts { threadId?, message, display?, images? } and
persists each turn as its own append-only ask_messages row; the old
{ history } body still works for one release. chat-view.tsx gained the
picker, a thread sidebar (new/select/rename/archive), and ?thread=<id>
in the URL.
Live browser check skipped: ask_threads/ask_messages/ask_log don't
exist yet in the target PocketBase (Task 1's schema is dry-run only,
pending the user's --apply). Covered by mocked unit tests instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Overview/Plant tiles and pages share one vehicle bucket rule (blank unit_type = fleet)
- Plant landing equipment figures were always 0; hour diffs now reject 0 baselines and >24h/day jumps
- km/L limits on plant (and L/h on vehicles) report unit-mismatch instead of false alerts
- formatPercent/formatDecimal replace display toFixed (en-ZA)
- POST /api/vehicles/[id]/merge + Merge duplicate dialog (dry run first)
- Attention links go to equipment vs vehicles by unit type; PO upload view link fixed
- Conditional hook fixed in DN document view; ESLint flat config (next lint removed in 16)
- Docs: current modules/routes/env vars; login + Ask reports plans
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Introduced a new secret key for receipt correction in the environment configuration. Enhanced the API for handling item edits in delivery notes, allowing for more granular updates and preserving existing manual overrides. Updated the document detail view to display additional supplier and customer information, and integrated a toggle for skipping customer identity checks. Improved validation for item entries and added tests to ensure robust handling of various edge cases in item editing.
Updated the purchase order processing to include enhanced validation for item edits, ensuring that all required fields are checked and properly formatted. Introduced new functions for computing item amounts, taking into account discounts and VAT. Refactored the PO detail view to streamline item management, including a new ItemsCard component for better organization of line items. Additionally, improved the handling of PO number sanitization to strip leading and trailing characters, enhancing matching accuracy. This update aims to improve the overall robustness and user experience of the purchase order system.
Enhanced the PersonScanner component to support a two-step flow for scanning employee badges. The new process includes a lookup phase to identify the employee and their last scan status, followed by a confirmation phase where the operator can verify the scan before recording the clock event. This change addresses issues with accidental double scans and improves user feedback with warnings for recent scans. Updated state management and error handling to reflect the new flow, ensuring a smoother user experience.
Introduced a new function to infer vehicle unit type from descriptions, improving the auto-creation process for vehicles in the fuel logs. Enhanced error handling for missing identifiers during vehicle creation, providing clearer feedback on the reasons for failures. Updated the SheetJS parsing to prevent date misinterpretation and refined the PlantPage to display all plant vehicles, regardless of cost per hour, ensuring better visibility of available resources.