@tangle-network/agent-app 0.60.230 → 0.60.231

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ import { type AppToolDefinition } from '../tools/registry';
2
+ import type { WorkProductService } from './service';
3
+ import { type WorkProductToolConfig } from './tool-config';
4
+ /** Register the incremental evidence and exception writes that accumulate a draft. */
5
+ export declare function buildDraftEmissionTools(config: WorkProductToolConfig, service: WorkProductService): AppToolDefinition[];
@@ -0,0 +1,19 @@
1
+ import type { AppToolContext } from '../tools/types';
2
+ import type { WorkProductOutcome, WorkProductService } from './service';
3
+ import { type WorkProductToolConfig } from './tool-config';
4
+ import type { WorkProductRecord } from './types';
5
+ /** Unwrap a guarded outcome, retrying ONCE on a lost race (the single
6
+ * serialized turn owner makes real contention rare; one re-read-and-retry
7
+ * absorbs the benign case). A deterministic rejection maps to a correctable
8
+ * `ToolInputError` so the model learns exactly why. */
9
+ export declare function unwrap<T>(run: () => Promise<WorkProductOutcome<T>>, code: string): Promise<T>;
10
+ export declare function requireScopeKey(args: Record<string, unknown>): string;
11
+ export declare function requireBatch(args: Record<string, unknown>, field: string): unknown[];
12
+ /**
13
+ * Resolve the scope's open draft row, creating or reopening as needed:
14
+ * an open `draft`/`blocked` row resumes; a `changes_requested` row reopens as
15
+ * the correction draft (version +1); a `ready` row refuses — the package is
16
+ * awaiting review and must receive a verdict first; otherwise a fresh draft
17
+ * is created at `last reviewed version + 1` with dispatch-stamped provenance.
18
+ */
19
+ export declare function resolveDraft(service: WorkProductService, config: WorkProductToolConfig, scopeKey: string, ctx: AppToolContext): Promise<WorkProductRecord>;
@@ -0,0 +1,160 @@
1
+ import type { AppToolContext } from '../tools/types';
2
+ import { type ConfusableTargetGroup } from './claim-support';
3
+ import type { WorkProductToolConfig } from './tool-config';
4
+ import type { EvidenceEntry } from './types';
5
+ /**
6
+ * Resolve every entry's quote against the document it names — the one place
7
+ * lineage text is decided.
8
+ *
9
+ * Two citation forms, and the asymmetry between them is the point:
10
+ *
11
+ * - `locator.span` — the model names `[start, end)` into text it just read
12
+ * and the PLATFORM slices the quote out of the source bytes. There is no
13
+ * retyping step, so a fabricated quote is not rejected, it is impossible.
14
+ * The slice REPLACES any quote the model also sent (the document is the
15
+ * authority, not the model's transcription of it) and the resolved text
16
+ * goes back in the tool result, so the model sees what was stored.
17
+ * - `locator.quote` alone — the legacy free-text form, still verified
18
+ * character-for-character. Kept because evidence written before spans
19
+ * existed, and sources reached through paths that cannot offer offsets,
20
+ * must stay expressible; a product does not lose lineage by upgrading.
21
+ *
22
+ * Entries are MUTATED in place with the resolved quote and its server-set
23
+ * `quoteBasis`, then persisted — so what a reviewer reads is what the platform
24
+ * proved, not what the model typed.
25
+ *
26
+ * Source texts are read once per distinct `sourceRef` in the batch — a
27
+ * 50-entry batch citing three documents is three reads, not fifty.
28
+ *
29
+ * Without `readSourceText` the product has given the shell no way to see its
30
+ * documents: free-text quotes go unchecked (as before — inventing a weaker
31
+ * check would report unverified lineage as verified), and a span is a LOUD
32
+ * refusal rather than a silently dropped locator, because a span the platform
33
+ * cannot slice is a wiring bug in the product, not a model mistake.
34
+ */
35
+ export declare function resolveEvidenceQuotes(config: WorkProductToolConfig, entries: readonly EvidenceEntry[], ctx: AppToolContext): Promise<void>;
36
+ /**
37
+ * Refuse any entry whose anchored text does not carry the figure it claims.
38
+ *
39
+ * This runs AFTER `resolveEvidenceQuotes`, on the text the platform decided,
40
+ * and it is deliberately independent of how that text was anchored. `find`
41
+ * makes a mis-addressed citation unlikely — the platform locates the line — but
42
+ * `span` still accepts offsets a caller computed, and this is what "accepted
43
+ * only when they independently verify" means concretely: the slice has to
44
+ * contain the value.
45
+ *
46
+ * Row `7256ef49` is the case. Four span citations, every quote a real slice of
47
+ * the right document, every one ~200 characters above the figure it claimed.
48
+ * `resolveEvidenceQuotes` passed all four; nothing else here would have caught
49
+ * them; a reviewer would have read four authoritative-looking citations
50
+ * supporting nothing.
51
+ *
52
+ * Rejection is a `ToolInputError` so it folds back to the model mid-turn, the
53
+ * same posture a non-occurring quote already gets, and the message names both
54
+ * ways out — cite the value, or drop the locator because the figure was
55
+ * computed. An unsatisfiable gate does not stop a bad submit, it selects for
56
+ * one, so naming the second exit is load-bearing rather than politeness.
57
+ */
58
+ export declare function assertClaimsSupported(config: WorkProductToolConfig, entries: readonly EvidenceEntry[]): void;
59
+ /**
60
+ * Refuse any entry whose cited line belongs to a sibling target.
61
+ *
62
+ * The fifth degree of freedom, and the one the four gates before it pass by
63
+ * construction: `quote_verification` proves the text is in the document,
64
+ * `claim_support` proves the text carries the claimed figure, and neither
65
+ * asks whether the figure belongs on THIS line. Row `95105c8a` shipped
66
+ * `evidence_coverage 6/6`, `claim_support 19/19`, `quote_verification 19/19`
67
+ * with `line_3a` (qualified dividends) pointing at the ordinary-dividends line
68
+ * and `line_3b` pointing at the qualified one.
69
+ *
70
+ * The product supplies which targets are confusable and what their lines say;
71
+ * the shell only compares. Refusal requires the document to positively name a
72
+ * sibling, so silence passes — see `./claim-support` for why that asymmetry is
73
+ * load-bearing rather than lenient.
74
+ */
75
+ export declare function assertTargetsNotCrossed(config: WorkProductToolConfig, entries: readonly EvidenceEntry[]): void;
76
+ /** Re-verify every persisted quote at submit time. The upsert gate stops new
77
+ * fabrication; this stops a package whose evidence was written BEFORE the
78
+ * gate existed (or under a since-corrected document) from reaching a
79
+ * reviewer. Entries with no quote are neither verified nor failures — they
80
+ * are lineage with no click target, counted separately so the recorded check
81
+ * states how much of the package is quote-backed.
82
+ *
83
+ * A span-anchored entry is re-checked by RE-SLICING the current document and
84
+ * comparing to the stored text, not by substring search. The difference
85
+ * matters exactly when a source has been replaced since the citation was
86
+ * written: a substring search would still pass if the sentence survived
87
+ * anywhere in the new file, while the reviewer's click target has silently
88
+ * moved. Re-slicing says the offsets still select the same characters. */
89
+ export declare function summarizeQuoteVerification(config: WorkProductToolConfig, evidence: readonly EvidenceEntry[], ctx: AppToolContext): Promise<{
90
+ verified: number;
91
+ spanAnchored: number;
92
+ withoutQuote: number;
93
+ failed: string[];
94
+ } | undefined>;
95
+ /**
96
+ * Re-run claim support over every PERSISTED entry at submit time.
97
+ *
98
+ * Unlike `summarizeQuoteVerification` this needs no `readSourceText`: the
99
+ * question is whether the stored quote carries the stored claim, and both are
100
+ * on the row. So it runs for every product, including one that cannot read its
101
+ * sources back — and it is the check that catches a package whose evidence was
102
+ * written before this gate existed. Row `7256ef49` is exactly that package.
103
+ */
104
+ export declare function summarizeClaimSupport(evidence: readonly EvidenceEntry[]): {
105
+ supported: number;
106
+ checkable: number;
107
+ unsupported: string[];
108
+ };
109
+ /**
110
+ * Re-run target correctness over every PERSISTED entry at submit time — the
111
+ * check that catches a package whose evidence was written before this gate
112
+ * existed. Like `summarizeClaimSupport` it reads only the row (the stored quote
113
+ * and the stored target), so it runs for every product.
114
+ */
115
+ export declare function summarizeTargetCorrectness(evidence: readonly EvidenceEntry[], groups: readonly ConfusableTargetGroup[], targetOf: (entry: EvidenceEntry) => string): {
116
+ correct: number;
117
+ checkable: number;
118
+ crossed: {
119
+ id: string;
120
+ detail: string;
121
+ }[];
122
+ };
123
+ /**
124
+ * Run artifact agreement over every PERSISTED entry against the artifact being
125
+ * submitted — the ONLY place it runs, and the "only" is load-bearing.
126
+ *
127
+ * The obvious second placement is the upsert, for the early feedback, and it
128
+ * makes the gate unsatisfiable on the one path that needs it most. A
129
+ * `changes_requested` row keeps the artifact the reviewer REJECTED, and an
130
+ * agent correcting a crossed package has exactly one order available to it:
131
+ * fix the evidence, then submit the corrected artifact, because the artifact
132
+ * is only settable at submit. Comparing the incoming citation to that stale
133
+ * artifact refuses precisely the correction being asked for —
134
+ *
135
+ * artifact (rejected): line_3a = 2204.18, line_3b = 1955.02
136
+ * agent re-emits: line_3a <- 1955.02 <- the fix
137
+ * stale comparison: "1955.02 is line_3b's value" -> refused, forever
138
+ *
139
+ * so the package can never be repaired. Same failure mode as a coverage gate
140
+ * demanding lineage for a computed value, removed for the same reason: an
141
+ * unsatisfiable rule does not stop bad work, it selects for invented work.
142
+ * Here both halves are current and either can be corrected during the turn.
143
+ *
144
+ * Nothing is lost by waiting. Row `95105c8a` is caught here and could only ever
145
+ * have been caught here — its crossed evidence was written turns before there
146
+ * was an artifact to compare it to.
147
+ *
148
+ * Only a real CONTRADICTION is refused: the claim asserts a figure the same
149
+ * artifact reports on another target. A component of an aggregate is not one
150
+ * (row `a68b1943` evidences a 189,750.00 wage line with two W-2s of 128,450.00
151
+ * and 61,300.00, and must keep doing so).
152
+ */
153
+ export declare function summarizeArtifactAgreement(evidence: readonly EvidenceEntry[], fieldValues: ReadonlyMap<string, string>, targetOf: (entry: EvidenceEntry) => string): {
154
+ agreeing: number;
155
+ checkable: number;
156
+ contradicting: {
157
+ id: string;
158
+ detail: string;
159
+ }[];
160
+ };
@@ -431,6 +431,60 @@ function workProductTrustInputs(records, verdictsFor) {
431
431
  return items;
432
432
  }
433
433
 
434
+ // src/work-product/tool-config.ts
435
+ var MAX_WORK_PRODUCT_BATCH = 50;
436
+ var EVIDENCE_COVERAGE_CHECK = "evidence_coverage";
437
+ var QUOTE_VERIFICATION_CHECK = "quote_verification";
438
+ var CLAIM_SUPPORT_CHECK = "claim_support";
439
+ var TARGET_CORRECTNESS_CHECK = "target_correctness";
440
+ var ARTIFACT_AGREEMENT_CHECK = "artifact_agreement";
441
+
442
+ // src/work-product/draft-tool-context.ts
443
+ async function unwrap(run, code) {
444
+ let outcome = await run();
445
+ if (!outcome.succeeded && outcome.conflict) outcome = await run();
446
+ if (!outcome.succeeded) throw new ToolInputError(code, outcome.error, outcome.conflict ? 409 : 400);
447
+ return outcome.value;
448
+ }
449
+ function requireScopeKey(args) {
450
+ const scopeKey = typeof args.scopeKey === "string" ? args.scopeKey.trim() : "";
451
+ if (!scopeKey) throw new ToolInputError("missing_scope_key", "scopeKey is required \u2014 the engagement key this work product belongs to.");
452
+ return scopeKey;
453
+ }
454
+ function requireBatch(args, field) {
455
+ const raw = args[field];
456
+ if (!Array.isArray(raw) || raw.length === 0) {
457
+ throw new ToolInputError("missing_entries", `${field} must be a non-empty array.`);
458
+ }
459
+ if (raw.length > MAX_WORK_PRODUCT_BATCH) {
460
+ throw new ToolInputError("batch_too_large", `${field} accepts at most ${MAX_WORK_PRODUCT_BATCH} entries per call \u2014 send smaller batches.`);
461
+ }
462
+ return raw;
463
+ }
464
+ async function resolveDraft(service, config, scopeKey, ctx) {
465
+ const open = await service.openDraft(ctx.workspaceId, scopeKey);
466
+ if (open) return open;
467
+ const awaitingReview = await service.awaitingReview(ctx.workspaceId, scopeKey);
468
+ if (awaitingReview) {
469
+ throw new ToolInputError(
470
+ "awaiting_review",
471
+ `Work product for ${scopeKey} (v${awaitingReview.version}) is awaiting review \u2014 no further emission until a reviewer verdict.`,
472
+ 409
473
+ );
474
+ }
475
+ const awaitingCorrection = await service.awaitingCorrection(ctx.workspaceId, scopeKey);
476
+ if (awaitingCorrection) {
477
+ return unwrap(() => service.reopen(awaitingCorrection.id), "reopen_failed");
478
+ }
479
+ return service.create({
480
+ workspaceId: ctx.workspaceId,
481
+ threadId: ctx.threadId,
482
+ scopeKey,
483
+ version: await service.nextVersion(ctx.workspaceId, scopeKey),
484
+ provenance: stampProvenance(config.provenance(ctx), config.now)
485
+ });
486
+ }
487
+
434
488
  // src/work-product/quote.ts
435
489
  var WHITESPACE = /[\s\p{Zs}\u2028\u2029\u200b-\u200d\ufeff]+/gu;
436
490
  var DASHES = /[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]/gu;
@@ -518,57 +572,7 @@ function sliceSourceSpan(sourceText, span) {
518
572
  return { ok: true, quote };
519
573
  }
520
574
 
521
- // src/work-product/tools.ts
522
- var MAX_WORK_PRODUCT_BATCH = 50;
523
- var EVIDENCE_COVERAGE_CHECK = "evidence_coverage";
524
- var QUOTE_VERIFICATION_CHECK = "quote_verification";
525
- var CLAIM_SUPPORT_CHECK = "claim_support";
526
- var TARGET_CORRECTNESS_CHECK = "target_correctness";
527
- var ARTIFACT_AGREEMENT_CHECK = "artifact_agreement";
528
- async function unwrap(run, code) {
529
- let outcome = await run();
530
- if (!outcome.succeeded && outcome.conflict) outcome = await run();
531
- if (!outcome.succeeded) throw new ToolInputError(code, outcome.error, outcome.conflict ? 409 : 400);
532
- return outcome.value;
533
- }
534
- function requireScopeKey(args) {
535
- const scopeKey = typeof args.scopeKey === "string" ? args.scopeKey.trim() : "";
536
- if (!scopeKey) throw new ToolInputError("missing_scope_key", "scopeKey is required \u2014 the engagement key this work product belongs to.");
537
- return scopeKey;
538
- }
539
- function requireBatch(args, field) {
540
- const raw = args[field];
541
- if (!Array.isArray(raw) || raw.length === 0) {
542
- throw new ToolInputError("missing_entries", `${field} must be a non-empty array.`);
543
- }
544
- if (raw.length > MAX_WORK_PRODUCT_BATCH) {
545
- throw new ToolInputError("batch_too_large", `${field} accepts at most ${MAX_WORK_PRODUCT_BATCH} entries per call \u2014 send smaller batches.`);
546
- }
547
- return raw;
548
- }
549
- async function resolveDraft(service, config, scopeKey, ctx) {
550
- const open = await service.openDraft(ctx.workspaceId, scopeKey);
551
- if (open) return open;
552
- const awaitingReview = await service.awaitingReview(ctx.workspaceId, scopeKey);
553
- if (awaitingReview) {
554
- throw new ToolInputError(
555
- "awaiting_review",
556
- `Work product for ${scopeKey} (v${awaitingReview.version}) is awaiting review \u2014 no further emission until a reviewer verdict.`,
557
- 409
558
- );
559
- }
560
- const awaitingCorrection = await service.awaitingCorrection(ctx.workspaceId, scopeKey);
561
- if (awaitingCorrection) {
562
- return unwrap(() => service.reopen(awaitingCorrection.id), "reopen_failed");
563
- }
564
- return service.create({
565
- workspaceId: ctx.workspaceId,
566
- threadId: ctx.threadId,
567
- scopeKey,
568
- version: await service.nextVersion(ctx.workspaceId, scopeKey),
569
- provenance: stampProvenance(config.provenance(ctx), config.now)
570
- });
571
- }
575
+ // src/work-product/evidence-verification.ts
572
576
  function spanErrorDetail(failure) {
573
577
  switch (failure.reason) {
574
578
  case "not_integer":
@@ -788,12 +792,9 @@ function summarizeArtifactAgreement(evidence, fieldValues, targetOf) {
788
792
  }
789
793
  return { agreeing, checkable, contradicting };
790
794
  }
791
- function buildWorkProductTools(config) {
792
- const service = createWorkProductService({
793
- store: config.store,
794
- ...config.now ? { now: config.now } : {},
795
- ...config.generateId ? { generateId: config.generateId } : {}
796
- });
795
+
796
+ // src/work-product/draft-emission-tools.ts
797
+ function buildDraftEmissionTools(config, service) {
797
798
  const canResolveTextLocators = config.readSourceText !== void 0;
798
799
  const locatorProperties = {
799
800
  page: { type: "number" },
@@ -950,7 +951,12 @@ function buildWorkProductTools(config) {
950
951
  };
951
952
  }
952
953
  });
953
- const submitWorkProduct = defineAppTool({
954
+ return [upsertEvidence, flagException];
955
+ }
956
+
957
+ // src/work-product/submission-tool.ts
958
+ function buildSubmissionTool(config, service) {
959
+ return defineAppTool({
954
960
  name: "submit_work_product",
955
961
  description: "Submit the finished work product for professional review \u2014 the terminal call after evidence and exceptions are recorded. Refused while a blocking exception is unresolved, or when a material target lacks evidence. Include your own quality checks in `checks`.",
956
962
  parameters: {
@@ -1144,7 +1150,16 @@ function buildWorkProductTools(config) {
1144
1150
  };
1145
1151
  }
1146
1152
  });
1147
- return [upsertEvidence, flagException, submitWorkProduct];
1153
+ }
1154
+
1155
+ // src/work-product/tools.ts
1156
+ function buildWorkProductTools(config) {
1157
+ const service = createWorkProductService({
1158
+ store: config.store,
1159
+ ...config.now ? { now: config.now } : {},
1160
+ ...config.generateId ? { generateId: config.generateId } : {}
1161
+ });
1162
+ return [...buildDraftEmissionTools(config, service), buildSubmissionTool(config, service)];
1148
1163
  }
1149
1164
 
1150
1165
  // src/work-product/route.ts