@agenticprimitives/context 0.0.0-alpha.3 → 0.0.0-alpha.31

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.
Files changed (75) hide show
  1. package/README.md +2 -0
  2. package/dist/affiliations-read.d.ts +1 -1
  3. package/dist/affiliations-read.js +4 -4
  4. package/dist/affiliations-read.js.map +1 -1
  5. package/dist/ask-discovery.d.ts.map +1 -1
  6. package/dist/ask-discovery.js +3 -0
  7. package/dist/ask-discovery.js.map +1 -1
  8. package/dist/directory-rows.d.ts +2 -0
  9. package/dist/directory-rows.d.ts.map +1 -1
  10. package/dist/directory-rows.js +2 -1
  11. package/dist/directory-rows.js.map +1 -1
  12. package/dist/estate.d.ts +57 -0
  13. package/dist/estate.d.ts.map +1 -0
  14. package/dist/estate.js +43 -0
  15. package/dist/estate.js.map +1 -0
  16. package/dist/facts.d.ts +52 -0
  17. package/dist/facts.d.ts.map +1 -0
  18. package/dist/facts.js +75 -0
  19. package/dist/facts.js.map +1 -0
  20. package/dist/grounded-composition.d.ts +1 -1
  21. package/dist/grounded-composition.d.ts.map +1 -1
  22. package/dist/grounded-composition.js +51 -0
  23. package/dist/grounded-composition.js.map +1 -1
  24. package/dist/grounded-types.d.ts +4 -0
  25. package/dist/grounded-types.d.ts.map +1 -1
  26. package/dist/index.d.ts +10 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/invitations-read.d.ts.map +1 -1
  31. package/dist/invitations-read.js +7 -4
  32. package/dist/invitations-read.js.map +1 -1
  33. package/dist/kb-question.d.ts.map +1 -1
  34. package/dist/kb-question.js +5 -0
  35. package/dist/kb-question.js.map +1 -1
  36. package/dist/kb-retrieve.d.ts +32 -0
  37. package/dist/kb-retrieve.d.ts.map +1 -0
  38. package/dist/kb-retrieve.js +73 -0
  39. package/dist/kb-retrieve.js.map +1 -0
  40. package/dist/membership-read.d.ts.map +1 -1
  41. package/dist/membership-read.js +10 -3
  42. package/dist/membership-read.js.map +1 -1
  43. package/dist/party-resolution.d.ts +81 -1
  44. package/dist/party-resolution.d.ts.map +1 -1
  45. package/dist/party-resolution.js +471 -212
  46. package/dist/party-resolution.js.map +1 -1
  47. package/dist/preferences.d.ts +39 -0
  48. package/dist/preferences.d.ts.map +1 -0
  49. package/dist/preferences.js +69 -0
  50. package/dist/preferences.js.map +1 -0
  51. package/dist/private-context.d.ts +13 -0
  52. package/dist/private-context.d.ts.map +1 -1
  53. package/dist/private-context.js +28 -10
  54. package/dist/private-context.js.map +1 -1
  55. package/dist/relationship-rows.d.ts +10 -0
  56. package/dist/relationship-rows.d.ts.map +1 -1
  57. package/dist/relationship-rows.js +4 -2
  58. package/dist/relationship-rows.js.map +1 -1
  59. package/dist/routines.d.ts +45 -0
  60. package/dist/routines.d.ts.map +1 -0
  61. package/dist/routines.js +34 -0
  62. package/dist/routines.js.map +1 -0
  63. package/dist/self-only.js +1 -1
  64. package/dist/self-only.js.map +1 -1
  65. package/dist/standing.d.ts +81 -7
  66. package/dist/standing.d.ts.map +1 -1
  67. package/dist/standing.js +164 -18
  68. package/dist/standing.js.map +1 -1
  69. package/dist/tiers.d.ts +6 -0
  70. package/dist/tiers.d.ts.map +1 -1
  71. package/dist/vault-question.d.ts +3 -0
  72. package/dist/vault-question.d.ts.map +1 -1
  73. package/dist/vault-question.js +55 -8
  74. package/dist/vault-question.js.map +1 -1
  75. package/package.json +20 -7
@@ -15,8 +15,9 @@
15
15
  // people search is a different ask (279/338).
16
16
  //
17
17
  // So resolution now runs over `@agenticprimitives/context`: providers own a tier, the tier travels on every
18
- // candidate, and a lookup that will bind an authority asks only the private ones. What remains public —
19
- // `find_agents`, `get_agent` — answers QUESTIONS about who exists, which is a different thing a person can
18
+ // candidate, and a lookup that will bind an authority asks only the private ones. The naming registry is
19
+ // PUBLIC (spec 445 §3.6): it answers a typed name she wrote out, and fills the options of a question — it is
20
+ // never a candidate for a bare label. What else is public — `find_agents`, `get_agent` — answers QUESTIONS about who exists, which is a different thing a person can
20
21
  // also want.
21
22
  //
22
23
  // The honest limit: the private tier reachable today is the asker's own relationships. Somebody known to
@@ -33,7 +34,7 @@ import { relationshipRows } from './relationship-rows.js';
33
34
  /** The vault record type holding an asker's received resolution grants (spec 338). Declared HERE —
34
35
  * the app's resolution-invitation module imports it back, so the key has one definition. */
35
36
  export const RESOLUTION_GRANTS_RECORD = 'resolution.grants';
36
- import { relationshipsProvider, rosterProvider } from './private-context.js';
37
+ import { relationshipsProvider, rosterProvider, exactNameProvider } from './private-context.js';
37
38
  /** The roots a bare label might live under, most-likely first. A person is the common case for "alice". */
38
39
  export const PARTY_ROOTS = ['me', 'org', 'team', 'treasury', 'workspace', 'svc', 'circle', 'church', 'registry'];
39
40
  /** The owner a candidate was reached THROUGH, when it was reached through one.
@@ -53,43 +54,67 @@ const isAddress = (v) => /^0[xX][0-9a-fA-F]{40}$/.test(v);
53
54
  * for is a question, not a resolution: a payment cannot be taken back. */
54
55
  export const VALUE_ARGS = ONTOLOGY_VALUE_ARGS;
55
56
  /**
56
- * A bare label against the typed roots the asker could plausibly mean, resolved on chain.
57
+ * THE NAMING REGISTRY IS THE PUBLIC TIER (spec 352 §7, spec 445 §3.6 / audit H-12).
57
58
  *
58
- * PRIVATE tier, deliberately: `alice.me` is not a search of everyone — it is the question "does the person
59
- * I am acting for have an agent by this label", asked of a naming service that answers exactly. It is
60
- * paired with `relationships`, which knows who they actually know; between them, a bare label that matches
61
- * nothing they have a link to still surfaces if it is a well-known typed name, and ambiguity between the
62
- * two is a question rather than a pick.
59
+ * The rule: a name resolves in what the asker HOLDS, or it is a question. The naming registry is public and
60
+ * first-come — a hit for `alice.treasury` proves somebody registered that name, never that this person
61
+ * knows them — so it is never a candidate for a bare label. This block once argued the opposite ("PRIVATE
62
+ * tier, deliberately"), and that label is what made a name-squatter the payee of "send alice 10": the
63
+ * lookup asked for `tiers: ['private']` and was handed the registry.
64
+ *
65
+ * What the registry is still used for, each under its own name:
66
+ *
67
+ * A TYPED NAME SHE WROTE OUT (`alice.treasury`) — `exactNameProvider`, public tier, exact. She named the
68
+ * registry entry herself, so it resolves; the result says `evidence: 'typed-public-name'`. For an
69
+ * argument that moves value it is a question the first time (below).
70
+ *
71
+ * OPTIONS FOR A QUESTION — `publicNameOptions`. When nothing she holds answers to a bare label, the typed
72
+ * roots are read so the question can offer "alice.me — a public name, not someone you are linked to".
73
+ * It only ever fills a list a person chooses from; it is not a candidate and resolves nothing.
63
74
  */
64
- function typedRootProvider(resolveName) {
65
- return {
66
- source: 'naming',
67
- tier: 'private',
68
- async candidates(query) {
69
- const label = query.term.trim().toLowerCase();
70
- if (isAddress(label))
71
- return [];
72
- // A spoken name is words: "missio nexus organization" is registered, if at all, as `missio-nexus`
73
- // or `missionexus` under a typed root — the kind word says which root to try first, and only that
74
- // root when it was said.
75
- const forms = label.includes('.') ? [label] : (/[^a-z0-9-]/.test(label) ? labelForms(label) : [label]);
76
- const kind = saidKind(label);
77
- const saidRoot = kind === 'organization' || kind === 'organisation' ? 'org' : kind;
78
- const roots = saidRoot && PARTY_ROOTS.includes(saidRoot) ? [saidRoot] : PARTY_ROOTS;
79
- const names = label.includes('.') ? [label] : forms.flatMap((f) => roots.map((r) => `${f}.${r}`));
80
- const found = await Promise.all(names.map(async (name) => ({ name, agent: await resolveName(name).catch(() => null) })));
81
- return found
82
- .filter((f) => !!f.agent)
83
- .map((f) => ({
84
- agent: f.agent.toLowerCase(),
85
- label: f.name,
86
- name: f.name,
87
- provenance: { tier: 'private', source: 'naming', ...(query.subject ? { subject: query.subject } : {}), match: label.includes('.') ? 'exact-name' : forms.length === 1 && forms[0] === label ? 'label' : 'close' },
88
- }));
89
- },
90
- };
75
+ export async function publicNameOptions(raw, resolveName) {
76
+ const label = raw.trim().toLowerCase();
77
+ if (!label || isAddress(label) || label.includes('.'))
78
+ return [];
79
+ // A spoken name is words: "missio nexus organization" is registered, if at all, as `missio-nexus`
80
+ // or `missionexus` under a typed root — the kind word says which root to try first, and only that
81
+ // root when it was said.
82
+ const forms = /[^a-z0-9-]/.test(label) ? labelForms(label) : [label];
83
+ const kind = saidKind(label);
84
+ const saidRoot = kind === 'organization' || kind === 'organisation' ? 'org' : kind;
85
+ const roots = saidRoot && PARTY_ROOTS.includes(saidRoot) ? [saidRoot] : PARTY_ROOTS;
86
+ const names = forms.flatMap((f) => roots.map((r) => `${f}.${r}`));
87
+ const found = await Promise.all(names.map(async (name) => ({ name, agent: await resolveName(name).catch(() => null) })));
88
+ const seen = new Set();
89
+ return found
90
+ .filter((f) => !!f.agent && !seen.has(f.agent.toLowerCase()) && !!seen.add(f.agent.toLowerCase()))
91
+ .map((f) => ({
92
+ agent: f.agent.toLowerCase(),
93
+ label: f.name,
94
+ name: f.name,
95
+ provenance: { tier: 'public', source: 'naming', match: forms.length === 1 && forms[0] === label ? 'label' : 'close' },
96
+ }));
91
97
  }
92
- /** The providers a party lookup may consult, in order — private ones only. */
98
+ /** The tiers a party lookup may read, decided by WHAT SHE TYPED: a bare label reads only her own tier; a
99
+ * typed name (it has a dot) may also be looked up, exactly, in the public naming registry. */
100
+ export function partyTiers(term) {
101
+ return term.trim().includes('.') ? ['private', 'public'] : ['private'];
102
+ }
103
+ /** Is this the registry entry she typed in full — public, exact, and backed by nothing she holds? */
104
+ const isTypedPublicName = (c) => c.provenance.tier === 'public' && c.provenance.source === 'naming' && c.provenance.match === 'exact-name';
105
+ /**
106
+ * DOES THE ASKER HOLD EVIDENCE THAT SHE MEANS THIS AGENT? (spec 445 §3.6, audit RUN-1 / RUNC-3.)
107
+ *
108
+ * Yes for a link in her own records — her relationships, her household, a resolution grant she was given.
109
+ * No for anything public, and no for a ROSTER row: a listing is what a member published about THEMSELVES
110
+ * (display name and handle alike), so any co-member can make themselves answer to "alice". That is enough
111
+ * to be a candidate for a message; for an argument that moves value it is a question.
112
+ */
113
+ function heldByAsker(c) {
114
+ return c.provenance.tier === 'private' && c.provenance.source !== 'roster';
115
+ }
116
+ /** The providers a party lookup may consult, in order: her own tier, then the exact typed-name lookup —
117
+ * PUBLIC, and reached only by a lookup that names the public tier (`partyTiers`). */
93
118
  export function partyProviders(lookups) {
94
119
  const providers = [];
95
120
  if (lookups.readSubjectRecord) {
@@ -99,13 +124,13 @@ export function partyProviders(lookups) {
99
124
  providers.push(relationshipsProvider(tier), rosterProvider(tier));
100
125
  }
101
126
  if (lookups.resolveName)
102
- providers.push(typedRootProvider(lookups.resolveName));
127
+ providers.push(exactNameProvider(lookups.resolveName));
103
128
  return providers;
104
129
  }
105
130
  /** Every agent the asker could mean by these words. Exported for tests and for a surface that wants to
106
131
  * show the same candidates the resolver saw. */
107
132
  export async function partyCandidates(raw, lookups, subject) {
108
- const outcome = await resolveEntity(partyProviders(lookups), { term: raw, tiers: ['private'], ...(subject ? { subject } : {}), limit: 8 });
133
+ const outcome = await resolveEntity(partyProviders(lookups), { term: raw, tiers: partyTiers(raw), ...(subject ? { subject } : {}), limit: 8 });
109
134
  if (outcome.outcome === 'certain')
110
135
  return [outcome.candidate];
111
136
  return outcome.outcome === 'ambiguous' ? outcome.candidates : [];
@@ -263,7 +288,8 @@ export async function ownedAgentsOfType(owner, type, lookups, asker) {
263
288
  const FOUND_IN = {
264
289
  relationships: 'you are linked to them',
265
290
  roster: 'a member of one of your organizations',
266
- naming: 'the naming service',
291
+ 'resolution-grant': 'a way to reach them that you were given',
292
+ household: 'in your household',
267
293
  };
268
294
  /**
269
295
  * What tells two agents with the same name apart. Kind first (a person and a team called the same thing
@@ -301,6 +327,7 @@ export async function householdMembers(subject, lookups) {
301
327
  return {
302
328
  agent: String(r.agent).toLowerCase(),
303
329
  ...(r.label ? { label: String(r.label) } : {}),
330
+ ...(r.name ? { name: String(r.name) } : {}),
304
331
  ...(kin ? { kin } : {}), ...(kinLabel ? { kinLabel } : {}),
305
332
  ...(r.role ? { role: String(r.role) } : {}),
306
333
  ...(r.household ? { household: String(r.household) } : {}),
@@ -377,7 +404,11 @@ export function candidateHint(c) {
377
404
  if (c.kind)
378
405
  bits.push(c.kind);
379
406
  bits.push(`${c.agent.slice(0, 8)}…${c.agent.slice(-4)}`);
380
- const from = FOUND_IN[c.provenance.source];
407
+ // The registry is public: a name she typed in full is said to be exactly that, and one offered for a
408
+ // bare label is said to be nobody she is linked to (spec 445 §3.6).
409
+ const from = c.provenance.source === 'naming'
410
+ ? (c.provenance.match === 'exact-name' ? 'the public name you typed' : 'a public name — not someone you are linked to')
411
+ : FOUND_IN[c.provenance.source];
381
412
  if (from)
382
413
  bits.push(from);
383
414
  // A near name is SAID to be one: the person sees "closest to what you said" beside it before anything
@@ -395,6 +426,64 @@ async function rememberedChoice(lookups, where, value, candidates) {
395
426
  return null;
396
427
  return lookups.preferredChoice({ word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName }, candidates).catch(() => null);
397
428
  }
429
+ /**
430
+ * Spec 420 §10 — THE NEAREST PERSON IN CONTEXT (`appr:namesResolveInContext`). Several candidates answer to a bare name;
431
+ * before asking, the resolver reads how near each is to the asker in the context she stands in: (1) on the roster of the
432
+ * ROOM she is asking in · (2) in her household · (3) in a context she shares (a roster of one of her organizations) ·
433
+ * (4) her recent dealings (how often they were a party in her recent turns) · (5) her other links. Exactly one at the
434
+ * nearest level that has any is the answer, CITED by that context; several at the same level stay a question — unless
435
+ * exactly one of them has recent dealings, which is then the answer, cited. Never a ranking score (ADR-0013): a level
436
+ * is a fact about the world ("on the team you are asking in"), and it is said.
437
+ */
438
+ /** The typed-name suffix a recorded KIND claims: `person` → `me`, `org`/`organization` → `org`, a class IRI's local name → its
439
+ * suffix (ADR-0061). Empty when the kind is unknown — a kind is never guessed from a label. */
440
+ export function suffixForKind(k) {
441
+ const low = (k ?? '').toLowerCase();
442
+ if (!low)
443
+ return '';
444
+ if (low in CLASS_FOR_SUFFIX)
445
+ return low;
446
+ const byClass = Object.entries(SUFFIX_FOR_CLASS).find(([iri]) => iri.toLowerCase().endsWith(`#${low}agent`) || iri.toLowerCase().endsWith(`#${low}`));
447
+ return byClass?.[1] ?? { person: 'me', organization: 'org', service: 'svc' }[low] ?? '';
448
+ }
449
+ export function nearestInContext(candidates, ctx) {
450
+ const lc2 = (v) => v.toLowerCase();
451
+ const room = ctx.room ? lc2(ctx.room) : undefined;
452
+ const inHousehold = new Set((ctx.household ?? []).map((h) => lc2(h.agent)));
453
+ const dealings = new Map();
454
+ for (const r of ctx.recent ?? [])
455
+ dealings.set(lc2(r.agent), (dealings.get(lc2(r.agent)) ?? 0) + 1);
456
+ const levelOf = (c) => {
457
+ const a = lc2(c.agent);
458
+ if (room && c.provenance.context?.agent && lc2(c.provenance.context.agent) === room)
459
+ return { level: 1, because: `${c.provenance.context.name ? `on ${c.provenance.context.name}'s roster` : 'on the roster of the agent'} you are asking in` };
460
+ if (inHousehold.has(a) || c.provenance.source === 'household')
461
+ return { level: 2, because: 'in your household' };
462
+ if (c.provenance.source === 'roster')
463
+ return { level: 3, because: c.provenance.context?.name ? `on ${c.provenance.context.name} with you` : 'in an organization with you' };
464
+ if (dealings.has(a))
465
+ return { level: 4, because: `you dealt with them ${dealings.get(a)} time${dealings.get(a) === 1 ? '' : 's'} recently` };
466
+ // A typed name the naming service answers exactly (`ryan.me`) is not a context the asker stands in: it is the farthest
467
+ // reading, and it is said as one — the situation baseline (2026-09-28) had "drop ryan a line" reach a stranger's
468
+ // `ryan.me` over the Ryan on a team she stewards, cited "you are linked to them", which was false.
469
+ if (c.provenance.source === 'naming')
470
+ return { level: 6, because: 'an agent by that name, in no context you share' };
471
+ return { level: 5, because: 'you are linked to them' };
472
+ };
473
+ const levelled = candidates.map((c) => ({ c, ...levelOf(c) }));
474
+ const nearest = Math.min(...levelled.map((x) => x.level));
475
+ const atNearest = levelled.filter((x) => x.level === nearest);
476
+ if (atNearest.length === 1)
477
+ return { agent: lc2(atNearest[0].c.agent), candidate: atNearest[0].c, because: atNearest[0].because };
478
+ const dealt = atNearest.filter((x) => dealings.has(lc2(x.c.agent)));
479
+ if (dealt.length === 1) {
480
+ const n = dealings.get(lc2(dealt[0].c.agent));
481
+ return { agent: lc2(dealt[0].c.agent), candidate: dealt[0].c, because: `${dealt[0].because}, and you dealt with them ${n} time${n === 1 ? '' : 's'} recently` };
482
+ }
483
+ return null;
484
+ }
485
+ /** How a kind is said in a sentence (a person, an organization — never "a me", "a org"). */
486
+ const KIND_WORDS = { me: 'a person', org: 'an organization', svc: 'a service agent', household: 'a household', team: 'a team', treasury: 'a treasury', workspace: 'a workspace', circle: 'a circle', church: 'a church' };
398
487
  export async function resolveParty(raw, lookups, where) {
399
488
  const value = String(raw ?? '').trim();
400
489
  if (isAddress(value)) {
@@ -495,193 +584,363 @@ export async function resolveParty(raw, lookups, where) {
495
584
  return chosen.value.agent;
496
585
  }
497
586
  }
498
- const outcome = await resolveEntity(partyProviders(lookups), {
499
- term: value, tiers: ['private'], ...(where.subject ? { subject: where.subject } : {}), limit: 8,
500
- });
501
- // ── WHAT KIND OF AGENT THIS ARGUMENT IS ──────────────────────────────────────────────────────────
502
- // "Send money to nathan" and "send nathan a message" are the same word; the difference lives in the
503
- // CAPABILITY, and the typed suffix (ADR-0061) is what makes it decidable. Tiers, in the order a person
504
- // means them: the first type anything answers to wins.
505
- //
506
- // This narrows and never picks. Two treasuries called nathan is still a question, and a capability whose
507
- // preferred types match nothing gets asked with everything that DID answer — "nathan has no treasury"
508
- // is an answer, not a licence to quietly pay some other Nathan.
509
- if (where.types?.length && (outcome.outcome === 'ambiguous' || outcome.outcome === 'certain')) {
510
- const all = outcome.outcome === 'ambiguous' ? outcome.candidates : [outcome.candidate];
511
- const suffix = (c) => (c.name ?? c.label ?? '').toLowerCase().split('.').pop() ?? '';
512
- /** Ways the asker HOLDS that the gate refused, with the reason — collected as the tiers are tried. */
513
- const heldButRefused = [];
514
- for (const [rank, type] of where.types.entries()) {
515
- const tier = all.filter((c) => suffix(c) === type);
516
- // A SUBSTITUTION IS NOT A RESOLUTION. "Send alice 20 USDC" asks for her treasury; when nothing
517
- // answers to one, paying her PERSON agent instead is a different destination reached silently — and
518
- // a payment to the wrong address is not a thing anyone can undo. So for arguments that move value,
519
- // dropping past the first-choice type is a question, with the reason said plainly.
520
- //
521
- // Only for money: a message falling from `.me` to `.org` is the same conversation with the same
522
- // person's organization, and asking about it would be noise.
523
- // NOT OF THIS TYPE — so ask what the ones we DID find OWN. "Send money to alice" names the person;
524
- // her treasury is a thing she HOLDS, and the two are connected by a relationship, not by their
525
- // names resembling each other. Resolve the person, then follow the link.
526
- if (!tier.length && rank === 0) {
527
- const lists = await Promise.all(all.map((c) => ownedAgentsOfType(c.agent, type, lookups, where.subject).catch(() => [])));
528
- // A WAY THEY HOLD THAT DID NOT WORK travels with the lists, so the question below can name it
529
- // rather than reporting "nothing called bob is a treasury" to somebody holding a way to reach him.
530
- for (const l of lists)
531
- heldButRefused.push(...(l.refusals ?? []));
532
- const owned = lists.flat().filter((c, i, xs) => xs.findIndex((y) => y.agent === c.agent) === i);
533
- if (owned.length === 1) {
534
- const c = owned[0];
535
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent, label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
536
- return c.agent.toLowerCase();
587
+ // ── WHAT A VALUE ARGUMENT NEEDS BEHIND IT (spec 445 §3.6) ─────────────────────────────────────────
588
+ // For an argument that moves value, a candidate the asker holds no link to — a public name, a roster
589
+ // listing its member published — is ALWAYS a question, never a pick. Asked once: the question carries the
590
+ // spec-385 scope, the trusted resume that answers it is remembered, and `preferredChoice` then answers
591
+ // for the same word, capability and argument without asking.
592
+ const moves = VALUE_ARGS.has(where.argName);
593
+ const scope = { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName };
594
+ // Spec 448 (audit T4-4) — A NEAR MATCH NEVER FILLS A VALUE ARGUMENT, WHICHEVER BRANCH PRODUCED IT. "sam" is not
595
+ // "samuel-okoro.treasury", and it is not "samuel-okoro.me" whose treasury is then substituted, nor the nearest of two
596
+ // treasuries that both begin with "sam". Every way below of reaching an agent from her WORDS ends at ONE gate
597
+ // (`fromWords` → the check after it): the agent returned for a value argument must be one her words named EXACTLY
598
+ // (`exactly`), owned by one they named exactly, or one she CONFIRMED for this word, capability and argument (spec 385).
599
+ // Anything else is asked about. Fail-closed by construction: a new branch that forgets to vouch for its agent asks.
600
+ // What the words became is reported only once the gate has passed, so a surface never shows a payee it then asks about.
601
+ const exactly = new Set();
602
+ const nearly = new Map();
603
+ let pending = null;
604
+ const report = (r) => { pending = r; };
605
+ const vouch = (agent) => { exactly.add(agent.toLowerCase()); };
606
+ const confirmed = async (cands) => {
607
+ const remembered = await rememberedChoice(lookups, where, value, cands);
608
+ if (!remembered)
609
+ return null;
610
+ vouch(remembered.agent);
611
+ const c = cands.find((x) => x.agent.toLowerCase() === remembered.agent.toLowerCase());
612
+ report({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? c?.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? c?.label ?? value}” for this before`, evidence: 'confirmed', ...(c && ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
613
+ return remembered.agent.toLowerCase();
614
+ };
615
+ const askToConfirm = (prompt, cands, hintOf = candidateHint, fieldHint = 'nothing you hold links you to this — pick it to confirm, or give another name or address') => ask(prompt, {
616
+ name: where.argName, label: where.what, type: 'choice', required: true,
617
+ choices: cands.map((c) => ({ value: c.agent, label: c.label, hint: hintOf(c) })),
618
+ allowOther: true,
619
+ hint: fieldHint,
620
+ }, undefined, scope);
621
+ /** Why a lone candidate is a question for a value argument, said plainly. */
622
+ const unheld = (c) => isTypedPublicName(c)
623
+ ? `“${value}” is a public name, and nothing you hold links you to it`
624
+ : `“${value}” is ${c.label}, known to you only through a listing they published`;
625
+ /** One candidate: use it — or, for a value argument she holds no link behind, the one she confirmed before, or ask. */
626
+ const settle = async (c) => {
627
+ if (moves && !heldByAsker(c)) {
628
+ const before = await confirmed([c]);
629
+ if (before)
630
+ return before;
631
+ askToConfirm(`${unheld(c)}. Is this who should be ${asVerb(where.what)}?`, [c]);
632
+ }
633
+ report({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}), ...(isTypedPublicName(c) ? { evidence: 'typed-public-name' } : {}) });
634
+ return c.agent.toLowerCase();
635
+ };
636
+ /** A decision made FOR her (nearest in context, the rolling window) may settle a value argument only on an agent she holds a link to. */
637
+ const mayDecide = (agent, among) => !moves || among.some((c) => c.agent.toLowerCase() === agent.toLowerCase() && heldByAsker(c));
638
+ const fromWords = async () => {
639
+ // A BARE LABEL READS ONLY HER OWN TIER. A typed name she wrote out is also looked up, exactly, in the
640
+ // public registry (`partyTiers`) — a separate, named path, never a fallback for the label.
641
+ const found = await resolveEntity(partyProviders(lookups), {
642
+ term: value, tiers: partyTiers(value), ...(where.subject ? { subject: where.subject } : {}), limit: 8,
643
+ });
644
+ lookups.onCandidates?.({
645
+ arg: where.argName, raw: value, outcome: found.outcome,
646
+ ...(found.outcome === 'unknown' ? { looked: found.looked.map((l) => l.source) } : {}),
647
+ candidates: (found.outcome === 'certain' ? [found.candidate] : found.outcome === 'ambiguous' ? found.candidates : []).map((c) => ({
648
+ agent: c.agent.toLowerCase(), source: c.provenance.source, ...(c.provenance.match ? { match: c.provenance.match } : {}),
649
+ ...(c.provenance.context?.name ? { context: c.provenance.context.name } : {}), ...(c.kind ? { kind: c.kind } : {}),
650
+ })),
651
+ });
652
+ // Spec 420 §10 — HER HOUSEHOLD IS A CONTEXT TOO. Under `nearest`, a household member answering to the word (their label,
653
+ // their name's first part, a kin word) joins the candidates as a `household` source, so the nearest-in-context rule can
654
+ // prefer them over a farther context — "tell rich" at her own agent means the Rich she lives with, not a Rich on a team.
655
+ const outcome = await (async () => {
656
+ if (!where.nearest || !where.subject || isAddress(value) || value.includes('.'))
657
+ return found;
658
+ const w = value.toLowerCase();
659
+ const hh = (await householdMembers(where.subject, lookups).catch(() => [])).filter((m) => [m.label, m.kinWord, m.kinLabel].some((x) => x && x.toLowerCase() === w) || (m.label ?? '').toLowerCase().split(/[\s.]+/)[0] === w);
660
+ if (!hh.length)
661
+ return found;
662
+ const base = found.outcome === 'certain' ? [found.candidate] : found.outcome === 'ambiguous' ? found.candidates : [];
663
+ const merged = [...base];
664
+ for (const m of hh)
665
+ if (!merged.some((c) => c.agent.toLowerCase() === m.agent.toLowerCase()))
666
+ merged.push({ agent: m.agent.toLowerCase(), label: m.label ?? m.name ?? m.agent, ...(m.name ? { name: m.name } : {}), kind: 'person', provenance: { tier: 'private', source: 'household', subject: where.subject, match: 'label' } });
667
+ return merged.length === 1 ? { outcome: 'certain', candidate: merged[0] } : { outcome: 'ambiguous', candidates: merged };
668
+ })();
669
+ for (const c of outcome.outcome === 'certain' ? [outcome.candidate] : outcome.outcome === 'ambiguous' ? outcome.candidates : []) {
670
+ if (c.provenance.match === 'close')
671
+ nearly.set(c.agent.toLowerCase(), { cand: c });
672
+ else
673
+ vouch(c.agent);
674
+ }
675
+ // ── WHAT KIND OF AGENT THIS ARGUMENT IS ──────────────────────────────────────────────────────────
676
+ // "Send money to nathan" and "send nathan a message" are the same word; the difference lives in the
677
+ // CAPABILITY, and the typed suffix (ADR-0061) is what makes it decidable. Tiers, in the order a person
678
+ // means them: the first type anything answers to wins.
679
+ //
680
+ // This narrows and never picks. Two treasuries called nathan is still a question, and a capability whose
681
+ // preferred types match nothing gets asked with everything that DID answer — "nathan has no treasury"
682
+ // is an answer, not a licence to quietly pay some other Nathan.
683
+ if (where.types?.length && (outcome.outcome === 'ambiguous' || outcome.outcome === 'certain')) {
684
+ const all = outcome.outcome === 'ambiguous' ? outcome.candidates : [outcome.candidate];
685
+ // A candidate with no typed name but a KNOWN kind still has a kind: a household member recorded by display name is a
686
+ // person (`.me`) — dropping every display-named candidate from the type tier asked "which person?" of the one Rich she lives with.
687
+ // A candidate with NEITHER is asked of the chain (`agentKindOf`), the record of what kind of agent it is — never guessed
688
+ // from the record that listed it (a roster lists people and teams alike).
689
+ if (lookups.agentKindOf)
690
+ await Promise.all(all.filter((c) => !(c.name ?? '').includes('.') && !c.kind).map(async (c) => { const k = await lookups.agentKindOf(c.agent).catch(() => null); if (k)
691
+ c.kind = k.toLowerCase(); }));
692
+ const suffix = (c) => { const n = (c.name ?? '').toLowerCase(); if (n.includes('.'))
693
+ return n.split('.').pop() ?? ''; if (c.kind)
694
+ return suffixForKind(c.kind) || c.kind; return (c.label ?? '').toLowerCase().split('.').pop() ?? ''; };
695
+ /** Ways the asker HOLDS that the gate refused, with the reason — collected as the tiers are tried. */
696
+ const heldButRefused = [];
697
+ for (const [rank, type] of where.types.entries()) {
698
+ // AN UNKNOWN KIND IS NOT THE WRONG KIND (spec 420 §10). A roster row that names a member by display name only, whose
699
+ // account records no type, is still a candidate for a person-shaped argument — dropping it let a stranger's typed
700
+ // `ryan.me` stand alone as the certain reading over the Ryan on her own team (situation baseline, 2026-09-28). It
701
+ // stays in the FIRST tier only, and never for an argument that moves value: money needs a KNOWN treasury.
702
+ const tier = all.filter((c) => suffix(c) === type || (rank === 0 && !VALUE_ARGS.has(where.argName) && c.provenance.source !== 'naming' && !(suffix(c) in CLASS_FOR_SUFFIX)));
703
+ // A SUBSTITUTION IS NOT A RESOLUTION. "Send alice 20 USDC" asks for her treasury; when nothing
704
+ // answers to one, paying her PERSON agent instead is a different destination reached silently — and
705
+ // a payment to the wrong address is not a thing anyone can undo. So for arguments that move value,
706
+ // dropping past the first-choice type is a question, with the reason said plainly.
707
+ //
708
+ // Only for money: a message falling from `.me` to `.org` is the same conversation with the same
709
+ // person's organization, and asking about it would be noise.
710
+ // NOT OF THIS TYPE — so ask what the ones we DID find OWN. "Send money to alice" names the person;
711
+ // her treasury is a thing she HOLDS, and the two are connected by a relationship, not by their
712
+ // names resembling each other. Resolve the person, then follow the link.
713
+ if (!tier.length && rank === 0) {
714
+ const lists = await Promise.all(all.map((c) => ownedAgentsOfType(c.agent, type, lookups, where.subject).catch(() => [])));
715
+ // A WAY THEY HOLD THAT DID NOT WORK travels with the lists, so the question below can name it
716
+ // rather than reporting "nothing called bob is a treasury" to somebody holding a way to reach him.
717
+ for (const l of lists)
718
+ heldButRefused.push(...(l.refusals ?? []));
719
+ const owned = lists.flat().filter((c, i, xs) => xs.findIndex((y) => y.agent === c.agent) === i);
720
+ // WHAT IT IS OWNED BY DECIDES ITS GRADE: a treasury held by an agent her words named only nearly was reached nearly.
721
+ lists.forEach((l, i) => { const o = all[i]; for (const x of l) {
722
+ if (o.provenance.match === 'close')
723
+ nearly.set(x.agent.toLowerCase(), { cand: x, via: o });
724
+ else
725
+ vouch(x.agent);
726
+ } });
727
+ // WHOSE IT IS, FIRST (audit RUNC-3). Ownership is followed to an answer only from ONE agent she holds
728
+ // a link to. With several candidates, "exactly one of them has a treasury anyone can find" used to
729
+ // settle which Alice she meant — decided by who published a `charteredUnder` edge, which is the
730
+ // co-member who listed themselves as "Alice" as readily as her friend. For a value argument that is
731
+ // a question, and each choice says whose account it is and where that agent was found.
732
+ if (moves && owned.length && !(all.length === 1 && heldByAsker(all[0]))) {
733
+ const before = await confirmed(owned);
734
+ if (before)
735
+ return before;
736
+ const holder = (c) => { const i = lists.findIndex((l) => l.some((x) => x.agent === c.agent)); const o = all[i]; return o ? `held by ${o.label} (${FOUND_IN[o.provenance.source] ?? o.provenance.source})` : ''; };
737
+ askToConfirm(all.length > 1
738
+ ? `${all.length} agents answer to “${value}”. Which ${type} should be ${asVerb(where.what)}?`
739
+ : `${unheld(all[0])}. Is their ${type} the one that should be ${asVerb(where.what)}?`, owned, (c) => [candidateHint(c), holder(c)].filter(Boolean).join(' · '));
740
+ }
741
+ if (owned.length === 1) {
742
+ const c = owned[0];
743
+ report({ arg: where.argName, raw: value, agent: c.agent, label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
744
+ return c.agent.toLowerCase();
745
+ }
746
+ if (owned.length > 1) {
747
+ // Several of theirs. Which one is theirs to say — a person may hold more than one treasury and
748
+ // nothing about the ask distinguishes them.
749
+ ask(`Which ${type} should be ${asVerb(where.what)}?`, {
750
+ name: where.argName, label: where.what, type: 'choice', required: true,
751
+ choices: owned.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
752
+ allowOther: true,
753
+ hint: `“${value}” holds ${owned.length} ${type}s — pick the one you mean`,
754
+ });
755
+ }
537
756
  }
538
- if (owned.length > 1) {
539
- // Several of theirs. Which one is theirs to say — a person may hold more than one treasury and
540
- // nothing about the ask distinguishes them.
541
- ask(`Which ${type} should be ${asVerb(where.what)}?`, {
757
+ if (tier.length && rank > 0 && VALUE_ARGS.has(where.argName)) {
758
+ // A WAY THEY HOLD THAT DID NOT WORK is the most useful thing this question can say. Without it a
759
+ // person who was given a way to reach somebody an hour ago is told "nothing called bob is a
760
+ // treasury" — true, and it hides the one fact they could act on.
761
+ ask(heldButRefused.length
762
+ ? `You hold a way to reach ${value}'s ${where.types[0]}, but it could not be used — ${heldButRefused[0]}. Who should be ${where.what}?`
763
+ : `Nothing called “${value}” is a ${where.types[0]}. Who should be ${where.what}?`, {
542
764
  name: where.argName, label: where.what, type: 'choice', required: true,
543
- choices: owned.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
765
+ choices: all.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
766
+ // The right answer is very often NOT in this list — that is the whole reason we are asking —
767
+ // so the person must be able to type it. Telling them to "give it in full" beside a list they
768
+ // cannot add to is a dead end with instructions on it.
544
769
  allowOther: true,
545
- hint: `“${value}” holds ${owned.length} ${type}s — pick the one you mean`,
770
+ hint: `a ${where.types[0]} may exist under another name — give it in full (e.g. ${value}2.${where.types[0]}) to send there instead`,
771
+ }, {
772
+ // THE WAY OUT OF THE DEAD END. Their ${where.types[0]} may exist and simply be unlisted — that
773
+ // is a choice its owner made, and the answer is to ask them, not to guess harder. Offered as a
774
+ // follow-up the person can send, because they should not have to know the phrasing.
775
+ //
776
+ // It carries the AMOUNT when the ask named one, so the request records what this was for and
777
+ // the payment can be finished in one press when the answer comes back. Without it the person
778
+ // has to remember, days later, what they were trying to send and to whom.
779
+ label: `Ask ${value} for a way to reach their ${where.types[0]}`,
780
+ message: where.pendingAmount
781
+ ? `ask ${value} for a way to pay their ${where.types[0]} so I can send ${where.pendingAmount} usdc`
782
+ : `ask ${value} for a way to pay their ${where.types[0]}`,
546
783
  });
547
784
  }
785
+ if (tier.length === 1)
786
+ return settle(tier[0]);
787
+ if (tier.length > 1) {
788
+ // THE ONE THEY CONFIRMED FOR THIS, DURABLY (spec 385): the scoped preference outranks the rolling
789
+ // window, revalidated against these candidates; evidence, never a grant.
790
+ const remembered = await rememberedChoice(lookups, where, value, tier);
791
+ if (remembered) {
792
+ vouch(remembered.agent);
793
+ report({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
794
+ return remembered.agent.toLowerCase();
795
+ }
796
+ // THE ONE THEY CHOSE LAST TIME (spec 370 P7): the same words, settled on one of these before.
797
+ const recentForTier = lookups.recentParties ? await lookups.recentParties().catch(() => []) : [];
798
+ const before = chosenBefore(value, tier, recentForTier);
799
+ if (before && mayDecide(before.agent, tier)) {
800
+ report({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
801
+ return before.agent.toLowerCase();
802
+ }
803
+ // Spec 420 §10 — the nearest in context, before asking.
804
+ const nearTier = where.nearest ? nearestInContext(tier, { ...(where.room ? { room: where.room } : {}), household: where.subject ? await householdMembers(where.subject, lookups).catch(() => []) : [], recent: recentForTier }) : null;
805
+ if (nearTier && mayDecide(nearTier.agent, tier)) {
806
+ report({ arg: where.argName, raw: value, agent: nearTier.agent, label: nearTier.candidate.label, hint: candidateHint(nearTier.candidate), because: nearTier.because, ruleId: 'nearest-in-context', pointId: 'party.nearest' });
807
+ return nearTier.agent;
808
+ }
809
+ ask(`Which “${value}” do you mean?`, {
810
+ name: where.argName, label: where.what, type: 'choice', required: true,
811
+ choices: tier.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
812
+ allowOther: true,
813
+ hint: `${tier.length} of them are what ${where.what} has to be — pick one, or give a full name`,
814
+ }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
815
+ }
548
816
  }
549
- if (tier.length && rank > 0 && VALUE_ARGS.has(where.argName)) {
550
- // A WAY THEY HOLD THAT DID NOT WORK is the most useful thing this question can say. Without it a
551
- // person who was given a way to reach somebody an hour ago is told "nothing called bob is a
552
- // treasury" — true, and it hides the one fact they could act on.
553
- ask(heldButRefused.length
554
- ? `You hold a way to reach ${value}'s ${where.types[0]}, but it could not be used — ${heldButRefused[0]}. Who should be ${where.what}?`
555
- : `Nothing called “${value}” is a ${where.types[0]}. Who should be ${where.what}?`, {
556
- name: where.argName, label: where.what, type: 'choice', required: true,
557
- choices: all.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
558
- // The right answer is very often NOT in this list — that is the whole reason we are asking —
559
- // so the person must be able to type it. Telling them to "give it in full" beside a list they
560
- // cannot add to is a dead end with instructions on it.
561
- allowOther: true,
562
- hint: `a ${where.types[0]} may exist under another name — give it in full (e.g. ${value}2.${where.types[0]}) to send there instead`,
817
+ }
818
+ if (outcome.outcome === 'certain') {
819
+ // ONE match is still a decision, and the person never made it. Report what "nathan" became so the
820
+ // surface can show it before a signature, rather than after — a certain resolution is the case where
821
+ // nobody is asked anything, which is exactly when a wrong one goes unnoticed.
822
+ const c = outcome.candidate;
823
+ // AND ONE MATCH OF THE WRONG KIND IS NOT A MATCH (spec 373). The type loop above narrows, asks and
824
+ // follows ownership — and when every one of those comes up empty it fell through to HERE, which
825
+ // returned the candidate whatever it was. That is how "send carol 1 usdc" put a person's agent on a
826
+ // payment card: `carol.me` was the only thing called carol, and being the only one is not being a
827
+ // treasury. Certain about the wrong kind of thing is a question, not an answer.
828
+ // WHAT KIND IT CLAIMS TO BE — and only a real claim counts. A typed NAME's suffix is a claim
829
+ // (`alice.me`); so is a `kind` the source recorded. A bare label is not: "Missio Nexus" split at its
830
+ // last dot is "missio nexus", which is a name, not a kind, and reading it as one asked "which org should
831
+ // be the organization?" of the one organization called that (caught live, 2026-09-08).
832
+ const knownSuffix = (v) => { const sfx = (v ?? '').toLowerCase().split('.').pop() ?? ''; return v?.includes('.') && sfx in CLASS_FOR_SUFFIX ? sfx : ''; };
833
+ const certainSuffix = knownSuffix(c.name) || suffixForKind(c.kind);
834
+ if (where.types?.length && certainSuffix && !where.types.includes(certainSuffix)) {
835
+ // A READ (no capability) about an agent of another kind resolves to that agent: the read says what it finds
836
+ // ("missio-nexus.org holds no treasury, and balances are kept only in treasuries") — asking "which treasury?" of a
837
+ // question is a worse answer than the true one. An ACT still asks: nothing is done to the wrong kind.
838
+ if (!where.capabilityId) {
839
+ report({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), ...(c.label ? { label: c.label } : {}), hint: `${c.label ?? c.agent} — ${KIND_WORDS[certainSuffix] ?? `a ${certainSuffix}`}` });
840
+ return c.agent.toLowerCase();
841
+ }
842
+ const want = where.types[0];
843
+ ask(`“${value}” is ${c.label ?? c.agent}, ${KIND_WORDS[certainSuffix] ?? `a ${certainSuffix}`}${VALUE_ARGS.has(where.argName) ? ', and money moves only between treasuries' : ''} — which ${want} should be ${asVerb(where.what)}?`, {
844
+ name: where.argName, label: where.what, type: 'address', required: true,
845
+ // A typed name has ONE label (ADR-0061: `<label>.<type>`), so the example is the label with the wanted suffix — never
846
+ // `missio-nexus.org.treasury`.
847
+ hint: `a ${want} name (${value.split('.')[0]}.${want}) or its address — nothing of theirs answered to one`,
563
848
  }, {
564
- // THE WAY OUT OF THE DEAD END. Their ${where.types[0]} may exist and simply be unlisted — that
565
- // is a choice its owner made, and the answer is to ask them, not to guess harder. Offered as a
566
- // follow-up the person can send, because they should not have to know the phrasing.
567
- //
568
- // It carries the AMOUNT when the ask named one, so the request records what this was for and
569
- // the payment can be finished in one press when the answer comes back. Without it the person
570
- // has to remember, days later, what they were trying to send and to whom.
571
- label: `Ask ${value} for a way to reach their ${where.types[0]}`,
849
+ label: `Ask ${value} for a way to reach their ${want}`,
572
850
  message: where.pendingAmount
573
- ? `ask ${value} for a way to pay their ${where.types[0]} so I can send ${where.pendingAmount} usdc`
574
- : `ask ${value} for a way to pay their ${where.types[0]}`,
851
+ ? `ask ${value} for a way to pay their ${want} so I can send ${where.pendingAmount} usdc`
852
+ : `ask ${value} for a way to pay their ${want}`,
575
853
  });
576
854
  }
577
- if (tier.length === 1) {
578
- const c = tier[0];
579
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
580
- return c.agent.toLowerCase();
855
+ return settle(c);
856
+ }
857
+ if (outcome.outcome === 'unknown') {
858
+ // NOTHING SHE HOLDS ANSWERS — and that is the answer (ADR-0013): no public hit becomes the party. What
859
+ // the registry may do is fill the QUESTION: the typed names this label is registered under are offered,
860
+ // each said to be public, and she picks or types another. The one she confirmed before for this word,
861
+ // capability and argument (spec 385) is the only way one of them is used without asking.
862
+ const registered = lookups.resolveName ? await publicNameOptions(value, lookups.resolveName).catch(() => []) : [];
863
+ const sfx = (c) => (c.name ?? '').split('.').pop() ?? '';
864
+ // Money needs a treasury; anything else, a kind the capability takes.
865
+ const options = !where.types?.length ? registered : registered.filter((c) => (moves ? sfx(c) === where.types[0] : where.types.includes(sfx(c))));
866
+ if (options.length) {
867
+ const before = await confirmed(options);
868
+ if (before)
869
+ return before;
870
+ askToConfirm(`I could not find “${value}” among the agents you know. ${options.length === 1 ? 'One public name answers' : `${options.length} public names answer`} to it — is ${options.length === 1 ? 'that' : 'one of them'} who you mean?`, options);
581
871
  }
582
- if (tier.length > 1) {
583
- // THE ONE THEY CONFIRMED FOR THIS, DURABLY (spec 385): the scoped preference outranks the rolling
584
- // window, revalidated against these candidates; evidence, never a grant.
585
- const remembered = await rememberedChoice(lookups, where, value, tier);
586
- if (remembered) {
587
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
588
- return remembered.agent.toLowerCase();
589
- }
590
- // THE ONE THEY CHOSE LAST TIME (spec 370 P7): the same words, settled on one of these before.
591
- const before = lookups.recentParties ? chosenBefore(value, tier, await lookups.recentParties().catch(() => [])) : null;
592
- if (before) {
593
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
872
+ // Say where we looked. "I could not find them" without that leaves a person correcting the wrong thing.
873
+ const said = {
874
+ relationships: 'the agents you are linked to',
875
+ roster: 'the members of your organizations',
876
+ naming: 'the public name registry',
877
+ };
878
+ const where_ = [...new Set(outcome.looked.map((l) => said[l.source] ?? l.source))].join(', ');
879
+ ask(`I could not find “${value}”. Which agent do you mean?`, {
880
+ name: where.argName, label: where.what, type: 'text', required: true,
881
+ hint: `nothing in ${where_ || 'your own agents'} answers to “${value}” — give the full name (e.g. ${value}.me) or the address`,
882
+ });
883
+ }
884
+ // SEVERAL. Never pick: the person is the only one who knows which one they meant.
885
+ //
886
+ // And a list of four things all called "Nathan" is not a choice. Each one carries what tells it APART —
887
+ // its full name, what KIND of agent it is, its address, and WHERE we know it from — because the person
888
+ // is about to authorize something against one of them, and "the second Nathan" is not a thing anyone
889
+ // knows about themselves. There is deliberately no default and no highlighted best: ranking these would
890
+ // need a score, and a score is the thing this resolver refuses to invent (spec 353 §3, ADR-0013).
891
+ const candidates = outcome.outcome === 'ambiguous' ? outcome.candidates : [];
892
+ // Nothing of the RIGHT KIND, when a kind was asked for: say so, and show what does exist. A person who
893
+ // hears "nathan has no treasury" knows what to do next; one who is silently offered nathan.me for a
894
+ // payment does not.
895
+ const wanted = where.types?.length ? `nothing called “${value}” is ${where.types[0] === 'me' ? 'a person' : `a ${where.types[0]}`} — ` : '';
896
+ if (candidates.length > 1) {
897
+ const remembered = await rememberedChoice(lookups, where, value, candidates);
898
+ if (remembered) {
899
+ vouch(remembered.agent);
900
+ report({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
901
+ return remembered.agent.toLowerCase();
902
+ }
903
+ // Spec 420 §10 — the nearest in context, before asking.
904
+ const recentAll = lookups.recentParties ? await lookups.recentParties().catch(() => []) : [];
905
+ const near = where.nearest ? nearestInContext(candidates, { ...(where.room ? { room: where.room } : {}), household: where.subject ? await householdMembers(where.subject, lookups).catch(() => []) : [], recent: recentAll }) : null;
906
+ if (near && mayDecide(near.agent, candidates)) {
907
+ report({ arg: where.argName, raw: value, agent: near.agent, label: near.candidate.label, hint: candidateHint(near.candidate), because: near.because, ruleId: 'nearest-in-context', pointId: 'party.nearest' });
908
+ return near.agent;
909
+ }
910
+ if (lookups.recentParties) {
911
+ const before = chosenBefore(value, candidates, await lookups.recentParties().catch(() => []));
912
+ if (before && mayDecide(before.agent, candidates)) {
913
+ report({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
594
914
  return before.agent.toLowerCase();
595
915
  }
596
- ask(`Which “${value}” do you mean?`, {
597
- name: where.argName, label: where.what, type: 'choice', required: true,
598
- choices: tier.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
599
- allowOther: true,
600
- hint: `${tier.length} of them are what ${where.what} has to be — pick one, or give a full name`,
601
- }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
602
916
  }
603
917
  }
604
- }
605
- if (outcome.outcome === 'certain') {
606
- // ONE match is still a decision, and the person never made it. Report what "nathan" became so the
607
- // surface can show it before a signature, rather than after — a certain resolution is the case where
608
- // nobody is asked anything, which is exactly when a wrong one goes unnoticed.
609
- const c = outcome.candidate;
610
- // AND ONE MATCH OF THE WRONG KIND IS NOT A MATCH (spec 373). The type loop above narrows, asks and
611
- // follows ownership — and when every one of those comes up empty it fell through to HERE, which
612
- // returned the candidate whatever it was. That is how "send carol 1 usdc" put a person's agent on a
613
- // payment card: `carol.me` was the only thing called carol, and being the only one is not being a
614
- // treasury. Certain about the wrong kind of thing is a question, not an answer.
615
- // WHAT KIND IT CLAIMS TO BE — and only a real claim counts. A typed NAME's suffix is a claim
616
- // (`alice.me`); so is a `kind` the source recorded. A bare label is not: "Missio Nexus" split at its
617
- // last dot is "missio nexus", which is a name, not a kind, and reading it as one asked "which org should
618
- // be the organization?" of the one organization called that (caught live, 2026-09-08).
619
- const knownSuffix = (v) => { const sfx = (v ?? '').toLowerCase().split('.').pop() ?? ''; return v?.includes('.') && sfx in CLASS_FOR_SUFFIX ? sfx : ''; };
620
- const kindOf = (k) => { const low = (k ?? '').toLowerCase(); if (!low)
621
- return ''; if (low in CLASS_FOR_SUFFIX)
622
- return low; const byClass = Object.entries(SUFFIX_FOR_CLASS).find(([iri]) => iri.toLowerCase().endsWith(`#${low}agent`) || iri.toLowerCase().endsWith(`#${low}`)); return byClass?.[1] ?? { person: 'me', organization: 'org', service: 'svc' }[low] ?? ''; };
623
- const certainSuffix = knownSuffix(c.name) || kindOf(c.kind);
624
- if (where.types?.length && certainSuffix && !where.types.includes(certainSuffix)) {
625
- const want = where.types[0];
626
- ask(`“${value}” is ${c.label ?? c.agent}, ${certainSuffix === 'me' ? 'a person' : `a ${certainSuffix}`}${VALUE_ARGS.has(where.argName) ? ', and money moves between treasuries' : ''} — which ${want} should be ${asVerb(where.what)}?`, {
627
- name: where.argName, label: where.what, type: 'address', required: true,
628
- hint: `a ${want} name (${value}.${want}) or its address — nothing of theirs answered to one`,
629
- }, {
630
- label: `Ask ${value} for a way to reach their ${want}`,
631
- message: where.pendingAmount
632
- ? `ask ${value} for a way to pay their ${want} so I can send ${where.pendingAmount} usdc`
633
- : `ask ${value} for a way to pay their ${want}`,
634
- });
635
- }
636
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
637
- return c.agent.toLowerCase();
638
- }
639
- if (outcome.outcome === 'unknown') {
640
- // Say where we looked. "I could not find them" without that leaves a person correcting the wrong thing.
641
- const said = {
642
- relationships: 'the agents you are linked to',
643
- roster: 'the members of your organizations',
644
- naming: 'the naming service',
645
- };
646
- const where_ = [...new Set(outcome.looked.map((l) => said[l.source] ?? l.source))].join(', ');
647
- ask(`I could not find “${value}”. Which agent do you mean?`, {
648
- name: where.argName, label: where.what, type: 'text', required: true,
649
- hint: `nothing in ${where_ || 'your own agents'} answers to “${value}” — give the full name (e.g. ${value}.me) or the address`,
650
- });
651
- }
652
- // SEVERAL. Never pick: the person is the only one who knows which one they meant.
653
- //
654
- // And a list of four things all called "Nathan" is not a choice. Each one carries what tells it APART —
655
- // its full name, what KIND of agent it is, its address, and WHERE we know it from — because the person
656
- // is about to authorize something against one of them, and "the second Nathan" is not a thing anyone
657
- // knows about themselves. There is deliberately no default and no highlighted best: ranking these would
658
- // need a score, and a score is the thing this resolver refuses to invent (spec 353 §3, ADR-0013).
659
- const candidates = outcome.outcome === 'ambiguous' ? outcome.candidates : [];
660
- // Nothing of the RIGHT KIND, when a kind was asked for: say so, and show what does exist. A person who
661
- // hears "nathan has no treasury" knows what to do next; one who is silently offered nathan.me for a
662
- // payment does not.
663
- const wanted = where.types?.length ? `nothing called “${value}” is ${where.types[0] === 'me' ? 'a person' : `a ${where.types[0]}`} — ` : '';
664
- if (candidates.length > 1) {
665
- const remembered = await rememberedChoice(lookups, where, value, candidates);
666
- if (remembered) {
667
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
668
- return remembered.agent.toLowerCase();
669
- }
670
- if (lookups.recentParties) {
671
- const before = chosenBefore(value, candidates, await lookups.recentParties().catch(() => []));
672
- if (before) {
673
- lookups.onResolved?.({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
674
- return before.agent.toLowerCase();
675
- }
918
+ ask(`Which “${value}” do you mean?`, {
919
+ name: where.argName, label: where.what, type: 'choice', required: true,
920
+ choices: candidates.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
921
+ // Someone they know may not be among these, and knowing the full name is a real answer.
922
+ allowOther: true,
923
+ hint: `${wanted}${candidates.length} agents you know answer to “${value}” — pick one, or give a full name`,
924
+ }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
925
+ throw new Error('unreachable');
926
+ };
927
+ const agent = (await fromWords()).toLowerCase();
928
+ if (moves && !exactly.has(agent)) {
929
+ const n = nearly.get(agent);
930
+ const cand = n?.cand ?? { agent, label: agent, provenance: { tier: 'private', source: 'unverified' } };
931
+ const before = await confirmed([cand]);
932
+ if (before) {
933
+ if (pending)
934
+ lookups.onResolved?.(pending);
935
+ return before;
676
936
  }
937
+ const closest = n?.via ?? n?.cand;
938
+ askToConfirm(closest
939
+ ? `“${value}” is not a name you hold; the closest is ${closest.label}${n?.via ? `, and ${cand.label} is theirs` : ''}. Is this who should be ${asVerb(where.what)}?`
940
+ : `“${value}” does not name ${cand.label} exactly. Is this who should be ${asVerb(where.what)}?`, [cand], candidateHint, 'closest to what you said — pick it to confirm, or give another name or address');
677
941
  }
678
- ask(`Which “${value}” do you mean?`, {
679
- name: where.argName, label: where.what, type: 'choice', required: true,
680
- choices: candidates.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
681
- // Someone they know may not be among these, and knowing the full name is a real answer.
682
- allowOther: true,
683
- hint: `${wanted}${candidates.length} agents you know answer to “${value}” — pick one, or give a full name`,
684
- }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
685
- throw new Error('unreachable');
942
+ if (pending)
943
+ lookups.onResolved?.(pending);
944
+ return agent;
686
945
  }
687
946
  //# sourceMappingURL=party-resolution.js.map