@runeditrun/rer 0.2.90 → 0.2.91

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.
@@ -16,6 +16,7 @@ import { verificationWebhooks } from './agent-webhooks.mjs';
16
16
  import { verificationInvoke, verificationJourney } from './agent-verifier.mjs';
17
17
  import { verificationBindings } from './agent-bindings.mjs';
18
18
  import { journeyFixtures } from './agent-journey-fixtures.mjs';
19
+ import { verificationAgentInitializer } from './agent-initializer.mjs';
19
20
 
20
21
  function finish(result, report) {
21
22
  if (result.capabilities) report(`Agent capabilities (${result.capabilities.mode}): declared=${result.capabilities.declared.join(',')}; refused=${result.capabilities.refused.join(',')}; unscoped=${result.capabilities.unscoped.join(',')}.`);
@@ -35,6 +36,7 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
35
36
  const manifest = setupManifest ?? JSON.parse(await readFile(join(root, 'rer-setup.json'), 'utf8'));
36
37
  const claim = manifest.steps?.find(step => step.type === 'owner-claim');
37
38
  const verification = declared.surface.verification ?? {};
39
+ const initializeAgent = await verificationAgentInitializer(root, verification.agent);
38
40
  const workerDriver = await verificationInvoke(root, verification.invoke);
39
41
  let prove;
40
42
  if (verification.proof !== undefined) {
@@ -43,7 +45,15 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
43
45
  prove = (await import(pathToFileURL(resolve(root, verification.proof.module)))).default;
44
46
  if (typeof prove !== 'function') throw new RerError('agent_proof_invalid', 'verification.proof module must default-export a native proof test function.', 1);
45
47
  }
46
- const principals = await verificationSponsors(root, verification), native = principals[0], { email, sub } = native;
48
+ const negativeOnly = new Set();
49
+ const sponsorDeclarations = Array.isArray(verification.sponsors) ? verification.sponsors.map((principal, index) => {
50
+ if (!principal || typeof principal !== 'object' || Array.isArray(principal)) return principal;
51
+ const { negativeOnly: probeOnly, ...declaration } = principal;
52
+ if (probeOnly !== undefined && typeof probeOnly !== 'boolean' || probeOnly && index === 0) throw new RerError('agent_sponsors_invalid', 'Only additional verification sponsors may declare negativeOnly:true.', 1);
53
+ if (probeOnly) negativeOnly.add(principal.label);
54
+ return declaration;
55
+ }) : verification.sponsors;
56
+ const principals = await verificationSponsors(root, { ...verification, sponsors: sponsorDeclarations }), native = principals[0], { email, sub } = native;
47
57
  if (verification.reviewers !== undefined && !native.initialize) throw new RerError('agent_reviewer_invalid', 'verification.reviewers requires a native owner initializer to drive invitation and independent review.', 1);
48
58
  const reviewers = await verificationReviewers(root, verification.reviewers, email);
49
59
  if (claim?.mode && !['signed', 'setup-token'].includes(claim.mode) && !native.initialize) throw new RerError('agent_owner_invalid', `Owner claim mode ${claim.mode} requires verification.owner.initializer using the seed's production lifecycle.`, 1);
@@ -130,10 +140,11 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
130
140
  }
131
141
  const secrets = await network.provision(hosted);
132
142
  const webhooks = await verificationWebhooks(root, verification.webhooks, secrets);
133
- const journey = await verificationJourney(root, verification.journey, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures });
134
- const prepare = await journeyFixtures(root, verification.fixtures, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures });
143
+ const journey = await verificationJourney(root, verification.journey, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, database: hosted.database });
144
+ const prepare = await journeyFixtures(root, verification.fixtures, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, database: hosted.database });
135
145
  const result = await runAgentDoorConformance({ fetch: request, origin: hosted.origin, surface: declared.surface,
136
- signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors, webhooks, business, prove, ...journey, prepare, invoke: workerDriver?.run(hosted),
146
+ signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors: sponsors.filter(person => !negativeOnly.has(person.label)), webhooks, business, prove, ...journey, prepare, invoke: workerDriver?.run(hosted),
147
+ initializeAgent: initializeAgent && (({ agentId, person }) => initializeAgent({ agentId, person, request, origin: hosted.origin, mail: network.mail, fixtures: network.fixtures })),
137
148
  });
138
149
  const points = [...result.points, ...reviewers.points()];
139
150
  return finish({ ...result, points, ok: points.every(point => point.ok) }, report);
@@ -0,0 +1,27 @@
1
+ import { resolve } from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { contained } from './project.mjs';
4
+ import { RerError } from './errors.mjs';
5
+
6
+ /** Load test tooling before starting the disposable installation. */
7
+ export async function verificationAgentInitializer(root, declaration) {
8
+ if (declaration === undefined) return undefined;
9
+ const invalid = () => new RerError('agent_initializer_invalid', 'verification.agent must name a contained initializer module with a function default export.', 1);
10
+ if (!declaration || typeof declaration !== 'object' || Array.isArray(declaration)
11
+ || Object.keys(declaration).join(',') !== 'initializer' || typeof declaration.initializer !== 'string') throw invalid();
12
+ let initialize;
13
+ try {
14
+ await contained(root, declaration.initializer);
15
+ initialize = (await import(pathToFileURL(resolve(root, declaration.initializer)))).default;
16
+ if (typeof initialize !== 'function') throw invalid();
17
+ } catch { throw invalid(); }
18
+ return ({ agentId, person, request, origin, mail, fixtures }) => initialize({ agentId, origin, email: person.email, sub: person.sub, mail, fixtures,
19
+ request: (absolute, { headers, ...init } = {}) => {
20
+ const sessionHeaders = new Headers(headers);
21
+ sessionHeaders.set('Origin', origin);
22
+ sessionHeaders.set('Cookie', person.cookie);
23
+ if (!sessionHeaders.has('Content-Type')) sessionHeaders.set('Content-Type', 'application/json');
24
+ return request(new URL(absolute, origin).href, { ...init, headers: sessionHeaders });
25
+ },
26
+ });
27
+ }
@@ -2,16 +2,20 @@ import { resolve } from 'node:path';
2
2
  import { pathToFileURL } from 'node:url';
3
3
  import { contained } from './project.mjs';
4
4
  import { RerError } from './errors.mjs';
5
+ import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
5
6
 
6
- /** Test tooling receives only the disposable installation's existing doors. */
7
+ /** Test tooling receives the disposable installation's doors and state reader. */
7
8
  export async function journeyFixtures(root, declaration, context) {
8
9
  if (declaration === undefined) return undefined;
9
10
  if (!declaration || Object.keys(declaration).join(',') !== 'module' || typeof declaration.module !== 'string') throw new RerError('agent_fixtures_invalid', 'verification.fixtures must name a contained test module.', 1);
10
11
  await contained(root, declaration.module);
11
12
  const prepare = (await import(pathToFileURL(resolve(root, declaration.module)))).default;
12
13
  if (typeof prepare !== 'function') throw new RerError('agent_fixtures_invalid', 'verification.fixtures module must default-export a phase preparation function.', 1);
13
- return async ({ phase, tool }) => {
14
- try { return await prepare({ ...context, phase, tool }); }
15
- catch { throw new Error('Native phase preparation failed; no captured mail, credentials or fixture values are logged.'); }
14
+ return async ({ phase, tool, now }) => {
15
+ try { return await prepare({ ...context, phase, tool, now }); }
16
+ catch (error) {
17
+ if (error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
18
+ throw new Error('Native phase preparation failed; no captured mail, credentials or fixture values are logged.');
19
+ }
16
20
  };
17
21
  }
@@ -2,6 +2,7 @@ import { resolve } from 'node:path';
2
2
  import { pathToFileURL } from 'node:url';
3
3
  import { contained } from './project.mjs';
4
4
  import { RerError } from './errors.mjs';
5
+ import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
5
6
 
6
7
  export async function verificationInvoke(root, config) {
7
8
  if (config === undefined) return;
@@ -23,7 +24,10 @@ export async function verificationJourney(root, path, context) {
23
24
  if (typeof module.default !== 'function' || ['beforeStep', 'afterStep'].some(key => module[key] !== undefined && typeof module[key] !== 'function')) throw new RerError('agent_journey_invalid', 'verification.journey must default-export a native journey; optional beforeStep and afterStep exports must be functions.', 1);
24
25
  const call = async (fn, value) => {
25
26
  try { await fn({ ...context, ...value }); }
26
- catch { throw new Error('Native verification journey failed; no captured mail or fixture values are logged.'); }
27
+ catch (error) {
28
+ if (error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
29
+ throw new Error('Native verification journey failed; no captured mail or fixture values are logged.');
30
+ }
27
31
  };
28
32
  return { nativeJourney: value => call(module.default, value),
29
33
  nativeStep: async ({ stage, ...value }) => { if (module[stage]) await call(module[stage], value); },
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.91
4
+
5
+ - Security: the agent door refuses a Business access token whose email is no longer its subject's current native email, with the same HTTP 401 and no effect as an unknown or inactive sponsor, so a token no longer outlives a change of address.
6
+ - Probe sponsor admission with verifier-signed access tokens for an unknown subject and a known subject with a changed email. Native negative-phase fixtures may declare `sponsors: {inactive: {sub,email}, excluded: {sub,email}}` for lifecycle-prepared persons. Each probe requires a typed HTTP 401/403 refusal and an unchanged native witness; omitted states are reported as undeclared without passing points. Fixtures receive no signing authority and failure diagnostics omit their values and identities. See `modules/agent-door/ADOPTING.md`.
7
+ - Additional `verification.sponsors` may declare `negativeOnly: true` when their native subjects must be registered for these probes. Their normal initialization and Business binding still run; successful cross-sponsor journeys remain required for regular sponsors.
8
+
9
+ - Account for linked native continuations and refused approval executions in agent-door audit conformance without shifting later harness rows; unrelated or policy-inconsistent extra rows still fail.
10
+
11
+ - Refuse continuation tools under unset, removed or unavailable policy and Business Pause before validating or resolving native continuation items, retaining current scope, revocation and once-only execution checks.
12
+
13
+ - Pass the disposable state reader and current verifier time to conformance phase fixtures and native step hooks. Database refusals retain a typed, redacted diagnostic; writable backdated history remains pending at the hosted state boundary.
14
+
15
+ - Audit native refusals under review policy by their refused outcome, matching returned code and absence of a review; retain linked reviews for completed effects and reject changes in bracketing native witnesses.
16
+
17
+ - Run a contained `verification.agent.initializer` once per chosen conformance agent ID, before its first public-door phase, using only the sponsor's session-bound native request and disposable mail/fixture controls. Invalid declarations refuse before installation and failures use a fixed diagnostic.
18
+
19
+ - Resource adapters now receive consent and operation identity; a resource that changes between check and read refuses `resource_changed`.
20
+
21
+ - For the 0.2.91 seed refresh, relock run-uptime (workflow lines 98, 256) and run-happytohelp (47, 170): drop `github.run_attempt` from shared build artifact names, use `<seed>-verify-build-<sha>-<run_id>` for both upload and download, and add `overwrite: true` to the upload. Verify's workflow guard rejects attempt-qualified downloads and their shared uploads; apply the same patch to any seed with this pattern on its next refresh. See `export/VERIFY-WORKFLOW.md`.
22
+
3
23
  ## 0.2.90
4
24
 
5
25
  - Withhold optional copied Base modules and workflow helpers whose required packages the edition has not declared. Refresh preserves supported dependency closure and explains the package declaration needed to opt in.
@@ -6,19 +6,88 @@ import { targetIdentity } from './target.mjs';
6
6
  import { auditRows } from './audit-rows.mjs';
7
7
 
8
8
  export { auditRows } from './audit-rows.mjs';
9
+
10
+ // Reuse recorded native witnesses without replaying the refused operation or
11
+ // comparing across another effect or policy/fixture round.
12
+ function refusalWitness(c, calls, index, direction) {
13
+ const witness = c.surface.witness;
14
+ for (let i = index + direction; i >= 0 && i < calls.length; i += direction) {
15
+ const call = calls[i];
16
+ if (call.decision?.revision !== calls[index].decision.revision) return;
17
+ if (call.name === witness.tool && isDeepStrictEqual(call.args, c.resolve(witness.args))) return call.result?.isError ? undefined : call.result?.structuredContent;
18
+ if (!c.surface.tools.find(tool => tool.name === call.name)?.readOnly && !call.code) return;
19
+ }
20
+ }
21
+
22
+ function reviewProblem(c, calls, index, row, reviews) {
23
+ const call = calls[index];
24
+ if (row.outcome === 'refused') {
25
+ if (typeof call.code !== 'string' || !call.code) return 'the returned refusal code is missing';
26
+ if (row.code !== call.code) return 'the audit refusal code differs from the returned code';
27
+ if (row.review !== null || call.result?._meta?.['com.runeditrun/review'] || reviews.some(review => review.decision_id === row.id)) return 'a refused call opened a review row';
28
+ const before = refusalWitness(c, calls, index, -1), after = refusalWitness(c, calls, index, 1);
29
+ if (before !== undefined && after !== undefined && !isDeepStrictEqual(before, after)) return 'the native witness changed across the refusal';
30
+ return;
31
+ }
32
+ if (!['done', 'replayed'].includes(row.outcome)) return `the audit outcome ${row.outcome} is neither completed nor refused`;
33
+ if (row.code != null || call.code || call.result?.isError) return 'the completed audit row contradicts the returned refusal code';
34
+ if (!row.review?.id) return 'the completed call is missing its review row';
35
+ if (!reviews.some(review => review.id === row.review.id && review.decision_id === (row.replay_of ?? row.id))) return 'the review row is not linked to the completed call';
36
+ }
37
+
38
+ // Only an earlier harness row can establish the origin of native work. A
39
+ // marker alone never exempts an embedded call from the ordered expectations.
40
+ function continuationRows(c, rows, differs, report = () => {}) {
41
+ const recorded = new Map(c.calls.filter(call => call.kind !== 'approval/execute' && call.decision?.id).map(call => [call.decision.id, call]));
42
+ const origins = new Map(), accepted = new Set(); let index = 0;
43
+ for (const row of rows) {
44
+ const call = recorded.get(row.id);
45
+ if (call) {
46
+ const principal = call.principal ?? { agent: { id: c.agentId, name: 'Agent door conformance', specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id, clientId: call.kind === 'embedded' ? null : 'rer-agent-conformance' };
47
+ if (row.tool === call.name && row.agent?.id === principal.agent.id && row.agent?.name === principal.agent.name && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && row.consent === principal.consent && row.client_id === principal.clientId && typeof row.operation_id === 'string' && row.operation_id) {
48
+ if (!origins.has(row.operation_id)) origins.set(row.operation_id, []);
49
+ origins.get(row.operation_id).push(row);
50
+ }
51
+ continue;
52
+ }
53
+ if (row.continuation_item_id === undefined) continue;
54
+ const origin = origins.get(row.operation_id)?.find(item => isDeepStrictEqual(item.agent, row.agent) && isDeepStrictEqual(item.sponsor, row.sponsor) && item.consent === row.consent && item.client_id === row.client_id);
55
+ const dispositions = ['autonomous', 'review', 'approval', 'blocked', 'unset', 'unavailable', 'paused'];
56
+ const classes = Array.isArray(row.classes) && row.classes.length > 0 && new Set(classIds(row.classes)).size === row.classes.length && row.classes.every(item => AGENT_CLASSES.includes(item.class) && item.facts && typeof item.facts === 'object');
57
+ const rules = classes && Array.isArray(row.rules) && isDeepStrictEqual(classIds(row.rules), classIds(row.classes)) && row.rules.every(rule => dispositions.includes(rule.do) && (['unset', 'unavailable', 'paused'].includes(rule.do) ? rule.rule === null : typeof rule.rule === 'string' && rule.rule.length > 0));
58
+ const valid = Boolean(origin) && row.door === 'embedded' && typeof row.continuation_item_id === 'string' && row.continuation_item_id.trim().length > 0
59
+ && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at))
60
+ && Number.isSafeInteger(row.revision) && row.revision > 0 && rules && row.decision === dispositions[Math.max(...row.rules.map(rule => dispositions.indexOf(rule.do)))]
61
+ && (row.outcome === 'done' && ['autonomous', 'review', 'approval'].includes(row.decision) && row.code === null || row.outcome === 'refused' && typeof row.code === 'string' && row.code.length > 0) && differs === 0;
62
+ report(`BASE-AGENT-009.1.continuation.${index++}`, valid, 'Native continuation must link an earlier harness operation with the same agent, sponsor, consent and client, a recorded policy decision and a completed or coded refused outcome.');
63
+ if (valid) accepted.add(row);
64
+ }
65
+ return accepted;
66
+ }
67
+
9
68
  export async function auditPhase(c) {
10
69
  const { rows, differs } = await auditRows(c), expected = [...c.calls];
11
- c.add('BASE-AGENT-009.1.count', rows.length === expected.length, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions, found ${rows.length}.`);
70
+ const reviews = expected.some(call => call.decision?.disposition === 'review') ? (await c.personJson('/agents/api/reviews')).reviews : [];
71
+ if (!Array.isArray(reviews)) throw new Error('Reviews API must return reviews');
72
+ const continuations = continuationRows(c, rows, differs, c.add);
73
+ c.add('BASE-AGENT-009.1.count', rows.length === expected.length + continuations.size, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions plus ${continuations.size} native continuations, found ${rows.length}.`);
12
74
  c.add('BASE-AGENT-009.1.unique', new Set(rows.map(row => row.id)).size === rows.length, 'Every tool call, resource read and approval execution must have its own audit ID.');
13
- const perAgent = new Map();
75
+ const perAgent = new Map(), positions = new Map(), previous = new Map();
14
76
  for (const row of rows) {
77
+ if (continuations.has(row)) continue;
15
78
  if (!perAgent.has(row.agent?.id)) perAgent.set(row.agent?.id, []);
79
+ positions.set(row, perAgent.get(row.agent?.id).length);
16
80
  perAgent.get(row.agent?.id).push(row);
17
81
  }
18
82
  for (const [index, call] of expected.entries()) {
19
83
  const principal = call.principal ?? { agent: { id: c.agentId, specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id };
20
- const row = perAgent.get(principal.agent.id)?.shift(), decision = call.decision;
21
- c.add(`BASE-AGENT-009.1.call.${index}`, Boolean(row) && row.tool === call.name && row.consent === principal.consent && row.agent?.id === principal.agent.id && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && (!call.principal || row.client_id === principal.clientId && row.agent?.name === principal.agent.name) && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at)) && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp'), `${call.name} lacks its complete ordered audit row.`);
84
+ const candidates = perAgent.get(principal.agent.id) ?? [], decision = call.decision;
85
+ const match = candidates.findIndex(row => call.kind === 'approval/execute' ? row.decision_id === decision?.id && row.id !== decision?.id
86
+ : decision?.id ? row.id === decision.id : row.tool === call.name && row.decision_id === null && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp') && row.code === (call.code ?? null));
87
+ const row = match < 0 ? undefined : candidates.splice(match, 1)[0];
88
+ const ordered = row && positions.get(row) > (previous.get(principal.agent.id) ?? -1);
89
+ if (row) previous.set(principal.agent.id, positions.get(row));
90
+ c.add(`BASE-AGENT-009.1.call.${index}`, ordered && row.tool === call.name && row.consent === principal.consent && row.agent?.id === principal.agent.id && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && (!call.principal || row.client_id === principal.clientId && row.agent?.name === principal.agent.name) && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at)) && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp'), `${call.name} lacks its complete ordered audit row.`);
22
91
  if (!row) continue;
23
92
  if (call.code === 'native_proof_required') c.add(`BASE-AGENT-004.native-proof.audit.${index}`, row.outcome === 'refused' && row.code === call.code, `${call.name} native proof challenge must retain its refused audit outcome.`);
24
93
  c.add(`BASE-AGENT-009.1.resource.${index}`, call.kind === 'resources/read' ? row.resource === call.args.uri : row.resource === null || targetIdentity(row.resource), `${call.name} audit resource must identify the requested URI or the seed-resolved native kind and id.`);
@@ -27,11 +96,16 @@ export async function auditPhase(c) {
27
96
  c.add(`BASE-AGENT-006.6.audit.${index}`, validClasses && (decision ? isDeepStrictEqual(classIds(row.classes), classIds(decision.classes)) && decision.classes.every(item => row.classes.some(actual => actual.class === item.class && isDeepStrictEqual(actual.facts, item.facts))) : call.kind === 'resources/read' || row.classes.length === 0), `${call.name} audit classes/facts differ from its computed decision.`);
28
97
  if (decision) c.add(`BASE-AGENT-009.2.decision.${index}`, (call.kind === 'approval/execute' || row.id === decision.id) && row.decision === decision.disposition && row.revision === decision.revision && isDeepStrictEqual(row.rules, decision.classes.map(({ class: cls, rule, do: disposition }) => ({ class: cls, rule, do: disposition }))), `${call.name} audit decision or revision differs from the response.`);
29
98
  else if (call.kind === 'resources/read') c.add(`BASE-AGENT-009.2.resource-rules.${index}`, Array.isArray(row.rules) && isDeepStrictEqual(classIds(row.rules), classIds(row.classes)) && row.rules.every(rule => typeof rule.rule === 'string' && ['autonomous', 'review', 'approval', 'blocked', 'unset'].includes(rule.do)), 'Resource audit classes must each carry the applied policy rule and disposition.');
30
- if (decision?.disposition === 'review') c.add(`BASE-AGENT-009.4.review.${index}`, Boolean(row.review?.id), `${call.name} was decided review without a review row.`);
99
+ if (decision?.disposition === 'review') {
100
+ const problem = reviewProblem(c, expected, index, row, reviews);
101
+ c.add(`BASE-AGENT-009.4.review.${index}`, !problem, `${call.name} review audit: ${problem}.`);
102
+ }
31
103
  if (call.pending) c.add(`BASE-AGENT-009.2.pending.${index}`, row.outcome === 'pending' && Boolean(call.approval?.id) && row.approval?.id === call.approval.id, `${call.name} must retain its original pending audit outcome and approval handle after the approval executes.`);
32
- if (call.kind === 'approval/execute') c.add(`BASE-AGENT-008.5.execution.${index}`, row.approval?.id === call.approvalId && row.approval.by?.includes(c.sponsor.id) && row.outcome === 'done', `${call.name} approved execution lacks its completed row and named sponsor approval.`);
104
+ if (call.kind === 'approval/execute') c.add(`BASE-AGENT-008.5.execution.${index}`, row.approval?.id === call.approvalId && row.approval.by?.includes(principal.sponsor) && row.outcome === (call.state === 'refused' ? 'refused' : 'done') && row.code === (call.code ?? null), `${call.name} approval execution must retain its returned outcome, code and named sponsor approval.`);
33
105
  if (call.result?._meta?.['com.runeditrun/receipt']) c.add(`BASE-AGENT-008.5.audit.${index}`, Boolean(row.approval?.id) && row.approval.by?.includes(row.sponsor.id), `${call.name} approval receipt lacks the signed-in sponsor as approver.`);
34
106
  }
107
+ let extraIndex = 0;
108
+ for (const extra of perAgent.values()) for (const row of extra) c.add(`BASE-AGENT-009.1.extra.${extraIndex++}`, false, `${row.tool} has no recorded harness call or valid native continuation.`);
35
109
  c.add('BASE-AGENT-007.7.differs-from-policy', differs === 0, `Audit evidence has ${differs} decisions that differ from the policy in force.`);
36
110
  // Audit is read before the events tool: its own call is audited as well, but
37
111
  // cannot occur in a snapshot taken before it was made.
@@ -61,5 +135,6 @@ export async function auditPhase(c) {
61
135
  c.add('BASE-AGENT-010.3.cursor', first.length > 0 && isDeepStrictEqual(first, second.slice(0, first.length)) && first[0] === events[1].id, 'Replaying one cursor must return the same retained event ids in order.');
62
136
  }
63
137
  const final = await auditRows(c);
64
- c.add('BASE-AGENT-009.1.events-audited', final.rows.length === c.calls.length && final.differs === 0, `events.list audit calls mismatch: ${final.rows.length} audit rows for ${c.calls.length} calls.`);
138
+ const finalContinuations = continuationRows(c, final.rows, final.differs);
139
+ c.add('BASE-AGENT-009.1.events-audited', final.rows.length === c.calls.length + finalContinuations.size && final.differs === 0, `events.list audit calls mismatch: ${final.rows.length} audit rows for ${c.calls.length} calls and ${finalContinuations.size} native continuations.`);
65
140
  }
@@ -1,4 +1,12 @@
1
1
  import { auditRows } from './audit-rows.mjs';
2
+ import { seconds } from './crypto.mjs';
3
+
4
+ export class FixtureDatabaseError extends Error {
5
+ constructor() {
6
+ super('agent_fixtures_database_unavailable: Disposable database access refused; fixture values, records and SQL are not logged.');
7
+ this.code = 'agent_fixtures_database_unavailable';
8
+ }
9
+ }
2
10
 
3
11
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
12
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -6,17 +14,24 @@ const text = value => typeof value === 'string' && value.trim().length > 0;
6
14
  /** Each round gets new native state, never a previous round's consumed values. */
7
15
  export function phaseFixtures(c, prepare) {
8
16
  c.fixtureValues = {};
17
+ c.fixtureSponsors = {};
9
18
  c.clients = new Map();
10
19
  c.nativeAgents = new Set();
11
20
  c.fixtureAuditIds = new Set();
12
21
  c.prepare = async phase => {
13
22
  c.fixtureValues = {};
23
+ c.fixtureSponsors = {};
14
24
  c.clients.clear();
15
25
  if (!prepare) return;
16
26
  try {
17
27
  const before = new Set((await auditRows(c, { agents: [null], includeFixtures: true })).rows.map(row => row.id));
18
- const result = await prepare({ phase, tool: c.tool });
19
- if (!object(result) || Object.keys(result).some(key => !['values', 'clients'].includes(key)) || !object(result.values ?? {}) || !object(result.clients ?? {})) throw new Error('Native phase preparation must return {values,clients}.');
28
+ const result = await prepare({ phase, tool: c.tool, now: seconds(c.now) * 1000 });
29
+ if (!object(result) || Object.keys(result).some(key => !['values', 'clients', 'sponsors'].includes(key)) || !object(result.values ?? {}) || !object(result.clients ?? {}) || !object(result.sponsors ?? {})) throw new Error('Native phase preparation must return {values,clients,sponsors}.');
30
+ for (const [kind, sponsor] of Object.entries(result.sponsors ?? {})) {
31
+ if (!['inactive', 'excluded'].includes(kind) || !object(sponsor) || Object.keys(sponsor).sort().join(',') !== 'email,sub'
32
+ || !text(sponsor.sub) || !text(sponsor.email) || sponsor.email !== sponsor.email.trim().toLowerCase()
33
+ || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(sponsor.email)) throw new Error('Native fixture sponsors require a subject and canonical email for an inactive or excluded person.');
34
+ }
20
35
  for (const [label, client] of Object.entries(result.clients ?? {})) {
21
36
  if (!text(label) || !object(client) || Object.keys(client).sort().join(',') !== 'agent,clientId,token'
22
37
  || !text(client.token) || !text(client.clientId) || !object(client.agent) || !text(client.agent.id) || !text(client.agent.name)
@@ -26,14 +41,18 @@ export function phaseFixtures(c, prepare) {
26
41
  c.nativeAgents.add(client.agent.id);
27
42
  }
28
43
  c.fixtureValues = structuredClone(result.values ?? {});
44
+ c.fixtureSponsors = structuredClone(result.sponsors ?? {});
29
45
  const setup = await auditRows(c, { agents: [...c.clients.values()].map(client => client.agent.id), includeFixtures: true });
30
46
  for (const row of setup.rows) if (!before.has(row.id)) {
31
47
  const client = [...c.clients.values()].find(client => client.agent.id === row.agent?.id);
32
48
  if (row.sponsor?.id !== c.sponsor.id || row.client_id !== client.clientId || row.agent?.name !== client.agent.name || row.agent?.specialist !== client.agent.specialist || row.consent !== null) throw new Error('Native fixture preparation identity differs from its declared client.');
33
49
  c.fixtureAuditIds.add(row.id);
34
50
  }
35
- } catch {
51
+ } catch (error) {
36
52
  c.clients.clear();
53
+ c.fixtureValues = {};
54
+ c.fixtureSponsors = {};
55
+ if (error instanceof FixtureDatabaseError) throw error;
37
56
  throw new Error('Native phase preparation failed; fixture values are not logged.');
38
57
  }
39
58
  };
@@ -19,13 +19,20 @@ import { invocationPhase } from './invocation.mjs';
19
19
  export { validateAgentSurface } from './surface.mjs';
20
20
 
21
21
  /** Run against a fresh, real installation using its HTTP and person doors. */
22
- export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare }) {
22
+ export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare, initializeAgent }) {
23
23
  const validation = validateAgentSurface(surface), points = [...validation.points];
24
24
  if (!validation.ok) return { ok: false, points };
25
25
  const capabilities = capabilitySet(surface.capabilities);
26
26
  surface = scopedSurface(surface);
27
27
  if (typeof fetch !== 'function' || !signer?.privateKey || !signer.issuer || !signer.installationId || !signer.kid || !person?.email || !person.cookie || typeof person.sub !== 'string' || !person.sub.trim() || typeof consent !== 'string' || !consent.trim() || new URL(origin).origin !== origin) throw new TypeError('Conformance requires fetch, canonical origin, signer, consent and signed-in person {email,cookie,sub}');
28
28
  const c = createProtocol({ fetch, origin, surface, signer, person, business, consent, now, prove, nativeStep, prepare, points, agentId: `rer-conformance-${randomUUID()}`, seq: 0, revision: 0, listed: new Map() });
29
+ if (initializeAgent) {
30
+ try { await initializeAgent({ agentId: c.agentId, person }); }
31
+ catch {
32
+ c.add('BASE-AGENT-001.agent-initializer', false, 'Native agent initialization failed; no captured mail, credentials or fixture values are logged.');
33
+ return { ok: false, points, capabilities };
34
+ }
35
+ }
29
36
  await c.phase('BASE-AGENT-001.transport', () => discoverDoor(c));
30
37
  await c.phase('BASE-AGENT-007.phase0', () => unsetPolicy(c, true));
31
38
  await c.phase('BASE-AGENT-007.phase1', () => removalPhase(c));
@@ -43,6 +50,6 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
43
50
  await c.phase('BASE-AGENT-subset.refusals', () => refusalPhase(c));
44
51
  if (capabilities.mode === 'declared' && offers(surface.capabilities, 'subscriptions')) await c.phase('BASE-AGENT-subset.subscriptions', () => subscriptionPhase(c));
45
52
  await c.phase('BASE-AGENT-009.phase7', () => auditPhase(c));
46
- if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors));
53
+ if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors, initializeAgent));
47
54
  return { ok: points.every(point => point.ok), points, capabilities };
48
55
  }
@@ -20,6 +20,31 @@ export async function negativePhase(c) {
20
20
  const answer = await c.mcp('tools/list', {}, { token: await accessToken(c, overrides) });
21
21
  c.add(`BASE-AGENT-004.${name === 'audience' ? '2' : '3'}.${name}`, answer.status === 401, `${name} token returned HTTP ${answer.status}, expected 401.`);
22
22
  }
23
+ const sponsorProbes = [
24
+ ['unknown', { sub: crypto.randomUUID() }],
25
+ ['changed-email', { email: `changed-${crypto.randomUUID()}@example.invalid` }],
26
+ ...Object.entries(c.fixtureSponsors),
27
+ ];
28
+ const undeclared = ['inactive', 'excluded'].filter(kind => !Object.hasOwn(c.fixtureSponsors, kind));
29
+ if (undeclared.length) console.error(`Agent sponsor probes: undeclared=${undeclared.join(',')}; no points run for these states.`);
30
+ for (const [kind, sponsor] of sponsorProbes) {
31
+ // Give each probe an unused agent, so a prior agent/sponsor binding cannot
32
+ // mask missing sponsor admission. Only sponsor claims override its valid
33
+ // token. Signing authority stays in the verifier.
34
+ let ok = false, status;
35
+ try {
36
+ const native = await c.witness();
37
+ const token = await accessToken({ ...c, agentId: `rer-sponsor-probe-${crypto.randomUUID()}` }, sponsor);
38
+ const answer = await c.mcp('tools/list', {}, { token });
39
+ const after = await c.witness(), code = errorCode(answer);
40
+ status = answer.status;
41
+ ok = [401, 403].includes(status)
42
+ && (answer.message?.error?.code === -32001 || typeof code === 'string' && code.length > 0)
43
+ && answer.result === undefined && isDeepStrictEqual(native, after);
44
+ } catch { /* Native and fixture diagnostics may contain private identities. */ }
45
+ c.add(`BASE-AGENT-004.sponsor.${kind}`, ok,
46
+ `Sponsor ${kind} must return HTTP 401 or 403 with a typed error and leave native state unchanged${status === undefined ? '' : ` (HTTP ${status})`}.`);
47
+ }
23
48
  const write = c.surface.journey.find(step => !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly);
24
49
  if (write) {
25
50
  const answer = await c.tool(write.tool, c.args(write, new Map(), { unresolved: true }), { token: await accessToken(c, { scope: 'events:read' }) });
@@ -81,8 +81,9 @@ export function createProtocol(context) {
81
81
  if (!valid) throw new Error('Cannot decide an approval without its exact summary evidence');
82
82
  const response = await context.personRequest(`${path}/${action}`, { method: 'POST', body: JSON.stringify({ revision: approval.revision, summary_sha256: approval.summary_sha256 }) });
83
83
  const body = await responseBody(response);
84
- if (response.ok && action === 'approve' && body.approval?.state === 'executed') context.calls.push({
84
+ if (response.ok && action === 'approve' && approval.state === 'pending' && ['executed', 'refused'].includes(body.approval?.state)) context.calls.push({
85
85
  kind: 'approval/execute', name: approval.tool, decision: structuredClone(pending.decision), approvalId: handle.id, principal: pending.principal,
86
+ state: body.approval.state, code: body.approval.code ?? null,
86
87
  });
87
88
  return { ok: response.ok, status: response.status, body };
88
89
  };
@@ -6,12 +6,19 @@ import { createProtocol, errorCode, APPROVAL } from './protocol.mjs';
6
6
 
7
7
  /** Additional principals use real native sessions and signed credentials. All
8
8
  * record and approval probes cross the same public doors as the main journey. */
9
- export async function crossSponsorPhase(c, sponsors) {
9
+ export async function crossSponsorPhase(c, sponsors, initializeAgent) {
10
10
  const declaration = c.surface.verification?.crossSponsor;
11
11
  if (!declaration || !Array.isArray(declaration.prepare) || !declaration.prepare.length || !declaration.read || !declaration.change) throw new Error('Multiple sponsors require verification.crossSponsor {prepare,read,change} fixtures.');
12
12
  for (const person of sponsors.slice(1)) {
13
13
  const b = createProtocol({ fetch: c.fetch, origin: c.origin, surface: c.surface, signer: c.signer, person,
14
14
  business: c.business, consent: randomUUID(), now: c.now, points: c.points, agentId: `rer-conformance-${randomUUID()}`, seq: c.seq, revision: c.revision, listed: c.listed });
15
+ if (initializeAgent) {
16
+ try { await initializeAgent({ agentId: b.agentId, person }); }
17
+ catch {
18
+ c.add('BASE-AGENT-001.agent-initializer', false, 'Native agent initialization failed; no captured mail, credentials or fixture values are logged.');
19
+ return;
20
+ }
21
+ }
15
22
  const prefix = `BASE-AGENT-004.cross-sponsor.${person.label}`;
16
23
  await c.adopt(autonomousPolicy());
17
24
  b.revision = c.revision;
@@ -1,4 +1,6 @@
1
+ import { seconds } from './crypto.mjs';
2
+
1
3
  export async function nativeStepHook(c, stage, phase, step, args, outputs, result) {
2
4
  if (!c.nativeStep) return;
3
- await c.nativeStep({ stage, phase, step: structuredClone(step), args: structuredClone(args), outputs: structuredClone(Object.fromEntries(outputs)), ...(result === undefined ? {} : { result: structuredClone(result) }), tool: c.tool });
5
+ await c.nativeStep({ stage, phase, now: seconds(c.now) * 1000, step: structuredClone(step), args: structuredClone(args), outputs: structuredClone(Object.fromEntries(outputs)), ...(result === undefined ? {} : { result: structuredClone(result) }), tool: c.tool });
4
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.90",
3
+ "version": "0.2.91",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",