File size: 32,769 Bytes
4cfab62
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
4cfab62
 
ce9586e
 
 
4cfab62
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
 
4cfab62
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
816fa8a
ce9586e
 
 
816fa8a
8cbc29f
ce9586e
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
4cfab62
 
 
 
816fa8a
4cfab62
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
4cfab62
e174d2c
4cfab62
 
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
 
 
 
 
 
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// Query's public contract.  Assistant owns the conversation; Query owns only the
// immutable, per-user artefacts the conversation creates.
import { API_V1, CREDENTIALS } from "../apiContract";

export type Result<T> =
  | { ok: true; value: T }
  | { ok: false; status: number; message: string; code?: string; sentence?: string };

/** C2: the one sentence a failed or refused Assistant turn shows, per server code. */
export const REFUSAL_SENTENCES: Readonly<Record<string, string>> = {
  assistant_forbidden: "You do not have access to that database.",
  query_source_unavailable: "That source is still syncing. Try again in a few minutes.",
  source_needs_filter: "That question needs every row at once. Add a filter or ask for a total.",
  provider_unreachable: "The model did not answer. Try again in a moment.",
  provider_limited: "The model is busy. Your answer resumes shortly.",
  store_unavailable: "Loopable could not reach its store. Try again in a moment.",
  question_too_long: "That question is too long. Shorten it and send it again.",
  semantic_field_unapproved: "That field is not approved for answers yet. Ask an Administrator.",
  session_expired: "Your session ended. Sign in again.",
};
export const REFUSAL_FALLBACK = "This database could not answer right now. Please try again.";

/** C2: an unknown code or no code reads as the fallback sentence. */
export function refusalSentence(code?: string): string {
  return code && Object.prototype.hasOwnProperty.call(REFUSAL_SENTENCES, code)
    ? REFUSAL_SENTENCES[code] : REFUSAL_FALLBACK;
}

/** C2 does not fix where the pair sits: read the top level, then `error`, then `detail`. */
export function refusalPair(body: unknown): { code?: string; message?: string } {
  const row = body && typeof body === "object" ? body as Record<string, unknown> : {};
  const layer = (value: unknown) => value && typeof value === "object" ? value as Record<string, unknown> : {};
  const detail = layer(row.detail);
  const layers = [row, layer(row.error), detail, layer(detail.error)];
  const first = (key: string) => layers.map((item) => item[key])
    .find((value): value is string => typeof value === "string" && value.length > 0);
  return { code: first("code"), message: first("message") };
}

export interface QuerySource {
  database: string;
  label: string;
  source_kind: string;
  source_version: unknown;
  retrieved_at: string;
  fields: Array<{ key: string; label?: string; type?: string }>;
  filters: unknown;
  permission_scope_applied: boolean;
}

export interface QueryCitation {
  id: string;
  href: string;
  database: string;
  snapshot: { kind: string; version: unknown };
  fields: string[];
  filters: unknown;
  permission_scope_applied: boolean;
  aggregation: { op: string; field?: string | null };
  contributing_record_count: number;
  retrieved_at: string;
}

export interface SavedQuery {
  id: string;
  viewId: string;
  scope: string;
  name: string;
  /** R20: a label the reader owns. The SPEC beside it stays immutable, which is the whole split. */
  description: string;
  kind: string;
  question: string;
  explain: string;
  threadId: string;
  createdAt: string;
  virtual: true;
  source: QuerySource;
  view: Record<string, unknown>;
  citationIds: string[];
  numeric: { label: string; value: number | null; contributing_record_count: number };
  /**
   * ⭐⭐ W35-T25 Β· CONTRACT C4 (R3) β€” THE AI'S OWN SPEC, AND WHETHER THIS ONE STILL MATCHES IT.
   *
   * `original_spec` is written ONCE, at creation, and is what "Revert to AI original" restores.
   * `edited` is DERIVED on the server by comparing the two, never stored β€” so a revert clears the
   * badge by construction rather than by remembering to.
   *
   * β›” `null` IS A REAL ANSWER AND THE CLIENT MUST HONOUR IT. An artefact created before this wave
   * has no original: it reports `edited: false` and offers no Revert. C4 is explicit that a Revert
   * with nothing to revert to is worse than an absent one.
   * ⚠ The snake_case key is contract C4's own spelling, not a slip. It is the wire name both
   * halves were specified against and renaming it here would be a silent one-sided change.
   */
  original_spec: Record<string, unknown> | null;
  edited: boolean;
}

export interface QueryThread {
  id: string;
  title: string;
  createdAt: string;
  updatedAt: string;
  sources: string[];
  model: string;
  activeViewId?: string;
}

export interface QueryMessage {
  id: string;
  threadId: string;
  role: "user" | "assistant";
  content: string;
  createdAt: string;
  targetDatabase?: string;
  sources?: string[];
  requestedModel?: string;
  model?: string | null;
  reason?: string | null;
  viewId?: string | null;
  citationIds?: string[];
  numeric?: SavedQuery["numeric"] | null;
  /** R20's thumbs. Read by the server's own replay, not only written. */
  provenance?: AnswerProvenance;
  rating?: "up" | "down" | null;
  ratingReason?: string;
  toolCalls?: AgentToolCall[];
  pendingDelete?: ArtifactPendingDelete | null;
  artifacts?: string[];
}

/** The answer basis is a disclosure, never a grant. */
export type AnswerBasis = "authorized_app_data" | "retrieved_knowledge" | "model_guidance";

export interface AnswerProvenance {
  basis: AnswerBasis;
  /** Opaque ids are resolved only against the caller's already-permitted citations. */
  citationIds: string[];
  modelGuidance: boolean;
  /** A stable explanation when no permitted source can be named. */
  noneUsedReason?: string;
}

/**
 * This sentence is deliberately not inferred from a question, database, record, or citation id.
 * It is the deterministic, truthful fallback when a response has no permitted source to show.
 */
export const NO_CITED_SOURCES_REASON =
  "No authorized application data or retrieved knowledge was cited for this answer.";

/**
 * The only user-facing source footer.  Source names and opaque ids never cross this boundary:
 * callers may resolve ids to citations they can already see, but the footer states the basis only.
 */
export function answerSourceFooter(
  provenance: AnswerProvenance | undefined,
  permittedCitations: QueryCitation[],
): string {
  if (permittedCitations.length && provenance?.basis === "authorized_app_data") {
    return provenance.modelGuidance
      ? "Sources: Authorized application data; model guidance composed the answer."
      : "Sources: Authorized application data.";
  }
  if (permittedCitations.length && provenance?.basis === "retrieved_knowledge") {
    return provenance.modelGuidance
      ? "Sources: Retrieved knowledge; model guidance composed the answer."
      : "Sources: Retrieved knowledge.";
  }
  const noneUsed = provenance?.noneUsedReason || NO_CITED_SOURCES_REASON;
  return provenance?.modelGuidance
    ? `Sources: ${noneUsed} Model guidance only.`
    : `Sources: ${noneUsed}`;
}

/**
 * A source this caller HOLDS, and whether it can actually be asked.
 *
 * ⭐ `permitted` and `answerable` are different questions and the picker needs the second.
 * Measured on tenant #0: twelve chips offered, two answerable β€” the rest are the `ut_odoo_*`
 * grids, whose rows live uncapped in the connector mirror and are read THROUGH it, which the
 * Assistant's read boundary refuses by design. `reason` is what the chip says instead of making
 * the reader spend a prompt to find out.
 */
export interface QuerySourceStatus {
  database: string;
  answerable: boolean;
  reason: string;
}

/**
 * A model this deployment OFFERS, and whether it can actually be called.
 *
 * ⭐ The same shape `QuerySourceStatus` uses, for the same reason one control to the left: a
 * picker that lists a model whose key is not set spends a click and a turn to be told
 * "unavailable" by a server that knew before the click.
 */
export interface QueryModelStatus {
  model: string;
  available: boolean;
  reason: string;
  /**
   * ⭐⭐ CONTRACT C5 (W36-T35, published by session E) β€” THE THREE DECLARATIONS A PICKER NEEDS.
   *
   * β›” `toolCalling` IS WHY W36-T34's `done-when` IS EXPRESSIBLE AT ALL: *"a model the ladder
   * declares incapable of tool calling is not offered for a tool-calling turn."* That sentence
   * needs a DECLARATION to read, not a runtime guess β€” the retired `_FAILED_GEN` regex, which
   * recovered a tool call out of a 400, is the evidence that guessing failed
   * [[permitted-is-not-answerable]].
   * ⚠ `outOfCredit` IS NOT THE SAME AS `!available`, and collapsing them loses R4's whole point:
   * an empty balance is a thing somebody can FIX today, while "not configured on this deployment"
   * is a thing they must ask an admin about. The server sends a distinct `reason` for each.
   * ⚠ ALL THREE DEFAULT PERMISSIVELY on an older server that omits them, for the reason the
   * `available` parse states one field up: a missing field must not disable a whole picker.
   */
  toolCalling: boolean;
  jsonMode: boolean;
  outOfCredit: boolean;
}

export interface QueryIndex {
  threads: QueryThread[];
  messages: QueryMessage[];
  views: SavedQuery[];
  citations: QueryCitation[];
  models: string[];
  modelStatus: QueryModelStatus[];
  sources: QuerySourceStatus[];
}

export interface ChatResult {
  thread: QueryThread;
  userMessage: QueryMessage;
  message: QueryMessage;
  view: SavedQuery | null;
  citations: QueryCitation[];
  toolCalls: AgentToolCall[];
  pendingDelete: ArtifactPendingDelete | null;
  artifacts: string[];
}

export interface ArtifactToolCall {
  name: string; args: Record<string, unknown>;
}
export interface AgentToolCall extends ArtifactToolCall {
  effect: "read" | "write" | "delete"; ok: boolean; ref: string | null;
}
export interface ArtifactPendingDelete { id: string; summary: string; expiresAt: string | number; }
export interface ArtifactTurnResult {
  reply: string; refused: string | null; toolCalls: AgentToolCall[];
  pendingDelete: ArtifactPendingDelete | null; artifacts: string[];
}
export interface AssistantArtifact {
  id: string; kind: "view" | "sheet" | "report" | "run" | "query" | "schedule" | "pdf" | "xlsx" | "image" | "snapshot";
  title: string; ref: string | null; door: "app" | "whatsapp" | "wake";
  createdAt: string; status: "active" | "paused" | "deleted";
  toolCall: ArtifactToolCall;
  file_id?: string; mime?: string; link?: string; frozen_at?: string;
  actions: Array<"open" | "run" | "pause" | "resume" | "rename" | "delete">;
}
export interface ArtifactIndex { items: AssistantArtifact[]; nextCursor: string | null; }

/** The cross-fence B contract: source reads and virtual workspace writes are separate. */
export interface QueryVirtualBinding {
  artifactId: string;
  dataScope: string;
  workspaceBinding: { kind: "query"; key: string };
  mutation: QueryMutationPolicy;
  source: QuerySource;
  view: Record<string, unknown>;
  citationIds: string[];
  /** Complete, clickable provenance for this exact virtual artefact. */
  citations: QueryCitation[];
  /*
   * β›” NO `edited` HERE, AND THE ABSENCE IS THE DESIGN (W35-T23 + T25).
   *
   * A draft of this carried one, because the grid kept the reader's spec in a local bucket and
   * needed a flag to decide whether that copy or the server's was current. That flag went stale
   * inside a session β€” `binding` is memoised on the artefact and nothing refetches it after an
   * autosave β€” so the first edit of a session survived a full reload and vanished on an in-session
   * remount. The fix was to delete the second store, not to freshen the flag: `view` above IS the
   * artefact's spec, and it is the only copy. The `edited` a reader SEES lives on `SavedQuery`,
   * where the rail reads it, and the renderer has no business asking.
   */
}

/**
 * The Query workspace's mutation policy.
 *
 * ⭐⭐ W35-T23 (owner item 4 / R2) β€” `update` NO LONGER MEANS "REFUSED", and this block is the
 * contract, so the change is stated here rather than only where it is enforced. A Query view is a
 * live view of its source database: resize, sort, group, hide and row height all write its spec,
 * through `POST /query/{qid}/events` and nowhere else. `create` is still refused β€” an artefact
 * holds exactly one view β€” and `delete` still removes the artefact itself.
 * ⚠ `QUERY_MUTATION_POLICY.update` is kept in the shape because the wire contract has three
 * readers and dropping a member is a breaking change; what it describes is now the refusal a
 * mismatched id gets, not every edit.
 */
export type QueryMutationOperation = "create" | "update" | "delete";
export interface QueryMutationRefusal {
  durable: false;
  transport: "none";
  code: "query_view_immutable";
  message: string;
}
export interface QueryDeleteMutation {
  durable: true;
  transport: "query_event";
  endpoint: "POST /query/{workspaceBinding.key}/events";
  event: "view_delete";
}
export interface QueryMutationPolicy {
  create: QueryMutationRefusal;
  update: QueryMutationRefusal;
  delete: QueryDeleteMutation;
}
export interface QueryMutationResult extends QueryMutationRefusal {
  artifactId: string;
  workspaceKey: string;
  operation: "create" | "update";
}

const IMMUTABLE_MUTATION: QueryMutationRefusal = {
  durable: false,
  transport: "none",
  code: "query_view_immutable",
  // ⭐⭐ W35-T23 (R2) β€” THE SENTENCE MOVED WITH THE RULE. It read *"This Query view is immutable.
  // Ask the Assistant to create a revised view."* and that is no longer true: a Query view's
  // spec is editable now, and the reader who resized a column would have been told to go and ask
  // a chatbot. What this refusal still covers is the ONE thing R2 did not open β€” a SECOND view
  // inside an artefact that holds exactly one.
  // ⚠ The CODE is unchanged (`query_view_immutable`): it is the wire contract three gates and
  // the server's own refusal key on, and the reason for the refusal did not change, only its
  // scope. Renaming it would be a protocol change dressed as a copy edit.
  // "the Assistant" β€” the rail's own word since W34-T13. Copy that names a module must name it
  // the way the reader sees it, or the sentence sends them looking for a door that is not there.
  message: "A Query view holds one saved answer, so it cannot take a second view. "
    + "Ask the Assistant for another one.",
};
export const QUERY_MUTATION_POLICY: QueryMutationPolicy = {
  create: IMMUTABLE_MUTATION,
  update: IMMUTABLE_MUTATION,
  delete: {
    durable: true,
    transport: "query_event",
    endpoint: "POST /query/{workspaceBinding.key}/events",
    event: "view_delete",
  },
};

/** The durable Query-only event payload; no source scope is permitted here. */
export interface QueryWorkspaceEvent {
  id?: string;
  type: "view_create" | "view_upsert" | "view_delete";
  viewId?: string;
  view?: Record<string, unknown>;
}
export interface QueryWorkspaceMutation {
  workspaceBinding: { kind: "query"; key: string };
  event: "view_delete";
  deleted: string;
}

export const QUERY_BINDING_EVENT = "aios:query-virtual-binding";

/** The local refusal B must use for every grid create, update, or delete attempt. */
export function refuseQueryMutation(
  binding: Pick<QueryVirtualBinding, "artifactId" | "workspaceBinding">,
  operation: "create" | "update",
): QueryMutationResult {
  return {
    ...IMMUTABLE_MUTATION,
    artifactId: binding.artifactId,
    workspaceKey: binding.workspaceBinding.key,
    operation,
  };
}

export function bindingFor(view: SavedQuery, citations: QueryCitation[]): QueryVirtualBinding {
  const ids = new Set(view.citationIds);
  return {
    artifactId: view.id,
    dataScope: view.source.database,
    workspaceBinding: { kind: "query", key: view.id },
    mutation: QUERY_MUTATION_POLICY,
    source: view.source,
    view: view.view,
    citationIds: view.citationIds,
    citations: citations.filter((citation) => ids.has(citation.id) && citation.database === view.source.database),
  };
}

export function errorMessage(status: number, message?: string): string {
  if (status >= 500 || !message) {
    return status >= 500
      ? "Something went wrong on our side. Try again in a moment."
      : `The server answered ${status}.`;
  }
  return message;
}

// Exported for the Assistant conversation clients (S68-T52): one transport, one error reader.
export async function call<T>(path: string, init: RequestInit, read: (body: unknown) => T): Promise<Result<T>> {
  let res: Response;
  try {
    res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
  } catch {
    return { ok: false, status: 0, message: "Cannot reach the server.", sentence: refusalSentence() };
  }
  const body = (await res.json().catch(() => null)) as unknown;
  if (!res.ok) {
    const detail = (body as { error?: { message?: string } } | null)?.error?.message;
    const { code } = refusalPair(body);
    // C2: `sentence` rides beside `message` so the dock reads it without a runtime import of this file.
    return { ok: false, status: res.status, message: errorMessage(res.status, detail), ...(code ? { code } : {}),
      sentence: refusalSentence(code) };
  }
  // C2: a 200 that says `status: "refused"` with a code is a non-answer, not a value.
  const refused = (body as { status?: unknown } | null)?.status === "refused" ? refusalPair(body) : {};
  if (refused.code) {
    const sentence = refusalSentence(refused.code);
    return { ok: false, status: res.status, message: sentence, code: refused.code, sentence };
  }
  return { ok: true, value: read(body) };
}

const sends = (method: string, data: unknown): RequestInit => ({
  method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(data),
});
const json = (data: unknown): RequestInit => sends("POST", data);
const str = (value: unknown): string => (typeof value === "string" ? value : "");
const rows = (value: unknown): Record<string, unknown>[] =>
  Array.isArray(value) ? value.filter((row): row is Record<string, unknown> => !!row && typeof row === "object") : [];

function provenance(value: unknown): AnswerProvenance | undefined {
  const row = value as Record<string, unknown> | null;
  const basis = str(row?.basis);
  if (basis !== "authorized_app_data" && basis !== "retrieved_knowledge" && basis !== "model_guidance") {
    return undefined;
  }
  return {
    basis,
    citationIds: (Array.isArray(row?.citationIds) ? row.citationIds : [])
      .filter((id): id is string => typeof id === "string"),
    modelGuidance: row?.modelGuidance === true,
    noneUsedReason: str(row?.noneUsedReason) || undefined,
  };
}

function source(value: unknown): QuerySource | null {
  const row = value as Record<string, unknown> | null;
  if (!row || !str(row.database) || !str(row.label) || !str(row.retrieved_at)) return null;
  return {
    database: str(row.database), label: str(row.label), source_kind: str(row.source_kind),
    source_version: row.source_version, retrieved_at: str(row.retrieved_at),
    fields: rows(row.fields).filter((field) => !!str(field.key)).map((field) => ({
      key: str(field.key), label: str(field.label) || undefined, type: str(field.type) || undefined,
    })),
    filters: row.filters, permission_scope_applied: row.permission_scope_applied === true,
  };
}

function saved(value: unknown): SavedQuery | null {
  const row = value as Record<string, unknown> | null;
  const src = source(row?.source);
  if (!row || !src || !str(row.id) || !str(row.viewId) || !str(row.threadId) || row.virtual !== true) return null;
  return {
    id: str(row.id), viewId: str(row.viewId), scope: str(row.scope) || src.database,
    name: str(row.name) || "Query", description: str(row.description), kind: str(row.kind) || "grid",
    question: str(row.question), explain: str(row.explain), threadId: str(row.threadId),
    createdAt: str(row.createdAt), virtual: true, source: src,
    view: (row.view && typeof row.view === "object" ? row.view : {}) as Record<string, unknown>,
    citationIds: (row.citationIds as unknown[] || []).filter((id): id is string => typeof id === "string"),
    numeric: ((row.numeric && typeof row.numeric === "object" ? row.numeric : {}) as SavedQuery["numeric"]),
    // ⚠ ABSENT β‡’ NOT EDITED AND NOT REVERTABLE, which is the safe direction: an older server that
    // sends neither key leaves the badge off and the control hidden, rather than offering a Revert
    // whose endpoint will 409.
    original_spec: (row.original_spec && typeof row.original_spec === "object"
      ? row.original_spec : null) as Record<string, unknown> | null,
    edited: row.edited === true,
  };
}

function message(value: unknown): QueryMessage | null {
  const row = value as Record<string, unknown> | null;
  const role = str(row?.role);
  if (!row || !str(row.id) || !str(row.threadId) || !str(row.content) || !str(row.createdAt)
      || (role !== "user" && role !== "assistant")) return null;
  return { id: str(row.id), threadId: str(row.threadId), role, content: str(row.content), createdAt: str(row.createdAt),
    targetDatabase: str(row.targetDatabase) || undefined,
    sources: (row.sources as unknown[] || []).filter((v): v is string => typeof v === "string"),
    requestedModel: str(row.requestedModel) || undefined, model: str(row.model) || null,
    reason: str(row.reason) || null, viewId: str(row.viewId) || null,
    citationIds: (Array.isArray(row.citationIds) ? row.citationIds : [])
      .filter((v): v is string => typeof v === "string"),
    numeric: (row.numeric && typeof row.numeric === "object" ? row.numeric : null) as QueryMessage["numeric"],
    provenance: provenance(row.provenance),
    rating: row.rating === "up" || row.rating === "down" ? row.rating : null,
    ratingReason: str(row.ratingReason),
    ...turnFields(row),
  };
}

function thread(value: unknown): QueryThread | null {
  const row = value as Record<string, unknown> | null;
  if (!row || !str(row.id) || !str(row.createdAt) || !str(row.updatedAt)) return null;
  return { id: str(row.id), title: str(row.title) || "New chat", createdAt: str(row.createdAt),
    updatedAt: str(row.updatedAt), sources: (row.sources as unknown[] || []).filter((v): v is string => typeof v === "string"),
    model: str(row.model) || "auto", activeViewId: str(row.activeViewId) || undefined };
}

function citation(value: unknown): QueryCitation | null {
  const row = value as Record<string, unknown> | null;
  const snap = row?.snapshot as Record<string, unknown> | null;
  if (!row || !snap || !str(row.id) || !str(row.href) || !str(row.database) || !str(row.retrieved_at)) return null;
  return { id: str(row.id), href: str(row.href), database: str(row.database),
    snapshot: { kind: str(snap.kind), version: snap.version },
    fields: (row.fields as unknown[] || []).filter((v): v is string => typeof v === "string"),
    filters: row.filters, permission_scope_applied: row.permission_scope_applied === true,
    aggregation: (row.aggregation && typeof row.aggregation === "object" ? row.aggregation : {}) as QueryCitation["aggregation"],
    contributing_record_count: Number(row.contributing_record_count) || 0, retrieved_at: str(row.retrieved_at) };
}

export function parseIndex(body: unknown): QueryIndex {
  const row = body as Record<string, unknown> | null;
  return {
    threads: rows(row?.threads).map(thread).filter((v): v is QueryThread => !!v),
    messages: rows(row?.messages).map(message).filter((v): v is QueryMessage => !!v),
    views: rows(row?.views).map(saved).filter((v): v is SavedQuery => !!v),
    citations: rows(row?.citations).map(citation).filter((v): v is QueryCitation => !!v),
    models: (row?.models as unknown[] || []).filter((v): v is string => typeof v === "string"),
    // ⚠ ABSENT β‡’ TREATED AS AVAILABLE, the same way an absent source row is treated as answerable:
    // the server is the authority and its refusal is still the wall. A client that greyed out
    // every model it had not heard about would disable the whole picker the moment this field
    // failed to arrive.
    modelStatus: rows(row?.modelStatus).filter((item) => !!str(item.model)).map((item) => ({
      model: str(item.model), available: item.available !== false, reason: str(item.reason),
      // ⚠ `!== false`, not `=== true`: an older server that sends no capability flags must read as
      // "capable", or the Agent chat's tool-calling filter would empty its own picker against a
      // deployment that is working fine. Same rule the line above already follows.
      toolCalling: item.toolCalling !== false, jsonMode: item.jsonMode !== false,
      // β›” AND THIS ONE INVERTS, deliberately: absent means NOT out of credit. Defaulting it the
      // other way would paint every model on an older server as broke.
      outOfCredit: item.outOfCredit === true,
    })),
    sources: rows(row?.sources).filter((item) => !!str(item.database)).map((item) => ({
      database: str(item.database), answerable: item.answerable === true, reason: str(item.reason),
    })),
  };
}

export function fetchQueries(): Promise<Result<QueryIndex>> {
  return call("/query", {}, parseIndex);
}

// The Artifacts page needs only the saved views. `only=views` skips resolving every source.
export function parseViews(body: unknown): SavedQuery[] {
  const row = body as Record<string, unknown> | null;
  return rows(row?.views).map(saved).filter((v): v is SavedQuery => !!v);
}

export function fetchQueryViews(): Promise<Result<SavedQuery[]>> {
  return call("/query?only=views", {}, parseViews);
}

export function submitChat(body: {
  question: string; database: string; sources: string[]; threadId?: string; model: string;
}): Promise<Result<ChatResult>> {
  return call("/query/chat", json(body), (raw) => {
    const row = raw as Record<string, unknown> | null;
    return {
      thread: thread(row?.thread) as QueryThread,
      userMessage: message(row?.userMessage) as QueryMessage,
      message: message(row?.message) as QueryMessage,
      view: saved(row?.view),
      citations: rows(row?.citations).map(citation).filter((v): v is QueryCitation => !!v),
      ...turnFields(row),
    };
  });
}

export function deleteQuery(id: string): Promise<Result<true>> {
  return call(`/query/${encodeURIComponent(id)}`, { method: "DELETE" }, () => true as const);
}

function turnFields(row: Record<string, unknown> | null) {
  const pending = row?.pendingDelete as Record<string, unknown> | null;
  return {
    toolCalls: rows(row?.toolCalls).filter((tool) => !!str(tool.name)).map((tool) => ({
      name: str(tool.name), args: (tool.args || {}) as Record<string, unknown>,
      effect: (tool.effect === "delete" || tool.effect === "write" ? tool.effect : "read") as AgentToolCall["effect"],
      ok: tool.ok === true, ref: str(tool.ref) || null,
    })),
    pendingDelete: pending && str(pending.id) ? {
      id: str(pending.id), summary: str(pending.summary), expiresAt: Number(pending.expiresAt),
    } : null,
    artifacts: (Array.isArray(row?.artifacts) ? row.artifacts : []).filter((id): id is string => typeof id === "string"),
  };
}

export function fetchArtifacts(cursor?: string): Promise<Result<ArtifactIndex>> {
  return call(`/artifacts${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`, {}, (raw) => {
    const row = raw as Record<string, unknown> | null;
    return { items: rows(row?.items) as unknown as AssistantArtifact[], nextCursor: str(row?.nextCursor) || null };
  });
}

function artifactAction(id: string, action: string): Promise<Result<ArtifactTurnResult>> {
  return call(`/artifacts/${encodeURIComponent(id)}/${action}`, json({}), (raw) => {
    const row = raw as Record<string, unknown> | null;
    return { reply: str(row?.reply), refused: str(row?.refused) || null, ...turnFields(row) };
  });
}
export const runArtifact = (id: string) => artifactAction(id, "run");
export const pauseArtifact = (id: string) => artifactAction(id, "pause");
export const resumeArtifact = (id: string) => artifactAction(id, "resume");
export function deleteArtifact(id: string): Promise<Result<{ pendingDelete: ArtifactPendingDelete }>> {
  return call(`/artifacts/${encodeURIComponent(id)}/delete`, json({}), (raw) =>
    ({ pendingDelete: turnFields(raw as Record<string, unknown>).pendingDelete as ArtifactPendingDelete }));
}

/**
 * ⭐⭐ R20 β€” THE THREE DOORS THAT ARE **NOT** `mutateQueryWorkspace`, and the distinction is the
 * whole design rather than a routing detail.
 *
 * `QUERY_MUTATION_POLICY` above is unchanged and still refuses create and update: the generated
 * SPEC and its provenance are immutable, because a cited number is only worth citing if the thing
 * it was computed from cannot be edited underneath it. What R20 opens is the LABELS beside it,
 * and a copy, and a read. Each gets its own named endpoint with a server-side allow-list, because
 * `routeQueryViewMutation` refuses `view_upsert` on a query binding LOCALLY, before any request
 * leaves the browser: opening that transport would give one question two answers.
 */
export function renameQuery(id: string, patch: { name?: string; description?: string }): Promise<Result<SavedQuery>> {
  return call(`/query/${encodeURIComponent(id)}`, sends("PATCH", patch),
    (raw) => saved(raw) as SavedQuery);
}

export function duplicateQuery(id: string): Promise<Result<SavedQuery>> {
  return call(`/query/${encodeURIComponent(id)}/duplicate`, json({}), (raw) => saved(raw) as SavedQuery);
}

/**
 * ⭐⭐ W35-T25 Β· CONTRACT C4 (R3) β€” "Revert to AI original".
 *
 * β›” IT RESTORES THE VIEW SPEC AND NOTHING ELSE, and the caller must SAY so before it acts. A
 * Query view is live now, so a cell the reader changed through it is a real write to a real
 * record in the source database; putting the filters back cannot walk that back. R3 requires the
 * confirm to state that BEFORE the click, not after.
 */
export function revertQuery(id: string): Promise<Result<SavedQuery>> {
  return call(`/query/${encodeURIComponent(id)}/revert`, json({}), (raw) => saved(raw) as SavedQuery);
}

/**
 * A DOWNLOAD, not a fetch: an ordinary same-origin link carries the session cookie, and the server
 * names the file through `Content-Disposition`. Building a Blob here would mean holding the whole
 * export in memory to hand it straight back to the browser.
 */
export function exportQueryHref(id: string): string {
  return `${API_V1}/query/${encodeURIComponent(id)}/export`;
}

/**
 * ⭐ R20's thumbs. `null` CLEARS the rating: a mis-click that cannot be taken back is worse than
 * no control, and the server reads a thumbs-down back into the next turn of the same thread, so
 * an uncorrected one keeps steering.
 */
/** What the database's own validator would not take, named rather than quietly missing. */
export interface QuerySaveResult {
  scope: string;
  viewId: string;
  name: string;
  dropped: string[];
}

/**
 * ⭐ R20: the answer becomes an ordinary view of its own database.
 *
 * β›” The server does NOT trust the write's own 200: `view_upsert` returns the same shape when it
 * saved and when it silently refused, so it reads the store back and refuses out loud instead.
 * There is nothing for this client to retry, which is the point.
 */
export function saveQueryToDatabase(id: string): Promise<Result<QuerySaveResult>> {
  return call(`/query/${encodeURIComponent(id)}/save-to-database`, json({}), (raw) => {
    const row = raw as Record<string, unknown> | null;
    return {
      scope: str(row?.scope), viewId: str(row?.viewId), name: str(row?.name),
      dropped: (row?.dropped as unknown[] || []).filter((v): v is string => typeof v === "string"),
    };
  });
}

export function rateMessage(id: string, rating: "up" | "down" | null, reason?: string): Promise<Result<QueryMessage>> {
  return call(`/query/messages/${encodeURIComponent(id)}/rating`,
    json({ rating, ...(reason ? { reason } : {}) }), (raw) => message(raw) as QueryMessage);
}

/**
 * The sole mutation path for a virtual Query workspace.  This intentionally never falls through
 * to the native grid event transport and never sends `dataScope`: the opaque Query key is the authority.
 * The server accepts delete and explicitly refuses create/update because AI artefacts are immutable.
 */
export function mutateQueryWorkspace(binding: QueryVirtualBinding, event: QueryWorkspaceEvent): Promise<Result<QueryWorkspaceMutation>> {
  const key = binding.workspaceBinding.key;
  return call(`/query/${encodeURIComponent(key)}/events`, json({
    workspaceBinding: binding.workspaceBinding, event,
  }), (raw) => {
    const row = raw as Record<string, unknown> | null;
    return {
      workspaceBinding: { kind: "query", key: str((row?.workspaceBinding as Record<string, unknown> | null)?.key) },
      event: str(row?.event) as QueryWorkspaceMutation["event"],
      deleted: str(row?.deleted),
    };
  });
}