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:
sam committed 2026-08-22 19:18:15 +10:00
1 parent c7987f0595
commit aba035a396
22 files changed
+2143 -13

No files matched your search

+39
View File
@@ -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`),
+1
View File
@@ -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"/>',
+2
View File
@@ -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 },
+141
View File
@@ -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"),
),
);
}
+82
View File
@@ -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);
}
+256
View File
@@ -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;
}