feat(webui): payload field mapping -- bind JSON paths to named fields, preview before saving
Adds t2db.3: schema-by-example field mapping for the no-code playbook epic. An operator picks a captured event, clicks through its payload to bind named fields to JSON paths, and previews the resolution against a real event before saving -- a missing, null, or type-changed path fails loudly (named by field and event) rather than handing an agent a blank value. - internal/domain/mapping: Mapping/Field types, path parsing/walking, Resolve (per-field failure reporting), Validate (incl. duplicate names) - internal/store/mappings.go: SQLite persistence, mirrors captures.go - internal/webui/api_mapping.go: CRUD + preview HTTP API - ui/src/mappings/: dashboard editor (clickable payload tree, live preview) Design decisions recorded in docs/prds/payload-field-mapping.md. t2db.4 (binding a mapping + matcher to a workflow) is out of scope here.
This commit is contained in:
1 parent
c7987f0595
commit
aba035a396
22 files changed
+2143
-13
No files matched your search
@@ -27,3 +27,6 @@
|
||||
{"id":"int-907fab8ee9218dfc52e1b312ccdde513","kind":"field_change","created_at":"2026-08-21T15:00:54.642569071Z","actor":"Sam Catlow","issue_id":"archie-core-7d5u.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Decided and documented in docs/prds/event-sources-and-reactions.md, satisfying this bead's own acceptance criterion (a one-page decision naming the packages it touches and stating whether plugins-and-extensions.md needs amending -- it does not).\n\nAnswers: (1) in-process typed families, no out-of-process dispatch -- archie has no existing extension-process boundary and neither epic's stated payoff needs one. (2) Reaction delivery reuses internal/eventbus's Publisher/Consumer contract (PublishUnique + Ack/Nak already provide at-least-once with dedup), but NOT the existing nats.Client as-is: it hardcodes Retention: jetstream.WorkQueuePolicy (client.go:65) for the competing-consumer ARCHIE_TASKS stream, which silently starves a second consumer on overlapping subjects per CLAUDE.md's documented trap -- reactions need fan-out, so retention needs to become a Config field and reactions get their own stream. (3) Reactions in these two epics are producer-only (cheap wake via curator's WakeOnPrimaryInput pattern, or produce real work via the existing pollNATS->publishTask path) -- no veto/mutate-in-flight-work capability is being built here; that belongs to archie-core-h019 if it's ever needed. (4) No single generic Source interface -- forge intake reuses workintake.TaskEnvelope unchanged (its IdempotencyKey is already keyed on owner/repo/number, not delivery source, so a webhook-sourced envelope naturally dedups against a poll-discovered one for free); chat webhook stays internal/channels/webhook, unmodified; what's genuinely new and shared is a small cross-cutting package for HMAC/rate-limit/approval/capture mechanics, owned by neither domain."}}
|
||||
{"id":"int-15527c6640daf7df72a4876d8e82864c","kind":"field_change","created_at":"2026-08-21T15:26:01.152938969Z","actor":"Sam Catlow","issue_id":"archie-core-7d5u.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Built internal/webhookguard: VerifyHMAC (behavior-preserving extraction from internal/channels/webhook, which now calls it instead of keeping a private copy), RateLimiter (per-source token bucket, independent budgets, observable rejection), RedactPayload (key-name heuristic matching gateway/stream.go's marker list, but -- deliberately unlike that function -- redacts only values under sensitive keys and leaves ordinary strings/numbers/bools untouched, since a captured payload exists to be inspected for field mapping in t2db.3).\n\nAll four acceptance criteria met and independently confirmed by a fresh adversarial review with zero surviving findings: HMAC extraction is byte-for-byte behavior-preserving (diffed against the deleted function); rate limiter hand-traced correct on two scenarios plus race-clean under -race; redaction's divergence from gateway/stream.go verified by reading both functions side by side; zero non-stdlib imports confirmed by grep. The reviewer also mutation-tested both the redaction and rate-limit guards (disabled each in turn) and confirmed the test suite catches both, then reverted and re-verified go test -race and git status were clean.\n\ntask check exit 0, golangci-lint 0 issues (one forcetypeassert finding was caught and fixed properly during build, not suppressed), gofumpt clean. All 10 pre-existing internal/channels/webhook tests pass unmodified; the one now-redundant unit test was removed with a comment pointing to where its coverage relocated."}}
|
||||
{"id":"int-ccb87c91023dbaa6718ae2f7564d38cc","kind":"field_change","created_at":"2026-08-21T18:51:09.120109805Z","actor":"Sam Catlow","issue_id":"archie-core-t2db.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Built capture storage + endpoint: docs/prds/event-capture-storage.md decides SQLite over NATS JetStream (NATS not unconditionally available pre-7d5u.2, capture's single-writer/single-reader access pattern doesn't need JetStream fan-out/replay). internal/store/captures.go adds captured_events table + InsertCapture (prune-on-write by retention age and row count) + ListCaptures. internal/webui/api_capture.go adds POST /webhooks/capture/{source}, unauthenticated (bypasses requireToken like /healthz), applying webhookguard redaction before persisting and a per-remote-address rate limit + hard body-size cap before that. New [capture] config section with documented defaults. Adversarial self-review (the usual fresh subagent pass hit a session API limit mid-run, so this was a manual re-read with the same checklist) caught and fixed three real bugs before landing: (1) body-size cap silently unenforced when unset -- added a hardcoded fallback floor since it's the only bound on a SINGLE payload's size; (2) rate limiter was keyed by the request's own unregistered source path segment, violating webhookguard.RateLimiter's documented bounded-key-space assumption -- an attacker could rotate the segment to bypass the limit and grow the bucket map unbounded; rekeyed to remote address; (3) retention prune used time.RFC3339Nano, whose variable-width trimmed fractional seconds break lexicographic string comparison in `WHERE received_at < ?` (an exact-second timestamp can sort after a later fractional one) -- switched to fixed-width RFC3339. All three have regression tests verified to fail against the pre-fix code. task check clean, golangci-lint zero new findings repo-wide."}}
|
||||
{"id":"int-772ca35948f33ac9ada8096eceeb7144","kind":"field_change","created_at":"2026-08-21T19:17:03.32765544Z","actor":"Sam Catlow","issue_id":"archie-core-t2db.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"GET /api/captures (token-gated, memory/skills-style enabled:false-not-an-error when Captures is nil) plus a new /captures dashboard page: recent captures newest-first, expandable per-row to explore redacted payload/headers pretty-printed. Live updates reuse the existing operator-activity event pipeline (Server.emit -> Events.Publish -> the /events SSE stream) as an invalidation signal, refetching the list rather than merging partial event data. Every row shows an 'Unbound' pill today since no binding model exists yet (t2db.4 wires the real distinction). Frontend follows the tasks/task-row.js precedent: row rendering split into capture-row.js for unit testing without the page's fetch/SSE wiring. Adversarial review (fresh subagent, full pass) found one real severe bug before merge: the live SSE event was embedding the full (up to 256KiB) redacted body/headers into the events table, which has no retention/row-count prune anywhere in the codebase -- silently defeating t2db.1's disk-bound guarantee for an unauthenticated, only-rate-limited endpoint. Fixed: the live event now carries just {id, source} as a pure invalidation signal; the dashboard refetches the authoritative list. Two smaller findings (untested Data[\"id\"] field the frontend's dedup depended on; a received_at precision mismatch between live and REST-fetched copies) were resolved as a side effect of that fix. task check clean, golangci-lint zero new findings."}}
|
||||
{"id":"int-ca26e9b428d406303510eea34c2c8d05","kind":"field_change","created_at":"2026-08-21T19:18:55.467881536Z","actor":"Sam Catlow","issue_id":"archie-core-7d5u.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Embedded NATS wired into production startup: mode=embedded/external/off resolves from url, daemon owns the in-process server lifecycle, Retention parameterized for a future fan-out reaction stream. task check + lint clean; adversarial review zero surviving findings. Committed 2c7db34."}}
|
||||
{"id":"int-484f5673b3d49ea1731bec29e2a84074","kind":"field_change","created_at":"2026-08-22T09:01:53.455811598Z","actor":"Sam Catlow","issue_id":"archie-core-t2db.3","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Payload field mapping: domain (internal/domain/mapping), SQLite store (internal/store/mappings.go), HTTP API (internal/webui/api_mapping.go), and dashboard editor (ui/src/mappings) shipped. PRD at docs/prds/payload-field-mapping.md. task check green; adversarial review found 4 issues (stale preview after rename, duplicate field names, hardcoded capture scan window, malformed path silently reinterpreted), all fixed and re-verified."}}
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
{"_type":"issue","id":"archie-core-t2db.5","title":"Security: an unauthenticated endpoint must not be able to run an agent","description":"P0 within this epic because the feature's own pitch is the threat model: a public intake surface whose output is an agent with tool access and a repo. Get this wrong and a webhook URL is remote code execution with extra steps.\n\nNon-negotiables to design:\n\n- Per-source authentication. A source registers with a secret (HMAC, as internal/channels/webhook already does per route) before its events can trigger anything. Capture-only for unknown senders is acceptable; triggering is not.\n- Human approval before a binding goes live. An operator authoring a binding is a deliberate act; an event arriving is not. Nothing should self-arm.\n- Rate and volume limits per source, so capture cannot be used to exhaust disk or drown the inspector.\n- Payload content is untrusted input flowing into an agent prompt. Treat prompt injection as expected, not exceptional -- the sender controls that text, and the agent has tools. Bound what a playbook-triggered workflow may do.\n- Captured payloads may contain secrets from the sending system. Decide retention, redaction and who can view them; internal/memory/scrubber may already have applicable prior art.\n\nArchie's own principle applies: environmental enforcement over prompt rules. 'The agent should ignore instructions in the payload' is not a control.","acceptance_criteria":"An event from an unauthenticated source can be captured but cannot trigger a workflow; a new binding requires explicit human approval before it arms; per-source rate limits exist; the blast radius of a playbook-triggered workflow is bounded by code rather than by prompt text; retention and visibility of captured payloads is decided and documented.","notes":"2026-08-22: security design decided and documented in docs/prds/webhook-intake-security.md, covering all five non-negotiables from this bead's description:\n1. Per-source auth reuses internal/channels/webhook's existing HMAC-SHA256 scheme; capture accepts unsigned events (visible, marked unauthenticated), only authenticated events can ever match a binding.\n2. Bindings gain a draft -\u003e pending_approval -\u003e armed state machine; any edit to an armed binding drops it back to pending_approval so approval can't be bypassed by editing. Modeled on telegram's existing dangerousAction/pendingApproval flow (dangerous.go/approval.go).\n3. Per-source token-bucket rate limiting (precedent: pairing/store.go's MaxPendingPerPlatform); limit-exceeded is an observable 429, not a silent drop.\n4. Blast radius bounded by the SAME code-level controls every task already gets -- gate, diff_cap_lines, sandboxed container, worktree isolation -- no new relaxation for playbook-triggered work, and payload text is ordinary untrusted prompt input, never a trusted instruction.\n5. 7-day configurable retention on captured payloads; best-effort redaction reusing gateway/stream.go's sensitiveParameterKey heuristic before persisting; visibility gated by the same dashboard auth as every other webui surface.\n\nThis bead's code-level acceptance criteria (capture-can't-trigger, rate limits exist, blast-radius bounded, approval gate) cannot be implemented yet: they constrain t2db.1 (capture), 7d5u.3 (intake family) and t2db.4 (binding), none of which have landed. This document is the contract those beads build against -- do not build any of them without satisfying it. Leaving this bead in_progress rather than closing it; it closes when t2db.1/7d5u.3/t2db.4 land and demonstrably satisfy points 1-5, not before.","status":"in_progress","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:46Z","created_by":"Sam Catlow","updated_at":"2026-08-21T14:53:33Z","started_at":"2026-08-21T14:51:26Z","dependencies":[{"issue_id":"archie-core-t2db.5","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.4","title":"Playbook binding: matcher + mapping + workflow, editable at runtime","description":"The object that ties it together. A binding is: a matcher (which inbound events does this apply to), a mapping (which fields the workflow receives), and a target agentic workflow.\n\nRuntime-editable is the whole point -- creating or changing a binding must not require a redeploy or a daemon restart. That has real consequences the design must face:\n\n- Bindings are persisted state, not config. They live in the store, not config.toml, because operators create them from the UI while the daemon runs.\n- They need versioning. A binding that starts a task should record WHICH version ran, or a later edit makes historical task provenance a lie.\n- Matcher ambiguity needs a defined resolution: two bindings matching one event either both run, or the more specific wins, or it is an error. Pick one and say so.\n- A binding referencing a workflow that no longer exists must fail visibly at bind time, not at 3am when the event arrives.","acceptance_criteria":"A binding can be created, edited and disabled from the UI while the daemon runs; a task records the binding version that started it; overlapping matchers resolve by a defined and documented rule; a binding naming a missing workflow is rejected when saved.","notes":"2026-08-22: the draft -\u003e pending_approval -\u003e armed state machine from t2db.5's decision belongs to the binding entity this bead defines, not to a shared package -- 7d5u.3 was narrowed to exclude it since there is exactly one consumer today. Implement the state transitions here.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:45Z","created_by":"Sam Catlow","updated_at":"2026-08-21T15:19:05Z","dependencies":[{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.5","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.3","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.1","title":"Capture inbound events archie does not yet understand","description":"The precondition for everything else. Today an unrecognised inbound request is rejected; for schema-by-example it must be RECORDED, because you cannot map a payload you have never seen.\n\nAccept, store and retain inbound events with no binding: raw body, headers, source, arrival time, and the identity that sent it. Retention must be bounded -- an open capture endpoint is an unbounded disk write, and this is exactly the kind of surface an attacker fills.\n\nStrong argument for NATS JetStream as the store rather than the in-process events.Bus: durable, replayable, retention-bounded natively, already deployed. Note the constraint though -- internal/infrastructure/eventbus/nats/doc.go states 'when no NATS URL is configured the daemon uses its local SQLite claim flow instead; nothing here is required for single-process operation'. NATS is currently OPTIONAL. Decide deliberately whether capture requires it (making this feature unavailable in single-process deployments) or degrades to SQLite, and record which -- do not let it become a hard dependency by accident.","acceptance_criteria":"An unbound webhook POST is captured and visible rather than rejected; capture is retention-bounded with a documented limit; the single-process (no NATS) behaviour is a deliberate, recorded decision; capture cannot exhaust disk.","notes":"2026-08-22: capture-storage ownership confirmed here (not in 7d5u.3, which was narrowed to storage-agnostic HMAC/rate-limit/redaction mechanics only). This bead's capture path should call webhookguard's redaction before persisting and its rate limiter at the HTTP boundary, but owns its own storage engine and the NATS-vs-SQLite decision.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-21T18:51:09Z","started_at":"2026-08-21T16:18:24Z","closed_at":"2026-08-21T18:51:09Z","close_reason":"Built capture storage + endpoint: docs/prds/event-capture-storage.md decides SQLite over NATS JetStream (NATS not unconditionally available pre-7d5u.2, capture's single-writer/single-reader access pattern doesn't need JetStream fan-out/replay). internal/store/captures.go adds captured_events table + InsertCapture (prune-on-write by retention age and row count) + ListCaptures. internal/webui/api_capture.go adds POST /webhooks/capture/{source}, unauthenticated (bypasses requireToken like /healthz), applying webhookguard redaction before persisting and a per-remote-address rate limit + hard body-size cap before that. New [capture] config section with documented defaults. Adversarial self-review (the usual fresh subagent pass hit a session API limit mid-run, so this was a manual re-read with the same checklist) caught and fixed three real bugs before landing: (1) body-size cap silently unenforced when unset -- added a hardcoded fallback floor since it's the only bound on a SINGLE payload's size; (2) rate limiter was keyed by the request's own unregistered source path segment, violating webhookguard.RateLimiter's documented bounded-key-space assumption -- an attacker could rotate the segment to bypass the limit and grow the bucket map unbounded; rekeyed to remote address; (3) retention prune used time.RFC3339Nano, whose variable-width trimmed fractional seconds break lexicographic string comparison in `WHERE received_at \u003c ?` (an exact-second timestamp can sort after a later fractional one) -- switched to fixed-width RFC3339. All three have regression tests verified to fail against the pre-fix code. task check clean, golangci-lint zero new findings repo-wide.","dependencies":[{"issue_id":"archie-core-t2db.1","depends_on_id":"archie-core-7d5u.4","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.1","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.2","title":"Event inspector: see real inbound payloads in the dashboard","description":"The operator-facing half of capture. A live view of recent inbound events: source, arrival time, and the actual payload, pretty-printed and explorable.\n\nThis is the screen that makes the feature feel like magic: you hit 'send test webhook' in the other app, alt-tab to archie, and the event is sitting there. Latency from arrival to visible matters more than it looks -- it is the difference between a design loop and a guessing game.\n\nShow unbound events prominently. An event nothing is listening to is not noise here, it is the queue of integrations waiting to be built.","acceptance_criteria":"Recent inbound events are listed with source, time and full payload; unbound events are distinguishable from bound ones; a newly arrived event appears without a manual refresh; payloads are explorable rather than a wall of text.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-21T18:57:52Z","started_at":"2026-08-21T18:57:52Z","dependencies":[{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.3","title":"Map payload fields by example, from a real captured event","description":"Pick a captured event, click through its payload, and bind JSON paths to named fields the workflow will receive. Schema by example, not schema by specification.\n\nThe hard part is not the happy path, it is drift. A mapping authored against one payload will eventually meet a payload where the path is missing, null, or a different type -- the sending app shipped a change nobody told you about. That must fail LOUDLY and land somewhere the operator sees, not silently pass an empty string into an agent prompt. An agent handed a blank field will confabulate around it, which turns a schema change into an agent doing confident nonsense in a repo.\n\nSupport a preview: given this mapping and this captured event, show exactly what the workflow would receive. Never ship a mapping the operator has not seen resolve against real data.","acceptance_criteria":"Fields are mappable from a captured payload without writing code; a mapping preview resolves against a real event before saving; a missing, null or type-changed path at runtime produces a visible failure rather than an empty value; the failure names the path and the event.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-21T13:45:18Z","dependencies":[{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:18Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.2","title":"Event inspector: see real inbound payloads in the dashboard","description":"The operator-facing half of capture. A live view of recent inbound events: source, arrival time, and the actual payload, pretty-printed and explorable.\n\nThis is the screen that makes the feature feel like magic: you hit 'send test webhook' in the other app, alt-tab to archie, and the event is sitting there. Latency from arrival to visible matters more than it looks -- it is the difference between a design loop and a guessing game.\n\nShow unbound events prominently. An event nothing is listening to is not noise here, it is the queue of integrations waiting to be built.","acceptance_criteria":"Recent inbound events are listed with source, time and full payload; unbound events are distinguishable from bound ones; a newly arrived event appears without a manual refresh; payloads are explorable rather than a wall of text.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-21T19:17:03Z","started_at":"2026-08-21T18:57:52Z","closed_at":"2026-08-21T19:17:03Z","close_reason":"GET /api/captures (token-gated, memory/skills-style enabled:false-not-an-error when Captures is nil) plus a new /captures dashboard page: recent captures newest-first, expandable per-row to explore redacted payload/headers pretty-printed. Live updates reuse the existing operator-activity event pipeline (Server.emit -\u003e Events.Publish -\u003e the /events SSE stream) as an invalidation signal, refetching the list rather than merging partial event data. Every row shows an 'Unbound' pill today since no binding model exists yet (t2db.4 wires the real distinction). Frontend follows the tasks/task-row.js precedent: row rendering split into capture-row.js for unit testing without the page's fetch/SSE wiring. Adversarial review (fresh subagent, full pass) found one real severe bug before merge: the live SSE event was embedding the full (up to 256KiB) redacted body/headers into the events table, which has no retention/row-count prune anywhere in the codebase -- silently defeating t2db.1's disk-bound guarantee for an unauthenticated, only-rate-limited endpoint. Fixed: the live event now carries just {id, source} as a pure invalidation signal; the dashboard refetches the authoritative list. Two smaller findings (untested Data[\"id\"] field the frontend's dedup depended on; a received_at precision mismatch between live and REST-fetched copies) were resolved as a side effect of that fix. task check clean, golangci-lint zero new findings.","dependencies":[{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db.3","title":"Map payload fields by example, from a real captured event","description":"Pick a captured event, click through its payload, and bind JSON paths to named fields the workflow will receive. Schema by example, not schema by specification.\n\nThe hard part is not the happy path, it is drift. A mapping authored against one payload will eventually meet a payload where the path is missing, null, or a different type -- the sending app shipped a change nobody told you about. That must fail LOUDLY and land somewhere the operator sees, not silently pass an empty string into an agent prompt. An agent handed a blank field will confabulate around it, which turns a schema change into an agent doing confident nonsense in a repo.\n\nSupport a preview: given this mapping and this captured event, show exactly what the workflow would receive. Never ship a mapping the operator has not seen resolve against real data.","acceptance_criteria":"Fields are mappable from a captured payload without writing code; a mapping preview resolves against a real event before saving; a missing, null or type-changed path at runtime produces a visible failure rather than an empty value; the failure names the path and the event.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:01:53Z","started_at":"2026-08-22T08:39:40Z","closed_at":"2026-08-22T09:01:53Z","close_reason":"Payload field mapping: domain (internal/domain/mapping), SQLite store (internal/store/mappings.go), HTTP API (internal/webui/api_mapping.go), and dashboard editor (ui/src/mappings) shipped. PRD at docs/prds/payload-field-mapping.md. task check green; adversarial review found 4 issues (stale preview after rename, duplicate field names, hardcoded capture scan window, malformed path silently reinterpreted), all fixed and re-verified.","dependencies":[{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:18Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-t2db","title":"[EPIC] Event capture and no-code playbooks: turn any inbound webhook into an agentic workflow","description":"The pitch, in the operator's words: point any app's outgoing webhook at archie, open archie, SEE the event that just arrived with its real payload, map the fields you care about, bind them to an agentic workflow, save. No code change, no redeploy, no restart. Adding a new integration stops being a development task.\n\nWhy this is different from n8n or Power Automate rather than a copy of them: their terminal node is a deterministic connector. Archie's is an AGENT with a repo, a worktree, tools and a gate. 'When Sentry reports a new issue in this project, open a PR that fixes it' is one binding here and an entire product elsewhere.\n\nThe design insight that makes it buildable: you cannot write a payload mapper against a payload you have not seen. Schema-by-example requires real recent events to map against, which means archie must CAPTURE events it does not yet understand -- including ones with no binding at all -- and retain them long enough to design against. That is also the strongest argument for putting inbound events on NATS JetStream rather than the lossy in-process bus: durable, replayable, retention-bounded, and already deployed. The capture requirement and the transport choice are the same decision.\n\nSequence: capture unrecognised events -\u003e inspect real payloads in the UI -\u003e map fields by example -\u003e bind matcher+mapping to a workflow -\u003e the next matching event runs it.\n\nThis is a public, unauthenticated-by-default intake surface whose output is an agent with tool access. Security is not a later hardening pass; it is a first-class child of this epic.","acceptance_criteria":"An operator can point a new external webhook at archie, see its payload in the UI without writing code, map fields, bind it to a workflow, and have the next matching event run that workflow -- with no redeploy and no daemon restart. A binding cannot go live without explicit human approval.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-21T13:44:56Z","created_by":"Sam Catlow","updated_at":"2026-08-21T13:44:56Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.4","title":"GitHub forge webhook receiver behind a feature flag","description":"The concrete autonomy win: react to an issue being assigned or labelled the moment it happens, instead of up to poll_interval (default 60s) later.\n\nVerified absent on 2026-08-21: internal/forge/ and internal/daemon/ contain zero webhook references, and no bead tracked forge-event intake before this epic. internal/channels/webhook exists but is a CHAT channel -- it routes inbound text through gateway.Router for LLM processing, a peer of Telegram and email. It is not forge intake and should not be bent into it.\n\nShip as a source in the typed intake family, off by default: [forge] intake = 'poll' (default) | 'webhook' | 'both'. Verify GitHub's HMAC signature. Reuse the label/assignee dispatch predicate the poller already uses -- do NOT reimplement it, since it just took a fix (3209a1f, refusing to poll on an empty label match) and two implementations will drift.\n\nDeployment reality from CLAUDE.md: archied may run on a host, in a container, or behind no public ingress at all. A webhook receiver that assumes a reachable public URL will not fit every profile, which is exactly why polling has to remain a first-class option rather than a legacy fallback.","acceptance_criteria":"With intake='webhook', a labelled issue starts a task without waiting for the poll interval; an invalid HMAC is rejected and logged; intake='poll' behaves exactly as today; the dispatch predicate is shared with the poller, not duplicated; the flag defaults to poll.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-21T13:26:52Z","dependencies":[{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-t2db.1","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.3","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.4","title":"GitHub forge webhook receiver behind a feature flag","description":"The concrete autonomy win: react to an issue being assigned or labelled the moment it happens, instead of up to poll_interval (default 60s) later.\n\nVerified absent on 2026-08-21: internal/forge/ and internal/daemon/ contain zero webhook references, and no bead tracked forge-event intake before this epic. internal/channels/webhook exists but is a CHAT channel -- it routes inbound text through gateway.Router for LLM processing, a peer of Telegram and email. It is not forge intake and should not be bent into it.\n\nShip as a source in the typed intake family, off by default: [forge] intake = 'poll' (default) | 'webhook' | 'both'. Verify GitHub's HMAC signature. Reuse the label/assignee dispatch predicate the poller already uses -- do NOT reimplement it, since it just took a fix (3209a1f, refusing to poll on an empty label match) and two implementations will drift.\n\nDeployment reality from CLAUDE.md: archied may run on a host, in a container, or behind no public ingress at all. A webhook receiver that assumes a reachable public URL will not fit every profile, which is exactly why polling has to remain a first-class option rather than a legacy fallback.","acceptance_criteria":"With intake='webhook', a labelled issue starts a task without waiting for the poll interval; an invalid HMAC is rejected and logged; intake='poll' behaves exactly as today; the dispatch predicate is shared with the poller, not duplicated; the flag defaults to poll.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T08:43:35Z","started_at":"2026-08-22T08:43:35Z","dependencies":[{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-t2db.1","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.3","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.5","title":"Idempotency and poll/webhook parity: never double-dispatch, never lose work","description":"Webhooks deliver at-least-once, out of order, and sometimes not at all. Polling is the opposite: slow but eventually consistent. Running both (intake='both') is the honest production configuration, and it is also where the two failure modes meet.\n\nTwo things must hold. A single issue event must not start two tasks because the webhook and the next poll both saw it. And a webhook outage must not silently stop work -- if the receiver is wedged or the ingress is down, polling has to pick the work up, which is the entire argument for keeping it.\n\nNote archie-core-...-286 (WebhookAdapter: idempotency cache) already exists for the chat adapter. Decide whether that mechanism generalises to intake or whether forge dispatch needs its own key; do not build a second one by accident.\n\nThe silent-failure shape to design against is the one this codebase keeps hitting: a path that looks like it is working because nothing errors. A webhook receiver that has silently stopped delivering looks identical to a repo with no activity.","acceptance_criteria":"A duplicate delivery of the same forge event starts exactly one task; with intake='both', disabling the webhook path still results in the work being picked up by polling; a wedged or non-delivering webhook receiver is observable rather than indistinguishable from an idle repo.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-21T13:26:52Z","dependencies":[{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.4","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-1786637497328-286-9c985f28","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.1","title":"Design: event sources, reaction delivery, and how extensions hook them","description":"No settled design covers this. docs/architecture/plugins-and-extensions.md settles the PLUGIN FRAMEWORK (metadata-only contract, typed capability families, owning registries) but says nothing about event sources, reaction delivery, or intake. Under the scope-discipline rule merged as PR #533, that means design first -- one page, decisive -- then a diff.\n\nDecide and record in docs/prds/:\n\n1. THE HEADLINE QUESTION, which changes everything downstream: do extensions react in-process through typed capability families (what the approved rule mandates), or out-of-process like tau's generic DispatchEvent? If out-of-process generic dispatch is genuinely wanted, docs/architecture/plugins-and-extensions.md is an APPROVED document and must be amended first -- CLAUDE.md's organisation rule is explicit that you change the doc before the rule it states. Do not quietly work around it.\n\n2. Reaction delivery. events.Bus drops on overflow by design and must stay that way for the dashboard. Decide whether reactions get a second in-process bus with at-least-once delivery, or ride the existing NATS eventbus (internal/infrastructure/eventbus), which already has durable semantics and the work-queue traps documented in CLAUDE.md.\n\n3. Whether a reaction may INFLUENCE an outcome (veto, mutate, add work) or only observe. This is the difference between a hook and a subscriber, and it determines whether ordering and failure semantics matter. If a reaction can block, decide what a slow or crashed extension does -- tau's answer was a dispatch timeout, and it still deadlocked unload once.\n\n4. The typed source/intake family: its interface, its owning registry, and how a source declares what it produces.\n\nRespect dependency direction: cmd -\u003e app -\u003e {domain, infrastructure}. A domain declares the contract; app wires implementations. Cross-cutting packages may be imported by any layer and import none.","acceptance_criteria":"A one-page decision in docs/prds/ answering all four questions, naming the packages it will touch, and stating explicitly whether plugins-and-extensions.md needs amending. It decides rather than surveys.","notes":"CORRECTION 2026-08-22 (second): decision question 2 in this bead's description asked whether reactions get a second in-process bus or ride the existing NATS eventbus. That framing is wrong -- there is no 'or'. NATS is the settled transport; the only open axis is external-server vs embedded, not NATS vs something else. Do not design a second bus. See archie-core-7d5u and archie-core-7d5u.2 for the corrected framing and the verified state of github.com/nats-io/nats-server/v2 as an already-present, test-proven, production-unwired dependency.","status":"closed","priority":1,"issue_type":"decision","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-21T15:00:55Z","started_at":"2026-08-21T14:56:21Z","closed_at":"2026-08-21T15:00:55Z","close_reason":"Decided and documented in docs/prds/event-sources-and-reactions.md, satisfying this bead's own acceptance criterion (a one-page decision naming the packages it touches and stating whether plugins-and-extensions.md needs amending -- it does not).\n\nAnswers: (1) in-process typed families, no out-of-process dispatch -- archie has no existing extension-process boundary and neither epic's stated payoff needs one. (2) Reaction delivery reuses internal/eventbus's Publisher/Consumer contract (PublishUnique + Ack/Nak already provide at-least-once with dedup), but NOT the existing nats.Client as-is: it hardcodes Retention: jetstream.WorkQueuePolicy (client.go:65) for the competing-consumer ARCHIE_TASKS stream, which silently starves a second consumer on overlapping subjects per CLAUDE.md's documented trap -- reactions need fan-out, so retention needs to become a Config field and reactions get their own stream. (3) Reactions in these two epics are producer-only (cheap wake via curator's WakeOnPrimaryInput pattern, or produce real work via the existing pollNATS-\u003epublishTask path) -- no veto/mutate-in-flight-work capability is being built here; that belongs to archie-core-h019 if it's ever needed. (4) No single generic Source interface -- forge intake reuses workintake.TaskEnvelope unchanged (its IdempotencyKey is already keyed on owner/repo/number, not delivery source, so a webhook-sourced envelope naturally dedups against a poll-discovered one for free); chat webhook stays internal/channels/webhook, unmodified; what's genuinely new and shared is a small cross-cutting package for HMAC/rate-limit/approval/capture mechanics, owned by neither domain.","dependencies":[{"issue_id":"archie-core-7d5u.1","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependeLine truncated
|
||||
{"_type":"issue","id":"archie-core-7d5u.2","title":"Reaction delivery via embedded NATS, no external server required","description":"Reactions need at-least-once delivery distinct from the lossy events.Bus (see epic description). The delivery mechanism is NATS -- that part is settled, not a design question. What's open is deployment shape.\n\nVERIFIED 2026-08-22: config.NATSConfig.URL empty currently means 'no NATS, use SQLite ClaimNext' (internal/config/config.go:573-582). That fallback was designed for task distribution working without a broker at all. It was never meant to generalise to 'archie has no NATS' as a permanent architectural stance -- the intended second deployment shape alongside an external NATS server was always NATS EMBEDDED (in-process), not a different eventbus.\n\ngithub.com/nats-io/nats-server/v2 is already a direct dependency and is proven to work in this codebase: internal/infrastructure/agenttransport/nats/transport_test.go and others already start a real embedded server via nats-server/v2/test for tests. It has just never been wired into production startup -- cmd/archied only knows 'external URL configured' vs 'fall back to SQLite'. No new library, no new bus, no architectural gap to design around: this is 'wire the dependency we already have and already test against into the daemon's own startup path.'\n\nDesign questions that remain, now correctly scoped: does an embedded NATS instance replace the SQLite fallback outright for single-process deployments, or run alongside it; what config controls embedded vs external vs disabled; does the daemon own the embedded server's lifecycle the same way it owns everything else (start/stop paired with daemon start/stop, per the shutdown-ordering rules in ARCHITECTURE.md).","acceptance_criteria":"A single-process deployment with no external NATS URL configured still gets reaction delivery via an embedded NATS instance; the daemon starts and stops the embedded server as part of its own lifecycle; no second eventbus type is introduced; internal/infrastructure/eventbus/nats is reused as the transport rather than duplicated.","notes":"2026-08-22, from docs/prds/event-sources-and-reactions.md: do not reuse the existing nats.Client's stream creation as-is. internal/infrastructure/eventbus/nats/client.go:65 hardcodes Retention: jetstream.WorkQueuePolicy -- correct for ARCHIE_TASKS (task distribution, one consumer claims each message) and wrong for reactions, which need fan-out (every registered reaction sees every matching event). Two reactions on overlapping subjects under WorkQueuePolicy hit the exact trap CLAUDE.md documents: the second consumer silently gets nothing. Config.StreamName/Config.Subjects are already composition-supplied (config.go:30-38); Retention is not parameterized and needs to become a Config field, defaulting to today's WorkQueuePolicy so ARCHIE_TASKS is unaffected, with reactions getting a second stream under a fan-out-capable policy and their own subject namespace.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-21T18:57:41Z","started_at":"2026-08-21T18:57:41Z","dependencies":[{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.2","title":"Reaction delivery via embedded NATS, no external server required","description":"Reactions need at-least-once delivery distinct from the lossy events.Bus (see epic description). The delivery mechanism is NATS -- that part is settled, not a design question. What's open is deployment shape.\n\nVERIFIED 2026-08-22: config.NATSConfig.URL empty currently means 'no NATS, use SQLite ClaimNext' (internal/config/config.go:573-582). That fallback was designed for task distribution working without a broker at all. It was never meant to generalise to 'archie has no NATS' as a permanent architectural stance -- the intended second deployment shape alongside an external NATS server was always NATS EMBEDDED (in-process), not a different eventbus.\n\ngithub.com/nats-io/nats-server/v2 is already a direct dependency and is proven to work in this codebase: internal/infrastructure/agenttransport/nats/transport_test.go and others already start a real embedded server via nats-server/v2/test for tests. It has just never been wired into production startup -- cmd/archied only knows 'external URL configured' vs 'fall back to SQLite'. No new library, no new bus, no architectural gap to design around: this is 'wire the dependency we already have and already test against into the daemon's own startup path.'\n\nDesign questions that remain, now correctly scoped: does an embedded NATS instance replace the SQLite fallback outright for single-process deployments, or run alongside it; what config controls embedded vs external vs disabled; does the daemon own the embedded server's lifecycle the same way it owns everything else (start/stop paired with daemon start/stop, per the shutdown-ordering rules in ARCHITECTURE.md).","acceptance_criteria":"A single-process deployment with no external NATS URL configured still gets reaction delivery via an embedded NATS instance; the daemon starts and stops the embedded server as part of its own lifecycle; no second eventbus type is introduced; internal/infrastructure/eventbus/nats is reused as the transport rather than duplicated.","notes":"2026-08-22, from docs/prds/event-sources-and-reactions.md: do not reuse the existing nats.Client's stream creation as-is. internal/infrastructure/eventbus/nats/client.go:65 hardcodes Retention: jetstream.WorkQueuePolicy -- correct for ARCHIE_TASKS (task distribution, one consumer claims each message) and wrong for reactions, which need fan-out (every registered reaction sees every matching event). Two reactions on overlapping subjects under WorkQueuePolicy hit the exact trap CLAUDE.md documents: the second consumer silently gets nothing. Config.StreamName/Config.Subjects are already composition-supplied (config.go:30-38); Retention is not parameterized and needs to become a Config field, defaulting to today's WorkQueuePolicy so ARCHIE_TASKS is unaffected, with reactions getting a second stream under a fan-out-capable policy and their own subject namespace.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-21T19:18:55Z","started_at":"2026-08-21T18:57:41Z","closed_at":"2026-08-21T19:18:55Z","close_reason":"Embedded NATS wired into production startup: mode=embedded/external/off resolves from url, daemon owns the in-process server lifecycle, Retention parameterized for a future fan-out reaction stream. task check + lint clean; adversarial review zero surviving findings. Committed 2c7db34.","dependencies":[{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u.3","title":"Shared webhook mechanics: HMAC verification, per-source rate limiting, payload redaction","description":"NARROWED 2026-08-22 from this bead's prior scope, which bundled capture-storage and an approval state machine into a single 'shared mechanics' package. On reflection those are not genuinely shared yet:\n\n- Capture STORAGE is t2db.1's job -- it depends on the NATS-vs-SQLite decision 7d5u.2 owns, and building a storage engine here would either duplicate or contradict that. This package may be USED by t2db.1's capture path, but does not own persistence.\n- The draft/pending_approval/armed state machine belongs to the entity that has that state -- t2db.4's binding -- not a generic package. There is exactly one consumer (bindings) today; per 'extract into a shared primitive on the second real consumer, never in anticipation of one,' building it here now would be speculative.\n\nWhat remains, and is genuinely storage-agnostic and reusable by any inbound HTTP source regardless of what consumes it:\n\n1. HMAC-SHA256 verification -- generalize internal/channels/webhook/webhook.go's existing unexported validateHMAC into an exported function here, and have that package call into it instead of keeping its own copy. One implementation of signature checking, not two that can drift.\n2. Per-source rate limiting -- a token bucket keyed by source ID (not global), so one noisy sender cannot exhaust another's budget. Limit-exceeded is an observable rejection, not a silent drop, per t2db.5's decision.\n3. Payload redaction -- generalize internal/gateway/stream.go's unexported sensitiveParameterKey/redactToolParameters heuristic (matches token/secret/password/passwd/api_key/apikey/authorization/credential/cookie/private_key against normalized JSON keys) into a reusable, storage-agnostic transform any capture path can apply before persisting.","acceptance_criteria":"webhookguard.VerifyHMAC replaces internal/channels/webhook's private copy with no behaviour change (its existing tests still pass); a per-source rate limiter rejects over-budget requests observably; a redaction function matches the same key heuristic already proven in gateway/stream.go; the package has zero imports of any domain, infrastructure or app package.","notes":"--notes=2026-08-22: merged to main as f3d3d32 (PR #534, squash of aa23ac9+46401ab+ce4f945).","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-21T15:35:55Z","started_at":"2026-08-21T15:19:09Z","closed_at":"2026-08-21T15:26:01Z","close_reason":"Built internal/webhookguard: VerifyHMAC (behavior-preserving extraction from internal/channels/webhook, which now calls it instead of keeping a private copy), RateLimiter (per-source token bucket, independent budgets, observable rejection), RedactPayload (key-name heuristic matching gateway/stream.go's marker list, but -- deliberately unlike that function -- redacts only values under sensitive keys and leaves ordinary strings/numbers/bools untouched, since a captured payload exists to be inspected for field mapping in t2db.3).\n\nAll four acceptance criteria met and independently confirmed by a fresh adversarial review with zero surviving findings: HMAC extraction is byte-for-byte behavior-preserving (diffed against the deleted function); rate limiter hand-traced correct on two scenarios plus race-clean under -race; redaction's divergence from gateway/stream.go verified by reading both functions side by side; zero non-stdlib imports confirmed by grep. The reviewer also mutation-tested both the redaction and rate-limit guards (disabled each in turn) and confirmed the test suite catches both, then reverted and re-verified go test -race and git status were clean.\n\ntask check exit 0, golangci-lint 0 issues (one forcetypeassert finding was caught and fixed properly during build, not suppressed), gofumpt clean. All 10 pre-existing internal/channels/webhook tests pass unmodified; the one now-redundant unit test was removed with a comment pointing to where its coverage relocated.","dependencies":[{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7d5u","title":"[EPIC] Event sources and typed reactions: archie as an extensible platform","description":"Goal: let archie react to things happening -- forge activity, inbound callers, schedules -- and let extensions hook those reactions, without a generic untyped event bus.\n\nTwo findings shape this, both verified in the tree on 2026-08-21.\n\n1. ARCHIE HAS TWO EVENT NEEDS AND ONE BUS. internal/events is documented as 'archied's in-process observability stream' with 'bounded per-subscriber buffers that DROP on overflow, so a stalled dashboard connection can never apply backpressure to the task engine'. Publish is fire-and-forget; subscribers get a read-only channel and cannot influence anything. Correct for the dashboard, wrong for reactions: a hook that silently misses events under load and cannot affect an outcome is worse than no hook, because it looks like it ran. Reactions need at-least-once delivery and the ability to change what happens. Do not bolt reactions onto events.Bus.\n\n2. THE OBVIOUS DESIGN IS PROHIBITED, DELIBERATELY. The tau model this is drawn from dispatches generically: DispatchEvent(ctx, eventName string, sessionID, ...) to out-of-process gRPC plugins. archie's approved foundation (docs/architecture/plugins-and-extensions.md) forbids that shape -- the generic plugin contract stays metadata-only and MUST NOT expose untyped hooks. plugin.Plugin is Name()/Version() only, enforced by internal/plugin/architecture_test.go and by the plugin engine rule in ARCHITECTURE.md. tau already carries the scar the rule avoids: TestUnload_DoesNotWaitForInFlightDispatch exists because a stuck plugin blocked plugin unload.\n\nThe reconciliation, and why this is an epic rather than a feature: separate INBOUND (callers push work in -- forge webhook, chat webhook, cron, channel) from REACTION (extensions respond to something that happened). Inbound becomes a typed source/intake capability family with an owning registry. Reactions become typed capability families owned by the domain whose semantics they affect. 'Webhooks aligned to types of callers' is exactly the typed-family model applied to intake: the instinct is right, the generic bus is what has to go.\n\nNear-term payoff: archie reacts to an issue being labelled the moment it happens, instead of up to poll_interval later.","acceptance_criteria":"A forge webhook triggers work behind a feature flag with polling still available as a backstop; inbound callers register through one typed family rather than bespoke wiring per caller; reactions have delivery guarantees distinct from the lossy observability bus; the generic plugin contract remains metadata-only and internal/plugin/architecture_test.go still passes.","notes":"CORRECTION 2026-08-22 (second): the earlier summary I gave characterized 'NATS is currently optional' as an open architectural gap for this epic to navigate around. That's wrong, and Sam corrected it directly: NATS was never meant to be optional as a technology. What's optional is running a standalone NATS SERVER -- config.NATSConfig.URL empty falls back to the existing SQLite ClaimNext flow (internal/config/config.go:573-582, internal/infrastructure/eventbus/nats/doc.go:24). The intended second deployment shape is NATS EMBEDDED (in-process, no external server to stand up), not 'no NATS, use some other eventbus'. There is no other eventbus in scope, was never meant to be one, and this epic must not introduce one.\n\nCurrent code state, verified: github.com/nats-io/nats-server/v2 (the embeddable NATS server package) is already a direct, non-indirect dependency, and is genuinely used to spin up an in-process server -- but only inside _test.go files (internal/infrastructure/agenttransport/nats/transport_test.go and others use github.com/nats-io/nats-server/v2/test to run tests against a real embedded server). It has never been wired into production as an actual deployment mode. So embedded NATS is proven to work in this codebase's own test harness, and the gap is purely that production startup only knows 'external URL configured' vs 'no NATS, fall back to SQLite' -- there is no production code path that starts nats-server in-process.\n\nThis changes 7d5u.2 (reaction delivery) materially: 'ride the existing NATS eventbus, or a second in-process bus' was the wrong framing. The actual question is whether reaction delivery requires an external NATS deployment or can run on an embedded NATS instance so single-process deployments still get it -- not whether to use NATS at all versus some other bus. If embedded NATS is wired for reaction delivery, capture (t2db.1) gets it too essentially for free, since they were flagged as needing the same underlying decision.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-21T13:25:57Z","created_by":"Sam Catlow","updated_at":"2026-08-21T14:28:13Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-h019.3","title":"Reviewer runs in a context that provably never saw the implementation","description":"This is the whole feature. A reviewer that shares the implementer's context is a second opinion from the same mind, and it will rationalise the same mistakes -- which is exactly the failure mode CLAUDE.md's 'never self-certified by the implementer' rule exists to prevent.\n\nArchie already has the machinery: each task runs in an isolated container against its own worktree. Launch the reviewer the same way, seeded only with the diff and the originating issue. It must not receive the implementer's conversation, its notes, its reasoning, or its own claims about what it did.\n\nPer 'environmental enforcement over prompt rules', isolation must be a property of construction, not a sentence in the prompt. The agent cannot talk its way out of a context it was never given. Assert it in a test rather than assuming it: a test that would fail if implementer context were threaded through.","acceptance_criteria":"The reviewer is launched with only diff + issue; a test fails if implementer context reaches it; the reviewer's prompt instructs it to assume every line is wrong until proven correct; the mechanism reuses the existing container/worktree isolation rather than inventing a second one.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","updated_at":"2026-08-21T13:02:54Z","dependencies":[{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
@@ -34,6 +35,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
forgewebhook "github.com/samcharles93/archie-core/internal/forge/webhook"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
@@ -325,6 +327,14 @@ func (b *boot) setupObservability() {
|
||||
b.web.CaptureMaxEvents = cfg.Capture.MaxEvents
|
||||
b.web.CaptureMaxBodyBytes = int64(cfg.Capture.MaxBodyBytes)
|
||||
b.web.CaptureLimiter = webhookguard.NewRateLimiter(cfg.Capture.RatePerSecond, cfg.Capture.RateBurst, time.Now)
|
||||
// Mapping storage: same narrow-assertion pattern as CaptureStore above,
|
||||
// for the same reason -- openProductionTaskStore's declared return type
|
||||
// doesn't expose it. See docs/prds/payload-field-mapping.md.
|
||||
if ms, ok := b.st.(store.MappingStore); ok {
|
||||
b.web.Mappings = ms
|
||||
} else {
|
||||
log.Warn("mapping storage unavailable: task store does not implement MappingStore")
|
||||
}
|
||||
sink := bus.Subscribe(256)
|
||||
go persistAndBroadcastEvents(sink, b.st, b.web, log)
|
||||
}
|
||||
@@ -970,6 +980,64 @@ func (b *boot) buildDaemon() {
|
||||
// this point /api/config and the daemon can never disagree about the
|
||||
// published config.
|
||||
b.web.Cfg = b.d.Cfg
|
||||
b.setupForgeWebhook()
|
||||
}
|
||||
|
||||
// setupForgeWebhook starts the forge webhook receiver when intake is "webhook"
|
||||
// or "both". It decodes GitHub issue events into task envelopes and publishes
|
||||
// them through the same path the poller uses, so a labelled or assigned issue
|
||||
// becomes work immediately instead of on the next poll. Called from
|
||||
// buildDaemon, since it needs the freshly built (*daemon.Daemon).PublishTask.
|
||||
//
|
||||
// A secret that fails to resolve degrades rather than aborts boot, same
|
||||
// reasoning as resolveForge: under intake="both" the poll is the deployment's
|
||||
// explicit backstop for exactly this kind of misconfiguration (CLAUDE.md's
|
||||
// "polling has to remain a first-class option, not a legacy fallback"), so a
|
||||
// typo'd env var name must not take the whole daemon down and silently stop
|
||||
// polling too. Config validation already requires webhook_secret to be a
|
||||
// configured reference before intake="webhook"/"both" is accepted; this
|
||||
// handles the reference resolving to nothing at runtime.
|
||||
// Single-identity only: the receiver has one dispatch config (root
|
||||
// Dispatch.Trigger/Label/BotUser), so a multi-identity deployment's
|
||||
// per-identity trigger/label/bot user cannot be matched correctly. Rather
|
||||
// than run with the wrong identity's rules and silently misclassify or drop
|
||||
// events for identity-scoped repos, webhook intake refuses to start when
|
||||
// [[identities]] is configured; those repos keep working via their own
|
||||
// per-identity poll loop, unaffected. Extending this to multi-identity is a
|
||||
// separate feature, not a bug in this one.
|
||||
func (b *boot) setupForgeWebhook() {
|
||||
cfg, log := b.cfg, b.log
|
||||
if cfg.Forge.Intake != config.ForgeIntakeWebhook && cfg.Forge.Intake != config.ForgeIntakeBoth {
|
||||
return
|
||||
}
|
||||
if len(cfg.Identities) > 0 {
|
||||
log.Error("forge webhook disabled: multi-identity deployments are not supported yet (each identity's own poll loop is unaffected)")
|
||||
return
|
||||
}
|
||||
secretValue, err := cfg.Forge.WebhookSecret.Resolve(b.secrets)
|
||||
if err != nil || secretValue == "" {
|
||||
log.Error("forge webhook disabled: secret unavailable",
|
||||
"engine", cfg.Forge.WebhookSecret.Engine, "key", cfg.Forge.WebhookSecret.Key, "err", err)
|
||||
return
|
||||
}
|
||||
receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, log)
|
||||
host, port := parseListenAddr(cfg.Forge.WebhookAddr, "0.0.0.0", 8645)
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
srv := &http.Server{Addr: addr, Handler: receiver}
|
||||
|
||||
b.startGateways = append(b.startGateways, func() {
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Error("forge webhook server stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
log.Info("forge webhook listening", "addr", addr)
|
||||
})
|
||||
b.addCleanup(func() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(shutdownCtx)
|
||||
})
|
||||
}
|
||||
|
||||
// publishConfig publishes a config snapshot and its provenance to both
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
# Payload field mapping -- decision
|
||||
|
||||
**Status:** Decided, not yet implemented
|
||||
**Date:** 2026-08-22
|
||||
**Beads issue:** `archie-core-t2db.3`, depends on `t2db.1`, blocks `t2db.4`
|
||||
|
||||
Answers what a "mapping" is, where it lives, and what "resolve against a
|
||||
real event" means precisely enough to implement. `t2db.4` (binding: matcher
|
||||
+ mapping + workflow) is out of scope -- this bead ships the mapping
|
||||
concept and its preview only, as a standalone entity `t2db.4` will later
|
||||
reference by ID.
|
||||
|
||||
## Decision: a new `internal/domain/mapping` package, SQLite storage
|
||||
|
||||
`internal/domain/mapping` owns the mapping vocabulary and the pure
|
||||
resolve/preview rule; `internal/store` persists it (mirrors
|
||||
`captures.go`'s shape exactly -- inline schema const, narrow store
|
||||
interface, `*store.Store` implementation); `internal/webui/api_mapping.go`
|
||||
is the transport. This follows `docs/prds/event-capture-storage.md`'s own
|
||||
placement precedent: `internal/store` is where this daemon's persistence
|
||||
already lives, not `internal/infrastructure` (that layer today holds
|
||||
cross-domain services -- config, eventbus, modelcatalog -- not this
|
||||
daemon's primary store).
|
||||
|
||||
### Why a domain package and not just a store table
|
||||
|
||||
Resolving a path against a payload and deciding "missing vs null vs
|
||||
type-changed" is a rule, not a query -- CLAUDE.md's domain layer owns
|
||||
"language, state, rules, operations" precisely so this logic is testable
|
||||
without a database and reusable by `t2db.4`'s runtime trigger path without
|
||||
either package importing the other's transport concerns.
|
||||
|
||||
## Mapping shape
|
||||
|
||||
```go
|
||||
type Mapping struct {
|
||||
ID int64
|
||||
Name string
|
||||
SourceHint string // free-text label (e.g. "sentry"), organisational only -- not enforced against Capture.Source
|
||||
Fields []Field
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Field struct {
|
||||
Name string // the name the workflow receives
|
||||
Path string // dot/bracket path into the payload, see below
|
||||
Type FieldType // expected type, checked at resolve time
|
||||
Required bool // Required=false + missing is not a failure; Required=false + wrong type still is
|
||||
}
|
||||
|
||||
type FieldType string // "string" | "number" | "bool" | "object" | "array" | "any"
|
||||
```
|
||||
|
||||
`SourceHint` is advisory only: an operator authors a mapping by clicking
|
||||
through one example capture, but the mapping is not pinned to that
|
||||
capture's exact source string, because `t2db.4`'s matcher (not this bead)
|
||||
decides which events a binding applies to. Pinning here would duplicate
|
||||
that decision in the wrong layer.
|
||||
|
||||
## Path syntax
|
||||
|
||||
Dot-separated keys with `[N]` for array indices: `data.items[0].id`. No
|
||||
wildcards, no filters, no external library -- the grammar is exactly what a
|
||||
click-through UI needs to express (this key, then this key, then this
|
||||
index), and every path in a mapping was generated by clicking a value in a
|
||||
real payload, never hand-written against a spec. A hand-rolled parser
|
||||
(~30 lines: split on `.`, strip `[N]` suffixes) is less risk than a new
|
||||
dependency for a grammar this small.
|
||||
|
||||
## Resolve semantics (the preview AND the future runtime path)
|
||||
|
||||
```go
|
||||
func Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure)
|
||||
|
||||
type Failure struct {
|
||||
FieldName string
|
||||
Path string
|
||||
Reason string // "missing" | "null" | "type_mismatch"
|
||||
}
|
||||
```
|
||||
|
||||
Decode with `json.Decoder.UseNumber()` (matches `webhookguard.RedactPayload`'s
|
||||
existing convention) so int/float distinction survives for type checking.
|
||||
Walk each field's path independently -- one field's failure does not stop
|
||||
resolution of the others, because the whole point of preview is showing
|
||||
the operator every problem at once, not the first one.
|
||||
|
||||
- Path segment doesn't exist, or indexes past an array's length -> `missing`
|
||||
- Path resolves to JSON `null` -> `null`
|
||||
- Path resolves to a value whose JSON type doesn't match `Field.Type`
|
||||
(`"any"` always matches) -> `type_mismatch`
|
||||
- `Required: false` suppresses `missing` only, never `null` or
|
||||
`type_mismatch` -- a field that's present but the wrong shape is always
|
||||
worth surfacing, since silently coercing it is exactly the "agent
|
||||
confabulates around a blank field" failure this bead exists to prevent.
|
||||
|
||||
**This is the same function both consumers use.** `t2db.3`'s preview calls
|
||||
it against an operator-picked capture and renders every result, pass or
|
||||
fail, in the UI -- that satisfies this bead's "fail loudly" acceptance
|
||||
criterion, because at this stage the only runtime consumer of a mapping
|
||||
*is* the human previewing it. `t2db.4` will call the identical function
|
||||
when a live event triggers a binding and turn any non-empty `failures` into
|
||||
a visible operator-facing failure (park the task / surface in the
|
||||
inspector) instead of starting a workflow with blank fields -- that wiring
|
||||
is `t2db.4`'s job, not duplicated here.
|
||||
|
||||
## Storage
|
||||
|
||||
`internal/store/mappings.go`, `field_mappings` table: `id, name,
|
||||
source_hint, fields_json, created_at, updated_at`. `fields_json` is the
|
||||
`[]Field` slice JSON-encoded into one column -- fields have no independent
|
||||
query need (nothing filters "mappings with a field named X" today), so a
|
||||
join table would be structure with no consumer, the same failure mode
|
||||
`organisation.md` bans for empty layering.
|
||||
|
||||
`MappingStore` interface (narrow, mirrors `CaptureStore`):
|
||||
`InsertMapping`, `ListMappings`, `GetMapping`, `UpdateMapping`,
|
||||
`DeleteMapping`.
|
||||
|
||||
## HTTP surface
|
||||
|
||||
All under `/api/mappings`, token-gated like every other `/api/*` route (no
|
||||
bypass -- unlike capture, nothing here accepts unauthenticated input):
|
||||
|
||||
- `GET /api/mappings` / `POST /api/mappings` -- list / create
|
||||
- `GET|PATCH|DELETE /api/mappings/{id}`
|
||||
- `POST /api/mappings/preview` -- body `{fields: []Field, capture_id:
|
||||
int64}`, calls `mapping.Resolve` against that capture's stored (already
|
||||
redacted) `Body` and returns `{values, failures}`. Deliberately takes
|
||||
loose `fields` rather than a saved mapping ID, so an operator can iterate
|
||||
before saving anything -- "never ship a mapping the operator has not seen
|
||||
resolve against real data" requires preview to work pre-save.
|
||||
|
||||
Preview resolves against `CapturedEvent.Body`, which is already
|
||||
redaction-passed (`webhookguard.RedactPayload`, per
|
||||
`event-capture-storage.md`) -- a mapped field pointing at a
|
||||
sensitive-keyed path previews as the literal string `"[redacted]"`, not the
|
||||
real value. This is accepted, not fixed here: it is the stored ground
|
||||
truth, the same payload `t2db.4`'s runtime path will resolve against, and a
|
||||
preview mismatch would be worse than an honest one.
|
||||
|
||||
## Frontend
|
||||
|
||||
New `ui/src/mappings/` feature folder, same three-file split as
|
||||
`ui/src/captures/`: `mappings.js` (page: list, fetch, create/edit flow),
|
||||
`mapping-editor.js` (pure, unit-testable: renders a captured payload as a
|
||||
clickable tree -- clicking a leaf appends a field row with `Path`
|
||||
pre-filled -- plus the field table and preview-result rendering),
|
||||
`mappings.css`. Creating a mapping starts from an existing captured event
|
||||
(reuses `api.captures`), so the editor always has a real payload to click
|
||||
through and preview against, never a blank form.
|
||||
|
||||
## What this does not decide
|
||||
|
||||
The binding entity, its matcher, its draft/pending_approval/armed state
|
||||
machine, and turning a runtime `Resolve` failure into a parked task are
|
||||
`t2db.4`. Per-source HMAC secret registration is `t2db.5`. This bead ships
|
||||
the mapping concept, its storage, and its preview only.
|
||||
@@ -0,0 +1,266 @@
|
||||
// Package mapping owns the payload field-mapping vocabulary and its
|
||||
// resolve/preview rule: binding named fields to JSON paths inside a
|
||||
// captured webhook payload, and deciding -- loudly -- when a path a mapping
|
||||
// depends on has drifted out from under it. See
|
||||
// docs/prds/payload-field-mapping.md.
|
||||
package mapping
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FieldType is the expected JSON shape of a mapped field, checked at
|
||||
// resolve time.
|
||||
type FieldType string
|
||||
|
||||
const (
|
||||
TypeString FieldType = "string"
|
||||
TypeNumber FieldType = "number"
|
||||
TypeBool FieldType = "bool"
|
||||
TypeObject FieldType = "object"
|
||||
TypeArray FieldType = "array"
|
||||
TypeAny FieldType = "any"
|
||||
)
|
||||
|
||||
// Failure reasons. A field either resolves to a value or fails for exactly
|
||||
// one of these -- never both.
|
||||
const (
|
||||
ReasonMissing = "missing"
|
||||
ReasonNull = "null"
|
||||
ReasonTypeMismatch = "type_mismatch"
|
||||
)
|
||||
|
||||
// Field binds one named field the workflow receives to a path into a
|
||||
// captured payload. Required=false suppresses ReasonMissing only -- a
|
||||
// present-but-wrong-shape value always fails, so a mapping never silently
|
||||
// hands an agent a value it didn't expect.
|
||||
type Field struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Type FieldType `json:"type"`
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
// Mapping is a named, reusable set of field bindings, authored by clicking
|
||||
// through one example captured event but not pinned to that event or its
|
||||
// source -- t2db.4's matcher decides which events a binding applies to.
|
||||
type Mapping struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
Fields []Field `json:"fields"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// validTypes is the set of FieldType values Validate accepts.
|
||||
var validTypes = map[FieldType]bool{
|
||||
TypeString: true, TypeNumber: true, TypeBool: true,
|
||||
TypeObject: true, TypeArray: true, TypeAny: true,
|
||||
}
|
||||
|
||||
// Validate checks a mapping is well-formed before it is persisted or
|
||||
// previewed: a name, at least one field, and every field naming a
|
||||
// non-empty field name, a non-empty path, and a recognised type. It does
|
||||
// not check the mapping against any payload -- that is Resolve's job.
|
||||
func (m Mapping) Validate() error {
|
||||
if strings.TrimSpace(m.Name) == "" {
|
||||
return fmt.Errorf("mapping: name is required")
|
||||
}
|
||||
if len(m.Fields) == 0 {
|
||||
return fmt.Errorf("mapping: at least one field is required")
|
||||
}
|
||||
seen := make(map[string]bool, len(m.Fields))
|
||||
for i, f := range m.Fields {
|
||||
if strings.TrimSpace(f.Name) == "" {
|
||||
return fmt.Errorf("mapping: field %d: name is required", i)
|
||||
}
|
||||
if strings.TrimSpace(f.Path) == "" {
|
||||
return fmt.Errorf("mapping: field %d (%s): path is required", i, f.Name)
|
||||
}
|
||||
if !validTypes[f.Type] {
|
||||
return fmt.Errorf("mapping: field %d (%s): unrecognised type %q", i, f.Name, f.Type)
|
||||
}
|
||||
// A duplicate name would let one field silently overwrite another's
|
||||
// resolved value in Resolve's values map -- reject it here instead
|
||||
// of losing data silently at resolve time.
|
||||
if seen[f.Name] {
|
||||
return fmt.Errorf("mapping: field %d: duplicate field name %q", i, f.Name)
|
||||
}
|
||||
seen[f.Name] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Failure describes one field that did not resolve cleanly against a
|
||||
// payload -- named by field and path so the operator (or, once t2db.4
|
||||
// lands, the runtime failure it surfaces) knows exactly what drifted.
|
||||
type Failure struct {
|
||||
FieldName string `json:"field_name"`
|
||||
Path string `json:"path"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Resolve walks payload independently for each field, so one field's
|
||||
// failure never stops the others from resolving -- preview must show every
|
||||
// problem at once, not the first one. A field that fails never appears in
|
||||
// values.
|
||||
func Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure) {
|
||||
values = make(map[string]any, len(fields))
|
||||
|
||||
var root any
|
||||
dec := json.NewDecoder(bytes.NewReader(payload))
|
||||
dec.UseNumber()
|
||||
if err := dec.Decode(&root); err != nil {
|
||||
for _, f := range fields {
|
||||
failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonMissing})
|
||||
}
|
||||
return values, failures
|
||||
}
|
||||
|
||||
for _, f := range fields {
|
||||
v, found := walk(root, parsePath(f.Path))
|
||||
if !found {
|
||||
if f.Required {
|
||||
failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonMissing})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if v == nil {
|
||||
failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonNull})
|
||||
continue
|
||||
}
|
||||
if !typeMatches(v, f.Type) {
|
||||
failures = append(failures, Failure{FieldName: f.Name, Path: f.Path, Reason: ReasonTypeMismatch})
|
||||
continue
|
||||
}
|
||||
values[f.Name] = normalize(v)
|
||||
}
|
||||
|
||||
return values, failures
|
||||
}
|
||||
|
||||
// pathSegment is a map key (Key set, Index == -1), an array index
|
||||
// (Index >= 0, Key empty), or Invalid -- a bracket segment whose contents
|
||||
// were not a plain non-negative integer (e.g. "items[abc]"). walk always
|
||||
// fails an Invalid segment rather than silently dropping it and matching a
|
||||
// shorter, unintended path -- a malformed path must read as ReasonMissing,
|
||||
// never as a different path succeeding by accident.
|
||||
type pathSegment struct {
|
||||
Key string
|
||||
Index int
|
||||
Invalid bool
|
||||
}
|
||||
|
||||
// parsePath splits "data.items[0].id" into
|
||||
// [{Key:"data"} {Key:"items"} {Index:0} {Key:"id"}]. No wildcards, no
|
||||
// filters -- the grammar is exactly what a click-through UI generates.
|
||||
func parsePath(path string) []pathSegment {
|
||||
var segs []pathSegment
|
||||
for part := range strings.SplitSeq(path, ".") {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
for {
|
||||
open := strings.IndexByte(part, '[')
|
||||
if open < 0 {
|
||||
if part != "" {
|
||||
segs = append(segs, pathSegment{Key: part, Index: -1})
|
||||
}
|
||||
break
|
||||
}
|
||||
if open > 0 {
|
||||
segs = append(segs, pathSegment{Key: part[:open], Index: -1})
|
||||
}
|
||||
closeIdx := strings.IndexByte(part[open:], ']')
|
||||
if closeIdx < 0 {
|
||||
segs = append(segs, pathSegment{Invalid: true})
|
||||
break
|
||||
}
|
||||
closeIdx += open
|
||||
idx, err := strconv.Atoi(part[open+1 : closeIdx])
|
||||
if err != nil {
|
||||
segs = append(segs, pathSegment{Invalid: true})
|
||||
} else {
|
||||
segs = append(segs, pathSegment{Index: idx})
|
||||
}
|
||||
part = part[closeIdx+1:]
|
||||
if part == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return segs
|
||||
}
|
||||
|
||||
// walk descends node by path. found=false means the path does not exist in
|
||||
// the payload at all (missing), which is distinct from resolving to a JSON
|
||||
// null (node == nil, found == true).
|
||||
func walk(node any, path []pathSegment) (value any, found bool) {
|
||||
cur := node
|
||||
for _, seg := range path {
|
||||
if seg.Invalid {
|
||||
return nil, false
|
||||
}
|
||||
if cur == nil {
|
||||
return nil, false
|
||||
}
|
||||
if seg.Index >= 0 {
|
||||
arr, ok := cur.([]any)
|
||||
if !ok || seg.Index >= len(arr) {
|
||||
return nil, false
|
||||
}
|
||||
cur = arr[seg.Index]
|
||||
continue
|
||||
}
|
||||
obj, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
v, ok := obj[seg.Key]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
cur = v
|
||||
}
|
||||
return cur, true
|
||||
}
|
||||
|
||||
func typeMatches(v any, want FieldType) bool {
|
||||
if want == TypeAny {
|
||||
return true
|
||||
}
|
||||
switch v.(type) {
|
||||
case string:
|
||||
return want == TypeString
|
||||
case json.Number:
|
||||
return want == TypeNumber
|
||||
case bool:
|
||||
return want == TypeBool
|
||||
case map[string]any:
|
||||
return want == TypeObject
|
||||
case []any:
|
||||
return want == TypeArray
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// normalize converts json.Number to float64 so resolved values are ordinary
|
||||
// JSON-encodable Go types for the preview response, matching
|
||||
// encoding/json's own default number decoding.
|
||||
func normalize(v any) any {
|
||||
if n, ok := v.(json.Number); ok {
|
||||
f, err := n.Float64()
|
||||
if err != nil {
|
||||
return fmt.Sprint(n)
|
||||
}
|
||||
return f
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package mapping_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
func TestResolveExtractsValuesByPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload string
|
||||
fields []mapping.Field
|
||||
want map[string]any
|
||||
}{
|
||||
{
|
||||
name: "top level string",
|
||||
payload: `{"action":"opened"}`,
|
||||
fields: []mapping.Field{{Name: "action", Path: "action", Type: mapping.TypeString}},
|
||||
want: map[string]any{"action": "opened"},
|
||||
},
|
||||
{
|
||||
name: "nested object",
|
||||
payload: `{"issue":{"title":"bug found"}}`,
|
||||
fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
|
||||
want: map[string]any{"title": "bug found"},
|
||||
},
|
||||
{
|
||||
name: "array index",
|
||||
payload: `{"items":[{"id":1},{"id":2}]}`,
|
||||
fields: []mapping.Field{{Name: "second_id", Path: "items[1].id", Type: mapping.TypeNumber}},
|
||||
want: map[string]any{"second_id": float64(2)},
|
||||
},
|
||||
{
|
||||
name: "any type matches anything",
|
||||
payload: `{"flag":true}`,
|
||||
fields: []mapping.Field{{Name: "flag", Path: "flag", Type: mapping.TypeAny}},
|
||||
want: map[string]any{"flag": true},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
values, failures := mapping.Resolve(tt.fields, []byte(tt.payload))
|
||||
if len(failures) != 0 {
|
||||
t.Fatalf("unexpected failures: %+v", failures)
|
||||
}
|
||||
for k, want := range tt.want {
|
||||
got, ok := values[k]
|
||||
if !ok {
|
||||
t.Fatalf("missing resolved value for %q", k)
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("values[%q] = %#v, want %#v", k, got, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveReportsFailuresLoudly(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload string
|
||||
fields []mapping.Field
|
||||
wantReason string
|
||||
}{
|
||||
{
|
||||
name: "missing path",
|
||||
payload: `{"action":"opened"}`,
|
||||
fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true}},
|
||||
wantReason: mapping.ReasonMissing,
|
||||
},
|
||||
{
|
||||
name: "null value",
|
||||
payload: `{"issue":{"title":null}}`,
|
||||
fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
|
||||
wantReason: mapping.ReasonNull,
|
||||
},
|
||||
{
|
||||
name: "type mismatch",
|
||||
payload: `{"issue":{"title":42}}`,
|
||||
fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
|
||||
wantReason: mapping.ReasonTypeMismatch,
|
||||
},
|
||||
{
|
||||
name: "index past array length",
|
||||
payload: `{"items":[{"id":1}]}`,
|
||||
fields: []mapping.Field{{Name: "second_id", Path: "items[1].id", Type: mapping.TypeNumber, Required: true}},
|
||||
wantReason: mapping.ReasonMissing,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
values, failures := mapping.Resolve(tt.fields, []byte(tt.payload))
|
||||
if len(failures) != 1 {
|
||||
t.Fatalf("got %d failures, want 1: %+v", len(failures), failures)
|
||||
}
|
||||
f := failures[0]
|
||||
if f.Reason != tt.wantReason {
|
||||
t.Errorf("Reason = %q, want %q", f.Reason, tt.wantReason)
|
||||
}
|
||||
if f.FieldName != tt.fields[0].Name {
|
||||
t.Errorf("FieldName = %q, want %q", f.FieldName, tt.fields[0].Name)
|
||||
}
|
||||
if f.Path != tt.fields[0].Path {
|
||||
t.Errorf("Path = %q, want %q", f.Path, tt.fields[0].Path)
|
||||
}
|
||||
if _, ok := values[tt.fields[0].Name]; ok {
|
||||
t.Errorf("a failed field must not appear in values, got %#v", values[tt.fields[0].Name])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveOptionalMissingIsNotAFailure(t *testing.T) {
|
||||
fields := []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: false}}
|
||||
values, failures := mapping.Resolve(fields, []byte(`{"action":"opened"}`))
|
||||
if len(failures) != 0 {
|
||||
t.Fatalf("optional missing field must not fail, got %+v", failures)
|
||||
}
|
||||
if _, ok := values["title"]; ok {
|
||||
t.Errorf("missing optional field must not appear in values")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveOptionalButWrongTypeStillFails(t *testing.T) {
|
||||
fields := []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: false}}
|
||||
_, failures := mapping.Resolve(fields, []byte(`{"issue":{"title":42}}`))
|
||||
if len(failures) != 1 || failures[0].Reason != mapping.ReasonTypeMismatch {
|
||||
t.Fatalf("optional field with wrong type must still fail loudly, got %+v", failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveKeepsGoingAfterOneFieldFails(t *testing.T) {
|
||||
fields := []mapping.Field{
|
||||
{Name: "missing", Path: "nope", Type: mapping.TypeString, Required: true},
|
||||
{Name: "action", Path: "action", Type: mapping.TypeString},
|
||||
}
|
||||
values, failures := mapping.Resolve(fields, []byte(`{"action":"opened"}`))
|
||||
if len(failures) != 1 {
|
||||
t.Fatalf("want exactly 1 failure, got %+v", failures)
|
||||
}
|
||||
if values["action"] != "opened" {
|
||||
t.Errorf("second field should still resolve, got values=%+v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsMalformedMappings(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
m mapping.Mapping
|
||||
}{
|
||||
{"empty name", mapping.Mapping{Name: "", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}}},
|
||||
{"no fields", mapping.Mapping{Name: "m", Fields: nil}},
|
||||
{"field with no name", mapping.Mapping{Name: "m", Fields: []mapping.Field{{Path: "a", Type: mapping.TypeString}}}},
|
||||
{"field with no path", mapping.Mapping{Name: "m", Fields: []mapping.Field{{Name: "a", Type: mapping.TypeString}}}},
|
||||
{"field with unknown type", mapping.Mapping{Name: "m", Fields: []mapping.Field{{Name: "a", Path: "a", Type: "wat"}}}},
|
||||
{"duplicate field names", mapping.Mapping{Name: "m", Fields: []mapping.Field{
|
||||
{Name: "a", Path: "x", Type: mapping.TypeString},
|
||||
{Name: "a", Path: "y", Type: mapping.TypeString},
|
||||
}}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.m.Validate(); err == nil {
|
||||
t.Fatalf("Validate() = nil, want an error for %+v", tt.m)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAcceptsWellFormedMapping(t *testing.T) {
|
||||
m := mapping.Mapping{
|
||||
Name: "sentry issue opened",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true}},
|
||||
}
|
||||
if err := m.Validate(); err != nil {
|
||||
t.Fatalf("Validate() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTreatsMalformedArrayIndexAsMissingNotReinterpreted(t *testing.T) {
|
||||
// "items[abc].id" must never silently resolve as if it were "items.id" --
|
||||
// a malformed path is a mistake the operator should see, not a different
|
||||
// path succeeding by accident.
|
||||
fields := []mapping.Field{{Name: "id", Path: "items[abc].id", Type: mapping.TypeNumber, Required: true}}
|
||||
values, failures := mapping.Resolve(fields, []byte(`{"items":{"id":5}}`))
|
||||
if len(failures) != 1 || failures[0].Reason != mapping.ReasonMissing {
|
||||
t.Fatalf("failures = %+v, want exactly one ReasonMissing", failures)
|
||||
}
|
||||
if _, ok := values["id"]; ok {
|
||||
t.Fatalf("a malformed path must never resolve a value, got %#v", values["id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveNumberPreservesIntVsFloatShapeButTypeCheckIsNumeric(t *testing.T) {
|
||||
fields := []mapping.Field{
|
||||
{Name: "count", Path: "count", Type: mapping.TypeNumber},
|
||||
}
|
||||
values, failures := mapping.Resolve(fields, []byte(`{"count":42}`))
|
||||
if len(failures) != 0 {
|
||||
t.Fatalf("unexpected failures: %+v", failures)
|
||||
}
|
||||
if values["count"] != float64(42) {
|
||||
t.Errorf("count = %#v, want float64(42)", values["count"])
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
@@ -85,6 +86,19 @@ type CaptureStore interface {
|
||||
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
|
||||
}
|
||||
|
||||
// MappingStore persists payload field mappings (t2db.3). Deliberately
|
||||
// separate from TaskStore and CaptureStore for the same reason those are
|
||||
// split: the dashboard's mapping editor should only acquire the mapping
|
||||
// surface, not the full task or capture APIs. See
|
||||
// docs/prds/payload-field-mapping.md.
|
||||
type MappingStore interface {
|
||||
InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error)
|
||||
GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error)
|
||||
ListMappings(ctx context.Context) ([]mapping.Mapping, error)
|
||||
UpdateMapping(ctx context.Context, m mapping.Mapping) error
|
||||
DeleteMapping(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
// Compile-time check: *Store satisfies TaskStore.
|
||||
var _ TaskStore = (*Store)(nil)
|
||||
|
||||
@@ -93,3 +107,6 @@ var _ WorkflowStore = (*Store)(nil)
|
||||
|
||||
// Compile-time check: *Store satisfies CaptureStore.
|
||||
var _ CaptureStore = (*Store)(nil)
|
||||
|
||||
// Compile-time check: *Store satisfies MappingStore.
|
||||
var _ MappingStore = (*Store)(nil)
|
||||
@@ -0,0 +1,163 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
const mappingsSchema = `
|
||||
CREATE TABLE IF NOT EXISTS field_mappings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
source_hint TEXT NOT NULL DEFAULT '',
|
||||
fields_json TEXT NOT NULL DEFAULT '[]',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
`
|
||||
|
||||
// ErrMappingNotFound is returned by UpdateMapping and DeleteMapping when no
|
||||
// row matches the given ID. GetMapping uses (nil, nil) instead, matching
|
||||
// TaskByID's convention -- "not found" is the normal answer to "does a
|
||||
// mapping with this ID currently exist," not an error.
|
||||
var ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
|
||||
// mappingTimeLayout follows captureTimeLayout's reasoning: fixed-width so
|
||||
// string and chronological order agree, even though nothing here prunes on
|
||||
// a string comparison today -- consistency with the rest of the store's
|
||||
// timestamp columns.
|
||||
const mappingTimeLayout = time.RFC3339
|
||||
|
||||
// InsertMapping persists a new mapping and stamps CreatedAt/UpdatedAt to
|
||||
// now, ignoring any caller-supplied values.
|
||||
func (s *Store) InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error) {
|
||||
fieldsJSON, err := json.Marshal(m.Fields)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("store: marshal mapping fields: %w", err)
|
||||
}
|
||||
now := time.Now().UTC().Format(mappingTimeLayout)
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO field_mappings (name, source_hint, fields_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
m.Name, m.SourceHint, string(fieldsJSON), now, now)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// GetMapping returns the mapping with the given ID, or (nil, nil) if none
|
||||
// exists.
|
||||
func (s *Store) GetMapping(ctx context.Context, id int64) (*mapping.Mapping, error) {
|
||||
row := s.db.QueryRowContext(ctx, `
|
||||
SELECT id, name, source_hint, fields_json, created_at, updated_at
|
||||
FROM field_mappings WHERE id=?`, id)
|
||||
m, err := scanMapping(row)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ListMappings returns every mapping, newest first.
|
||||
func (s *Store) ListMappings(ctx context.Context) (out []mapping.Mapping, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, name, source_hint, fields_json, created_at, updated_at
|
||||
FROM field_mappings ORDER BY id DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { retErr = errors.Join(retErr, rows.Close()) }()
|
||||
|
||||
for rows.Next() {
|
||||
m, err := scanMappingRow(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpdateMapping replaces the name, source hint and fields of an existing
|
||||
// mapping and bumps UpdatedAt to now. Returns ErrMappingNotFound if m.ID
|
||||
// does not exist.
|
||||
func (s *Store) UpdateMapping(ctx context.Context, m mapping.Mapping) error {
|
||||
fieldsJSON, err := json.Marshal(m.Fields)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store: marshal mapping fields: %w", err)
|
||||
}
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
UPDATE field_mappings SET name=?, source_hint=?, fields_json=?, updated_at=?
|
||||
WHERE id=?`,
|
||||
m.Name, m.SourceHint, string(fieldsJSON), time.Now().UTC().Format(mappingTimeLayout), m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrMappingNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteMapping removes a mapping by ID. Returns ErrMappingNotFound if it
|
||||
// does not exist.
|
||||
func (s *Store) DeleteMapping(ctx context.Context, id int64) error {
|
||||
res, err := s.db.ExecContext(ctx, `DELETE FROM field_mappings WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrMappingNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mappingScanner is satisfied by both *sql.Row and *sql.Rows, so
|
||||
// scanMapping's column list stays in exactly one place.
|
||||
type mappingScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanMapping(row mappingScanner) (*mapping.Mapping, error) {
|
||||
return scanMappingRow(row)
|
||||
}
|
||||
|
||||
func scanMappingRow(row mappingScanner) (*mapping.Mapping, error) {
|
||||
var m mapping.Mapping
|
||||
var fieldsJSON, createdAt, updatedAt string
|
||||
if err := row.Scan(&m.ID, &m.Name, &m.SourceHint, &fieldsJSON, &createdAt, &updatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal([]byte(fieldsJSON), &m.Fields); err != nil {
|
||||
return nil, fmt.Errorf("store: unmarshal mapping fields: %w", err)
|
||||
}
|
||||
created, err := time.Parse(mappingTimeLayout, createdAt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: unrecognised mapping created_at %q: %w", createdAt, err)
|
||||
}
|
||||
updated, err := time.Parse(mappingTimeLayout, updatedAt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: unrecognised mapping updated_at %q: %w", updatedAt, err)
|
||||
}
|
||||
m.CreatedAt = created.UTC()
|
||||
m.UpdatedAt = updated.UTC()
|
||||
return &m, nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
func testFields() []mapping.Field {
|
||||
return []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
{Name: "count", Path: "count", Type: mapping.TypeNumber},
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertMappingRoundTrips(t *testing.T) {
|
||||
s := openTest(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "sentry issue opened",
|
||||
SourceHint: "sentry",
|
||||
Fields: testFields(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping: %v", err)
|
||||
}
|
||||
if id == 0 {
|
||||
t.Fatalf("InsertMapping returned zero id")
|
||||
}
|
||||
|
||||
got, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetMapping: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("GetMapping returned nil for a just-inserted row")
|
||||
}
|
||||
if got.ID != id || got.Name != "sentry issue opened" || got.SourceHint != "sentry" {
|
||||
t.Fatalf("round-tripped mapping = %+v", got)
|
||||
}
|
||||
if len(got.Fields) != 2 || got.Fields[0].Name != "title" || got.Fields[0].Path != "issue.title" ||
|
||||
got.Fields[0].Type != mapping.TypeString || !got.Fields[0].Required {
|
||||
t.Fatalf("round-tripped fields = %+v", got.Fields)
|
||||
}
|
||||
if got.CreatedAt.IsZero() || got.UpdatedAt.IsZero() {
|
||||
t.Fatalf("CreatedAt/UpdatedAt must be stamped, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetMappingMissingReturnsNilNoError(t *testing.T) {
|
||||
s := openTest(t)
|
||||
got, err := s.GetMapping(t.Context(), 999)
|
||||
if err != nil {
|
||||
t.Fatalf("GetMapping: %v", err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("GetMapping for a missing id = %+v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMappingsOrdersNewestFirst(t *testing.T) {
|
||||
s := openTest(t)
|
||||
for i := range 3 {
|
||||
if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", Fields: testFields()}); err != nil {
|
||||
t.Fatalf("InsertMapping[%d]: %v", i, err)
|
||||
}
|
||||
}
|
||||
got, err := s.ListMappings(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ListMappings: %v", err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("ListMappings = %d rows, want 3", len(got))
|
||||
}
|
||||
if got[0].ID <= got[1].ID || got[1].ID <= got[2].ID {
|
||||
t.Fatalf("ListMappings not newest-first: ids = %d, %d, %d", got[0].ID, got[1].ID, got[2].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateMappingChangesFieldsAndBumpsUpdatedAt(t *testing.T) {
|
||||
s := openTest(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "orig", Fields: testFields()})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping: %v", err)
|
||||
}
|
||||
before, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil || before == nil {
|
||||
t.Fatalf("GetMapping before update: %+v, %v", before, err)
|
||||
}
|
||||
|
||||
newFields := []mapping.Field{{Name: "renamed", Path: "a.b", Type: mapping.TypeBool}}
|
||||
if err := s.UpdateMapping(t.Context(), mapping.Mapping{
|
||||
ID: id, Name: "renamed mapping", SourceHint: "github", Fields: newFields,
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateMapping: %v", err)
|
||||
}
|
||||
|
||||
after, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil || after == nil {
|
||||
t.Fatalf("GetMapping after update: %+v, %v", after, err)
|
||||
}
|
||||
if after.Name != "renamed mapping" || after.SourceHint != "github" {
|
||||
t.Fatalf("updated mapping = %+v", after)
|
||||
}
|
||||
if len(after.Fields) != 1 || after.Fields[0].Name != "renamed" {
|
||||
t.Fatalf("updated fields = %+v", after.Fields)
|
||||
}
|
||||
if !after.UpdatedAt.After(before.UpdatedAt) && !after.UpdatedAt.Equal(before.UpdatedAt) {
|
||||
t.Fatalf("UpdatedAt did not advance: before=%v after=%v", before.UpdatedAt, after.UpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateMappingMissingReturnsErrMappingNotFound(t *testing.T) {
|
||||
s := openTest(t)
|
||||
err := s.UpdateMapping(t.Context(), mapping.Mapping{ID: 999, Name: "x", Fields: testFields()})
|
||||
if !errors.Is(err, ErrMappingNotFound) {
|
||||
t.Fatalf("UpdateMapping on missing id = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMappingRemovesRow(t *testing.T) {
|
||||
s := openTest(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", Fields: testFields()})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping: %v", err)
|
||||
}
|
||||
if err := s.DeleteMapping(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteMapping: %v", err)
|
||||
}
|
||||
got, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetMapping after delete: %v", err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("GetMapping after delete = %+v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteMappingMissingReturnsErrMappingNotFound(t *testing.T) {
|
||||
s := openTest(t)
|
||||
err := s.DeleteMapping(t.Context(), 999)
|
||||
if !errors.Is(err, ErrMappingNotFound) {
|
||||
t.Fatalf("DeleteMapping on missing id = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func Open(ctx context.Context, path string) (*Store, error) {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema); err != nil {
|
||||
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close())
|
||||
}
|
||||
if err := migrateTasks(ctx, db); err != nil {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// mappingRequest is the wire shape POST /api/mappings and
|
||||
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
|
||||
// server-assigned, never taken from the request body.
|
||||
type mappingRequest struct {
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
Fields []mapping.Field `json:"fields"`
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
mappings, err := s.Mappings.ListMappings(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list mappings", "err", err)
|
||||
http.Error(w, "list mappings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"mappings": mappings})
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req mappingRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id, err := s.Mappings.InsertMapping(r.Context(), m)
|
||||
if err != nil {
|
||||
s.Log.Error("insert mapping", "err", err)
|
||||
http.Error(w, "create mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
if err != nil || created == nil {
|
||||
s.Log.Error("get mapping after insert", "err", err, "id", id)
|
||||
http.Error(w, "create mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, created)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingGet(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid mapping id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
if err != nil {
|
||||
s.Log.Error("get mapping", "err", err, "id", id)
|
||||
http.Error(w, "get mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if m == nil {
|
||||
http.Error(w, "mapping not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
writeJSON(w, m)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid mapping id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var req mappingRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
|
||||
if errors.Is(err, store.ErrMappingNotFound) {
|
||||
http.Error(w, "mapping not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.Log.Error("update mapping", "err", err, "id", id)
|
||||
http.Error(w, "update mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated, err := s.Mappings.GetMapping(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
s.Log.Error("get mapping after update", "err", err, "id", id)
|
||||
http.Error(w, "update mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid mapping id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.Mappings.DeleteMapping(r.Context(), id); err != nil {
|
||||
if errors.Is(err, store.ErrMappingNotFound) {
|
||||
http.Error(w, "mapping not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.Log.Error("delete mapping", "err", err, "id", id)
|
||||
http.Error(w, "delete mapping failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// mappingPreviewRequest lets an operator resolve a candidate set of fields
|
||||
// against a real captured event before saving anything -- Fields is loose
|
||||
// input, not a saved mapping ID, per docs/prds/payload-field-mapping.md.
|
||||
type mappingPreviewRequest struct {
|
||||
CaptureID int64 `json:"capture_id"`
|
||||
Fields []mapping.Field `json:"fields"`
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingPreview(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if s.Captures == nil {
|
||||
http.Error(w, "captures not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req mappingPreviewRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
capture, err := s.captureByID(r.Context(), req.CaptureID)
|
||||
if err != nil {
|
||||
s.Log.Error("get capture for preview", "err", err, "capture_id", req.CaptureID)
|
||||
http.Error(w, "preview failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if capture == nil {
|
||||
http.Error(w, "capture not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
values, failures := mapping.Resolve(req.Fields, []byte(capture.Body))
|
||||
if failures == nil {
|
||||
failures = []mapping.Failure{}
|
||||
}
|
||||
writeJSON(w, map[string]any{"values": values, "failures": failures})
|
||||
}
|
||||
|
||||
// captureByID finds one captured event by ID. CaptureStore exposes only
|
||||
// ListCaptures (see docs/prds/event-capture-storage.md -- capture has
|
||||
// exactly one reader, the dashboard list view, so a by-ID lookup was never
|
||||
// needed until preview), so this scans the newest window rather than
|
||||
// adding a new store method for a single low-volume caller.
|
||||
func (s *Server) captureByID(ctx context.Context, id int64) (*store.CapturedEvent, error) {
|
||||
captures, err := s.Captures.ListCaptures(ctx, mappingCaptureScanWindow(s.CaptureMaxEvents))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range captures {
|
||||
if captures[i].ID == id {
|
||||
return &captures[i], nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// captureScanWindowDefault bounds captureByID's linear scan when
|
||||
// CaptureMaxEvents is unset (zero or negative, matching CaptureConfig's own
|
||||
// "zero means default" convention). Matches CaptureConfig's documented
|
||||
// default so an unconfigured deployment's scan window still covers its
|
||||
// whole table.
|
||||
const captureScanWindowDefault = 5000
|
||||
|
||||
// mappingCaptureScanWindow ties captureByID's scan bound to the operator's
|
||||
// actual configured retention (CaptureMaxEvents), rather than a constant
|
||||
// that silently drifts out of sync with it -- an operator raising
|
||||
// [capture] max_events above the old hardcoded 5000 would otherwise make a
|
||||
// genuinely still-retained capture 404 as "not found" during preview.
|
||||
func mappingCaptureScanWindow(configuredMaxEvents int) int {
|
||||
if configuredMaxEvents <= 0 {
|
||||
return captureScanWindowDefault
|
||||
}
|
||||
return configuredMaxEvents
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// mappingTestServer builds a Server with both Mappings and Captures backed
|
||||
// by the same concrete *store.Store, so preview tests can insert a real
|
||||
// capture and resolve a mapping against it end to end.
|
||||
func mappingTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: s,
|
||||
Captures: s,
|
||||
}
|
||||
}
|
||||
|
||||
func doJSON(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var r *http.Request
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal request body: %v", err)
|
||||
}
|
||||
r = httptest.NewRequestWithContext(t.Context(), method, path, bytes.NewReader(b))
|
||||
} else {
|
||||
r = httptest.NewRequestWithContext(t.Context(), method, path, nil)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestHandleMappingCreateAndGet(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
var created mapping.Mapping
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
||||
t.Fatalf("unmarshal created mapping: %v", err)
|
||||
}
|
||||
if created.ID == 0 || created.Name != "sentry issue opened" {
|
||||
t.Fatalf("created mapping = %+v", created)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("get status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var got mapping.Mapping
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("unmarshal got mapping: %v", err)
|
||||
}
|
||||
if got.ID != created.ID || len(got.Fields) != 1 {
|
||||
t.Fatalf("got mapping = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingCreateRejectsInvalidMapping(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{"name": "", "fields": []mapping.Field{}})
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingGetMissingReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings/999", nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingsList(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
for range 3 {
|
||||
doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Mappings []mapping.Mapping `json:"mappings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(body.Mappings) != 3 {
|
||||
t.Fatalf("mappings = %d, want 3", len(body.Mappings))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingUpdate(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "orig",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+strconv.FormatInt(created.ID, 10), map[string]any{
|
||||
"name": "renamed",
|
||||
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil)
|
||||
var got mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &got)
|
||||
if got.Name != "renamed" || len(got.Fields) != 1 || got.Fields[0].Name != "b" {
|
||||
t.Fatalf("updated mapping = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPatch, "/api/mappings/999", map[string]any{
|
||||
"name": "x",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingDelete(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodDelete, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil)
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("delete status = %d, want %d; body = %s", w.Code, http.StatusNoContent, w.Body.String())
|
||||
}
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/mappings/"+strconv.FormatInt(created.ID, 10), nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("get after delete status = %d, want %d", w.Code, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingPreviewResolvesAgainstARealCapture(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
capID, err := srv.Captures.InsertCapture(t.Context(), store.CapturedEvent{
|
||||
Source: "sentry",
|
||||
Body: `{"issue":{"title":"bug found"},"count":3}`,
|
||||
}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture: %v", err)
|
||||
}
|
||||
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings/preview", map[string]any{
|
||||
"capture_id": capID,
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
{Name: "missing", Path: "nope", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("preview status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Values map[string]any `json:"values"`
|
||||
Failures []mapping.Failure `json:"failures"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if body.Values["title"] != "bug found" {
|
||||
t.Fatalf("values = %+v", body.Values)
|
||||
}
|
||||
if len(body.Failures) != 1 || body.Failures[0].FieldName != "missing" || body.Failures[0].Reason != mapping.ReasonMissing {
|
||||
t.Fatalf("failures = %+v", body.Failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingPreviewUnknownCaptureReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings/preview", map[string]any{
|
||||
"capture_id": 999,
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCaptureScanWindowUsesConfiguredCaptureMaxEvents(t *testing.T) {
|
||||
if got := mappingCaptureScanWindow(20000); got != 20000 {
|
||||
t.Errorf("mappingCaptureScanWindow(20000) = %d, want 20000", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCaptureScanWindowFallsBackWhenUnconfigured(t *testing.T) {
|
||||
if got := mappingCaptureScanWindow(0); got != captureScanWindowDefault {
|
||||
t.Errorf("mappingCaptureScanWindow(0) = %d, want default %d", got, captureScanWindowDefault)
|
||||
}
|
||||
if got := mappingCaptureScanWindow(-1); got != captureScanWindowDefault {
|
||||
t.Errorf("mappingCaptureScanWindow(-1) = %d, want default %d", got, captureScanWindowDefault)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleMappingsUnavailableWhenNotConfigured(t *testing.T) {
|
||||
srv := &Server{Store: nil, Log: slog.New(slog.DiscardHandler)}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,11 @@ type Server struct {
|
||||
// this via http.MaxBytesReader, before redaction or storage sees it.
|
||||
CaptureMaxBodyBytes int64
|
||||
|
||||
// Mappings persists payload field mappings (docs/prds/payload-field-mapping.md).
|
||||
// Optional: nil makes every /api/mappings route answer 503 rather than
|
||||
// the dashboard failing to start.
|
||||
Mappings store.MappingStore
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
}
|
||||
@@ -207,6 +212,12 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/work-requests", s.handleWorkRequest)
|
||||
mux.HandleFunc("GET /api/skills", s.handleSkills)
|
||||
mux.HandleFunc("GET /api/captures", s.handleCaptures)
|
||||
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
|
||||
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
|
||||
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
|
||||
mux.HandleFunc("PATCH /api/mappings/{id}", s.handleMappingUpdate)
|
||||
mux.HandleFunc("DELETE /api/mappings/{id}", s.handleMappingDelete)
|
||||
mux.HandleFunc("POST /api/mappings/preview", s.handleMappingPreview)
|
||||
mux.HandleFunc("GET /api/channels", s.handleChannels)
|
||||
mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload)
|
||||
mux.HandleFunc("GET /api/config", s.handleConfig)
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accenLine truncated
|
||||
:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accenLine truncated
|
||||
Vendored
+7
-7
@@ -1,12 +1,12 @@
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,chat:`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>`,tasks:`<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>`,logs:`<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>`,skills:`<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>`,workflows:`<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>`,memory:`<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>`,channels:`<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>`,captures:`<path d="M12 3v11M12 14l-4-4M12 14l4-4"/><path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4"/>`,settings:`<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>`,search:`<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>`,moon:`<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>`,sun:`<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>`,refresh:`<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>`,bell:`<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>`,trendUp:`<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>`,trendDown:`<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>`,check:`<path d="M4.5 12.5l5 5 10-11"/>`,help:`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>`};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),captures:e=>u(`/api/captures`+d({limit:e})),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`vLine truncated
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,chat:`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>`,tasks:`<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>`,logs:`<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>`,skills:`<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>`,workflows:`<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>`,memory:`<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>`,channels:`<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>`,captures:`<path d="M12 3v11M12 14l-4-4M12 14l4-4"/><path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4"/>`,mappings:`<circle cx="5" cy="7" r="2"/><circle cx="5" cy="17" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 7l10 5M7 17l10-5"/>`,settings:`<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>`,search:`<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>`,moon:`<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>`,sun:`<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>`,refresh:`<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>`,bell:`<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>`,trendUp:`<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>`,trendDown:`<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>`,check:`<path d="M4.5 12.5l5 5 10-11"/>`,help:`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>`};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`r
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),captures:e=>u(`/api/captures`+d({limit:e})),mappings:()=>u(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chat
Line truncated
|
||||
<path d="${l(150,240)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${l(150,240)}" fill="none" stroke="${a}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${c}"
|
||||
stroke-dashoffset="${c*(1-i/100)}"
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function
Line truncated
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function
Line truncated
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
@@ -71,10 +71,10 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;function Be(){let e=document.createElement(`template`);e.innerHTML=ze.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function Ve(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`;function Ye(){let e=document.createElement(`template`);e.innerHTML=Je.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function Xe(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`),i=[],a=null,o=null,s=()=>{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;t<r.length;t++){let l=r[t];if(l.startsWith("```")){s(),c(),o?(n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1<r.length?Y(r[t+1]):null;if(u&&d&&He(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=Y(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function He(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Ue(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function We(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function Ge(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Ve(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Ve(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function Ke(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),qe(t).append(o),o}function qe(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var Je=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Je);return e||(e=crypto.randomUUID(),localStorage.setItem(Je,e)),e}function Ye(e){return{text:e,sourceID:crypto.randomUUID()}}function Xe(e){return{...e}}function Ze(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Xe(e.turn):Ye(r),isRetry:n}}function Qe({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Ue(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function $e(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,et(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function et(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function tt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function nt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function rt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function it(e){return e?.status===501?null:`Could not check for updates.`}function at(){let{root:t,refs:n}=Be(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,up
Line truncated
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1<r.length?Y(r[t+1]):null;if(u&&d&&Ze(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=Y(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Ze(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Qe(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function $e(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function et(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Xe(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Xe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function tt(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),nt(t).append(o),o}function nt(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var rt=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(rt);return e||(e=crypto.randomUUID(),localStorage.setItem(rt,e)),e}function it(e){return{text:e,sourceID:crypto.randomUUID()}}function at(e){return{...e}}function ot(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?at(e.turn):it(r),isRetry:n}}function st({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Qe(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ct(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,lt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function lt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function ut(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function dt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function ft(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function pt(e){return e?.status===501?null:`Could not check for updates.`}function mt(){let{root:t,refs:n}=Ye(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,up
Line truncated
|
||||
|
||||
`);i=a.pop()||``;for(let e of a){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&Ke(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=Xe(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{et({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:at},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:we},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Fe},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ie},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:le}],ot=`archie.theme`;function st(e){document.documentElement.dataset.theme=e,localStorage.setItem(ot,e)}function $(){return localStorage.getItem(ot)||`dark`}function ct(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{st($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function lt(){st($());let t=e(`main.main`),r=ct(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?
Line truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&tt(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=at(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{lt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:mt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:we},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Fe},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:We},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ge},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:le}],ht=`archie.theme`;function gt(e){document.documentElement.dataset.theme=e,localStorage.setItem(ht,e)}function $(){return localStorage.getItem(ht)||`dark`}function _t(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{gt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function vt(){gt($());let t=e(`main.main`),r=_t(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?Line truncated
|
||||
@@ -108,6 +108,45 @@ export const api = {
|
||||
},
|
||||
logs: (params) => req("/api/logs" + qs(params)),
|
||||
captures: (limit) => req("/api/captures" + qs({ limit })),
|
||||
mappings: () => req("/api/mappings"),
|
||||
mappingCreate: async (mapping) => {
|
||||
const res = await fetch("/api/mappings", {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify(mapping),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
mappingUpdate: async (id, mapping) => {
|
||||
const res = await fetch(`/api/mappings/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify(mapping),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
mappingDelete: async (id) => {
|
||||
const res = await fetch(`/api/mappings/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: { Accept: "application/json", "X-Archie-CSRF": "1" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
},
|
||||
mappingPreview: async (captureId, fields) => {
|
||||
const res = await fetch("/api/mappings/preview", {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify({ capture_id: captureId, fields }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
memory: () => req("/api/memory"),
|
||||
chatSessions: () => req("/api/chat/sessions"),
|
||||
chatMessages: (id) => req(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
|
||||
|
||||
@@ -17,6 +17,7 @@ const paths = {
|
||||
memory: '<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>',
|
||||
channels: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>',
|
||||
captures: '<path d="M12 3v11M12 14l-4-4M12 14l4-4"/><path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4"/>',
|
||||
mappings: '<circle cx="5" cy="7" r="2"/><circle cx="5" cy="17" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 7l10 5M7 17l10-5"/>',
|
||||
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',
|
||||
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>',
|
||||
moon: '<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>',
|
||||
|
||||
@@ -9,6 +9,7 @@ import { channelsPage } from "./channels/channels.js";
|
||||
import { settingsPage } from "./settings/settings.js";
|
||||
import { logsPage } from "./logs/logs.js";
|
||||
import { capturesPage } from "./captures/captures.js";
|
||||
import { mappingsPage } from "./mappings/mappings.js";
|
||||
import { memoryPage } from "./memory/memory.js";
|
||||
import { chatPage } from "./chat/chat.js";
|
||||
|
||||
@@ -26,6 +27,7 @@ const routes = [
|
||||
{ path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage },
|
||||
{ path: "/logs", label: "Logs", icon: "logs", view: logsPage },
|
||||
{ path: "/captures", label: "Event inspector", icon: "captures", view: capturesPage },
|
||||
{ path: "/mappings", label: "Field mappings", icon: "mappings", view: mappingsPage },
|
||||
{ path: "/skills", label: "Skills", icon: "skills", view: skillsPage },
|
||||
{ path: "/workflows", label: "Workflows", icon: "workflows", view: workflowsPage },
|
||||
{ path: "/memory", label: "Memory", icon: "memory", view: memoryPage },
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { el, pill } from "../base/dom.js";
|
||||
|
||||
/**
|
||||
* Pure rendering + path/type logic for the mapping editor, split out from
|
||||
* mappings.js so it is unit-testable without the page's fetch wiring,
|
||||
* mirroring captures/capture-row.js.
|
||||
*/
|
||||
|
||||
const FIELD_TYPES = ["string", "number", "bool", "object", "array", "any"];
|
||||
|
||||
/** Infers the FieldType a freshly-clicked example value suggests. */
|
||||
export function fieldTypeFromValue(value) {
|
||||
if (value === null || value === undefined) return "any";
|
||||
if (Array.isArray(value)) return "array";
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
return "string";
|
||||
case "number":
|
||||
return "number";
|
||||
case "boolean":
|
||||
return "bool";
|
||||
case "object":
|
||||
return "object";
|
||||
default:
|
||||
return "any";
|
||||
}
|
||||
}
|
||||
|
||||
export function pathAppendKey(path, key) {
|
||||
return path ? `${path}.${key}` : key;
|
||||
}
|
||||
|
||||
export function pathAppendIndex(path, index) {
|
||||
return `${path}[${index}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders payload as a clickable tree: every key/index and every leaf calls
|
||||
* onPick({ path, type, name }) when clicked, so the editor can bind a field
|
||||
* without the operator ever typing a JSON path by hand -- "click through
|
||||
* its payload, bind JSON paths" per docs/prds/payload-field-mapping.md.
|
||||
*/
|
||||
export function payloadTree(value, { path = "", name = "", onPick } = {}) {
|
||||
if (value !== null && typeof value === "object") {
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((v, i) => [String(i), v, pathAppendIndex(path, i)])
|
||||
: Object.entries(value).map(([k, v]) => [k, v, pathAppendKey(path, k)]);
|
||||
return el(
|
||||
"ul.mapping-tree-list",
|
||||
...entries.map(([key, child, childPath]) =>
|
||||
el(
|
||||
"li.mapping-tree-item",
|
||||
el(
|
||||
"span.mapping-tree-key",
|
||||
{ onclick: (e) => { e.stopPropagation(); onPick?.({ path: childPath, type: fieldTypeFromValue(child), name: key }); } },
|
||||
key,
|
||||
),
|
||||
payloadTree(child, { path: childPath, name: key, onPick }),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return el(
|
||||
"span.mapping-tree-value",
|
||||
{ onclick: (e) => { e.stopPropagation(); onPick?.({ path, type: fieldTypeFromValue(value), name }); } },
|
||||
JSON.stringify(value),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the bound-fields table. preview is { values, failures } | null --
|
||||
* null means "not previewed yet" and every row shows a neutral status
|
||||
* rather than a false pass, since an unresolved field is not the same
|
||||
* claim as a resolved one.
|
||||
*/
|
||||
export function fieldsTable(fields, { preview, onRemove, onNameChange, onTypeChange, onRequiredChange } = {}) {
|
||||
if (!fields.length) {
|
||||
return el("div.mapping-empty-fields", "Click a value in the payload to bind a field.");
|
||||
}
|
||||
const failureByField = new Map((preview?.failures || []).map((f) => [f.field_name, f]));
|
||||
return el(
|
||||
"table.table.mapping-fields-table",
|
||||
el(
|
||||
"thead",
|
||||
el("tr", ...["Field name", "Path", "Type", "Required", "Preview", ""].map((h) => el("th", h))),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...fields.map((f, i) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td", el("input.mapping-input", {
|
||||
value: f.name,
|
||||
oninput: (e) => onNameChange?.(i, e.target.value),
|
||||
})),
|
||||
el("td.mono", f.path),
|
||||
el(
|
||||
"td",
|
||||
el(
|
||||
"select.mapping-select",
|
||||
{ onchange: (e) => onTypeChange?.(i, e.target.value) },
|
||||
...FIELD_TYPES.map((t) => el("option", { value: t, selected: t === f.type }, t)),
|
||||
),
|
||||
),
|
||||
el("td", el("input", {
|
||||
type: "checkbox",
|
||||
checked: f.required,
|
||||
onchange: (e) => onRequiredChange?.(i, e.target.checked),
|
||||
})),
|
||||
el("td", previewStatus(f, preview, failureByField)),
|
||||
el("td", el("button.btn.btn-small", { type: "button", onclick: () => onRemove?.(i) }, "Remove")),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function previewStatus(field, preview, failureByField) {
|
||||
if (!preview) return pill("not previewed", "idle");
|
||||
const failure = failureByField.get(field.name);
|
||||
if (failure) return pill(failure.reason, "danger");
|
||||
if (Object.prototype.hasOwnProperty.call(preview.values || {}, field.name)) {
|
||||
return pill(JSON.stringify(preview.values[field.name]), "ok");
|
||||
}
|
||||
return pill("skipped (optional)", "idle");
|
||||
}
|
||||
|
||||
/** One saved mapping's summary row for the mapping list. */
|
||||
export function mappingRow(m, { onEdit, onDelete }) {
|
||||
return el(
|
||||
"tr",
|
||||
el("td", m.name),
|
||||
el("td.mono", m.source_hint || "—"),
|
||||
el("td", String(m.fields?.length ?? 0)),
|
||||
el(
|
||||
"td",
|
||||
el("button.btn.btn-small", { type: "button", onclick: () => onEdit?.(m) }, "Edit"),
|
||||
el("button.btn.btn-small", { type: "button", onclick: () => onDelete?.(m) }, "Delete"),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/* Field mapping editor: bind named fields to JSON paths by clicking a
|
||||
captured event's payload, then preview the resolution before saving. */
|
||||
|
||||
.mapping-form,
|
||||
.mapping-fields,
|
||||
.mapping-payload {
|
||||
margin-bottom: var(--sp-4);
|
||||
padding: var(--sp-4);
|
||||
}
|
||||
|
||||
.mapping-form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-1);
|
||||
margin-bottom: var(--sp-3);
|
||||
font-size: var(--text-sm);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
.mapping-input,
|
||||
.mapping-select {
|
||||
padding: var(--sp-2);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-raised);
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.mapping-section-title {
|
||||
font-size: var(--text-xs);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--fg-subtle);
|
||||
margin-bottom: var(--sp-2);
|
||||
}
|
||||
|
||||
.mapping-fields-table .mapping-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mapping-empty-fields {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--text-sm);
|
||||
padding: var(--sp-3) 0;
|
||||
}
|
||||
|
||||
.mapping-error {
|
||||
color: var(--danger, #e5484d);
|
||||
font-size: var(--text-sm);
|
||||
margin-bottom: var(--sp-3);
|
||||
}
|
||||
|
||||
.mapping-tree-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding-left: var(--sp-4);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.mapping-tree-item {
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.mapping-tree-key,
|
||||
.mapping-tree-value {
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.mapping-tree-key:hover,
|
||||
.mapping-tree-value:hover {
|
||||
background: var(--bg-raised);
|
||||
outline: 1px solid var(--accent);
|
||||
}
|
||||
|
||||
.mapping-tree-value {
|
||||
color: var(--fg-subtle);
|
||||
margin-left: var(--sp-1);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import "./mappings.css";
|
||||
import { api } from "../base/api.js";
|
||||
import { el, empty, mount } from "../base/dom.js";
|
||||
import { fieldsTable, mappingRow, payloadTree } from "./mapping-editor.js";
|
||||
|
||||
/**
|
||||
* Payload field mapping (t2db.3): bind named fields to JSON paths inside a
|
||||
* real captured event, preview the resolution before saving, and manage
|
||||
* saved mappings. See docs/prds/payload-field-mapping.md. t2db.4 (binding
|
||||
* a mapping + matcher to a workflow) is a separate, not-yet-built page --
|
||||
* this one only produces the mapping entity and its preview.
|
||||
*/
|
||||
export function mappingsPage() {
|
||||
const root = el("div");
|
||||
|
||||
let mappings = [];
|
||||
let captures = [];
|
||||
let loadError = null;
|
||||
let editor = null;
|
||||
|
||||
render();
|
||||
load();
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [mRes, cRes] = await Promise.all([api.mappings(), api.captures(100)]);
|
||||
mappings = mRes.mappings || [];
|
||||
captures = cRes.captures || [];
|
||||
loadError = null;
|
||||
} catch (err) {
|
||||
loadError = String(err.message || err);
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
function startCreate() {
|
||||
editor = { id: null, name: "", sourceHint: "", fields: [], captureId: null, payload: null, payloadError: null, preview: null, actionError: null };
|
||||
render();
|
||||
}
|
||||
|
||||
function startEdit(m) {
|
||||
editor = {
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
sourceHint: m.source_hint || "",
|
||||
fields: (m.fields || []).map((f) => ({ ...f })),
|
||||
captureId: null,
|
||||
payload: null,
|
||||
payloadError: null,
|
||||
preview: null,
|
||||
actionError: null,
|
||||
};
|
||||
render();
|
||||
}
|
||||
|
||||
async function remove(m) {
|
||||
if (!window.confirm(`Delete mapping "${m.name}"?`)) return;
|
||||
try {
|
||||
await api.mappingDelete(m.id);
|
||||
await load();
|
||||
} catch (err) {
|
||||
loadError = String(err.message || err);
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
function selectCapture(captureId) {
|
||||
const c = captures.find((c) => String(c.id) === String(captureId));
|
||||
editor.captureId = c ? c.id : null;
|
||||
editor.preview = null;
|
||||
if (!c) {
|
||||
editor.payload = null;
|
||||
editor.payloadError = null;
|
||||
} else {
|
||||
try {
|
||||
editor.payload = JSON.parse(c.body);
|
||||
editor.payloadError = null;
|
||||
} catch {
|
||||
editor.payload = null;
|
||||
editor.payloadError = "This capture's body is not valid JSON, so its fields cannot be mapped by path.";
|
||||
}
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
function addField({ path, type, name }) {
|
||||
const existing = new Set(editor.fields.map((f) => f.name));
|
||||
let candidate = name || "field";
|
||||
let n = 1;
|
||||
while (existing.has(candidate)) candidate = `${name || "field"}_${++n}`;
|
||||
editor.fields.push({ name: candidate, path, type, required: true });
|
||||
editor.preview = null;
|
||||
render();
|
||||
}
|
||||
|
||||
function removeField(i) {
|
||||
editor.fields.splice(i, 1);
|
||||
editor.preview = null;
|
||||
render();
|
||||
}
|
||||
|
||||
// Every field mutation goes through here so a stale preview can never be
|
||||
// shown against fields it wasn't actually resolved against -- see
|
||||
// docs/prds/payload-field-mapping.md's "never show a mapping the operator
|
||||
// has not seen resolve against real data."
|
||||
function mutateField(i, patch) {
|
||||
Object.assign(editor.fields[i], patch);
|
||||
editor.preview = null;
|
||||
render();
|
||||
}
|
||||
|
||||
const renameField = (i, name) => mutateField(i, { name });
|
||||
const retypeField = (i, type) => mutateField(i, { type });
|
||||
const requireField = (i, required) => mutateField(i, { required });
|
||||
|
||||
async function preview() {
|
||||
if (!editor.captureId) {
|
||||
editor.actionError = "Pick a captured event to preview against.";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
editor.preview = await api.mappingPreview(editor.captureId, editor.fields);
|
||||
editor.actionError = null;
|
||||
} catch (err) {
|
||||
editor.actionError = String(err.message || err);
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const body = { name: editor.name, source_hint: editor.sourceHint, fields: editor.fields };
|
||||
try {
|
||||
if (editor.id) {
|
||||
await api.mappingUpdate(editor.id, body);
|
||||
} else {
|
||||
await api.mappingCreate(body);
|
||||
}
|
||||
editor = null;
|
||||
await load();
|
||||
} catch (err) {
|
||||
editor.actionError = String(err.message || err);
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
editor = null;
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
mount(root, editor ? renderEditor() : renderList());
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
return el(
|
||||
"div",
|
||||
el(
|
||||
"div.page-head",
|
||||
el(
|
||||
"div",
|
||||
el("h1.page-title", "Field mappings"),
|
||||
el("p.page-sub", "Bind named fields to JSON paths from a real captured event, ready for a playbook binding."),
|
||||
),
|
||||
el("div.page-actions", el("button.btn.btn-primary", { type: "button", onclick: startCreate }, "New mapping")),
|
||||
),
|
||||
loadError
|
||||
? empty("Cannot reach archied", loadError)
|
||||
: mappings.length
|
||||
? el(
|
||||
"div.card",
|
||||
el(
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Name", "Source hint", "Fields", ""].map((h) => el("th", h)))),
|
||||
el("tbody", ...mappings.map((m) => mappingRow(m, { onEdit: startEdit, onDelete: remove }))),
|
||||
),
|
||||
),
|
||||
)
|
||||
: empty("No mappings yet", "Create one from a captured event to reuse fields in a future playbook binding."),
|
||||
);
|
||||
}
|
||||
|
||||
function renderEditor() {
|
||||
return el(
|
||||
"div",
|
||||
el(
|
||||
"div.page-head",
|
||||
el("div", el("h1.page-title", editor.id ? "Edit mapping" : "New mapping")),
|
||||
el(
|
||||
"div.page-actions",
|
||||
el("button.btn", { type: "button", onclick: cancel }, "Cancel"),
|
||||
el("button.btn.btn-primary", { type: "button", onclick: save }, "Save"),
|
||||
),
|
||||
),
|
||||
editor.actionError ? el("div.mapping-error", editor.actionError) : null,
|
||||
el(
|
||||
"div.card.mapping-form",
|
||||
el(
|
||||
"label.mapping-form-row",
|
||||
"Name",
|
||||
el("input.mapping-input", {
|
||||
value: editor.name,
|
||||
oninput: (e) => { editor.name = e.target.value; },
|
||||
}),
|
||||
),
|
||||
el(
|
||||
"label.mapping-form-row",
|
||||
"Source hint (organisational only)",
|
||||
el("input.mapping-input", {
|
||||
value: editor.sourceHint,
|
||||
oninput: (e) => { editor.sourceHint = e.target.value; },
|
||||
}),
|
||||
),
|
||||
el(
|
||||
"label.mapping-form-row",
|
||||
"Preview against captured event",
|
||||
el(
|
||||
"select.mapping-select",
|
||||
{ onchange: (e) => selectCapture(e.target.value) },
|
||||
el("option", { value: "" }, "— pick a captured event —"),
|
||||
...captures.map((c) =>
|
||||
el("option", { value: c.id, selected: String(editor.captureId) === String(c.id) },
|
||||
`${c.source || "(unknown)"} — ${c.received_at || ""}`),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
el(
|
||||
"div.card.mapping-fields",
|
||||
el("div.mapping-section-title", "Bound fields"),
|
||||
fieldsTable(editor.fields, {
|
||||
preview: editor.preview,
|
||||
onRemove: removeField,
|
||||
onNameChange: renameField,
|
||||
onTypeChange: retypeField,
|
||||
onRequiredChange: requireField,
|
||||
}),
|
||||
el("button.btn", { type: "button", onclick: preview }, "Preview"),
|
||||
),
|
||||
el(
|
||||
"div.card.mapping-payload",
|
||||
el("div.mapping-section-title", "Payload — click a value to bind it"),
|
||||
editor.payloadError
|
||||
? el("div.mapping-error", editor.payloadError)
|
||||
: editor.payload !== null
|
||||
? payloadTree(editor.payload, { onPick: addField })
|
||||
: el("div.mapping-empty-fields", "Pick a captured event above to see its payload."),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import {
|
||||
fieldTypeFromValue,
|
||||
fieldsTable,
|
||||
mappingRow,
|
||||
pathAppendIndex,
|
||||
pathAppendKey,
|
||||
payloadTree,
|
||||
} from "../src/mappings/mapping-editor.js";
|
||||
|
||||
test("fieldTypeFromValue infers a FieldType from an example value", () => {
|
||||
assert.equal(fieldTypeFromValue("x"), "string");
|
||||
assert.equal(fieldTypeFromValue(1), "number");
|
||||
assert.equal(fieldTypeFromValue(true), "bool");
|
||||
assert.equal(fieldTypeFromValue({}), "object");
|
||||
assert.equal(fieldTypeFromValue([]), "array");
|
||||
assert.equal(fieldTypeFromValue(null), "any");
|
||||
assert.equal(fieldTypeFromValue(undefined), "any");
|
||||
});
|
||||
|
||||
test("pathAppendKey joins with a dot, or starts fresh from an empty path", () => {
|
||||
assert.equal(pathAppendKey("", "issue"), "issue");
|
||||
assert.equal(pathAppendKey("issue", "title"), "issue.title");
|
||||
});
|
||||
|
||||
test("pathAppendIndex appends a bracketed index", () => {
|
||||
assert.equal(pathAppendIndex("items", 0), "items[0]");
|
||||
assert.equal(pathAppendIndex("", 2), "[2]");
|
||||
});
|
||||
|
||||
test("payloadTree renders every object key", () => {
|
||||
const tree = payloadTree({ issue: { title: "bug found" }, count: 3 });
|
||||
assert.match(tree.textContent, /issue/);
|
||||
assert.match(tree.textContent, /title/);
|
||||
assert.match(tree.textContent, /"bug found"/);
|
||||
assert.match(tree.textContent, /count/);
|
||||
assert.match(tree.textContent, /3/);
|
||||
});
|
||||
|
||||
test("payloadTree renders array indices", () => {
|
||||
const tree = payloadTree({ items: [{ id: 1 }, { id: 2 }] });
|
||||
assert.match(tree.textContent, /items/);
|
||||
assert.match(tree.textContent, /id/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows a hint instead of a table when there are no fields", () => {
|
||||
const node = fieldsTable([], {});
|
||||
assert.match(node.textContent, /Click a value in the payload/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows 'not previewed' for every field before a preview runs", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, { preview: null });
|
||||
assert.match(node.textContent, /not previewed/);
|
||||
});
|
||||
|
||||
test("fieldsTable surfaces a resolved value after a successful preview", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, { preview: { values: { title: "bug found" }, failures: [] } });
|
||||
assert.match(node.textContent, /bug found/);
|
||||
assert.doesNotMatch(node.textContent, /not previewed/);
|
||||
});
|
||||
|
||||
test("fieldsTable surfaces a failure reason loudly, never a blank value", () => {
|
||||
const fields = [{ name: "title", path: "issue.title", type: "string", required: true }];
|
||||
const node = fieldsTable(fields, {
|
||||
preview: { values: {}, failures: [{ field_name: "title", path: "issue.title", reason: "missing" }] },
|
||||
});
|
||||
assert.match(node.textContent, /missing/);
|
||||
});
|
||||
|
||||
test("fieldsTable shows every bound field's name and path", () => {
|
||||
const fields = [
|
||||
{ name: "title", path: "issue.title", type: "string", required: true },
|
||||
{ name: "count", path: "count", type: "number", required: false },
|
||||
];
|
||||
const node = fieldsTable(fields, { preview: null });
|
||||
assert.match(node.textContent, /issue\.title/);
|
||||
assert.match(node.textContent, /count/);
|
||||
});
|
||||
|
||||
test("mappingRow shows name, source hint, and field count", () => {
|
||||
const row = mappingRow(
|
||||
{ id: 1, name: "sentry issue opened", source_hint: "sentry", fields: [{}, {}] },
|
||||
{ onEdit: () => {}, onDelete: () => {} },
|
||||
);
|
||||
assert.match(row.textContent, /sentry issue opened/);
|
||||
assert.match(row.textContent, /sentry/);
|
||||
assert.match(row.textContent, /2/);
|
||||
});
|
||||
|
||||
test("mappingRow shows a placeholder when there is no source hint", () => {
|
||||
const row = mappingRow({ id: 1, name: "m", fields: [] }, { onEdit: () => {}, onDelete: () => {} });
|
||||
assert.match(row.textContent, /—/);
|
||||
});
|
||||
Reference in new issue
Block a user