@event4u/agent-config 14.8.0 → 14.9.0

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 (136) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +165 -237
  3. package/README.md +1 -1
  4. package/agents/templates/.ai-council.yml.example +34 -4
  5. package/dist/agent-src/commands/pr/merge.md +9 -5
  6. package/dist/agent-src/commands/review/changes.md +95 -14
  7. package/dist/agent-src/commands/roadmap/process-full.md +2 -2
  8. package/dist/agent-src/contexts/execution/host-capability-manifest.md +77 -0
  9. package/dist/agent-src/contexts/execution/roadmap-execution-contract.md +36 -0
  10. package/dist/agent-src/contexts/execution/subagent-response-contract.md +80 -0
  11. package/dist/agent-src/rules/untrusted-input-defense.md +9 -3
  12. package/dist/agent-src/skills/code-review/evals/evals.json +87 -46
  13. package/dist/agent-src/skills/humanizer/SKILL.md +39 -0
  14. package/dist/agent-src/skills/humanizer/evals/strip_fixtures.json +57 -0
  15. package/dist/agent-src/skills/humanizer/references/fixtures.md +54 -0
  16. package/dist/agent-src/skills/judge-spec-compliance/SKILL.md +154 -0
  17. package/dist/agent-src/skills/judge-synthesis/SKILL.md +45 -0
  18. package/dist/agent-src/skills/roadmap-writing/SKILL.md +18 -18
  19. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  20. package/dist/agent-src/templates/roadmaps.md +8 -0
  21. package/dist/cli/registry.js +2 -0
  22. package/dist/cli/registry.js.map +1 -1
  23. package/dist/cli-delegate/{chunk-MMSGVZKV.js → chunk-77GR3VD4.js} +65 -40
  24. package/dist/cli-delegate/{chunk-Q26HT4QT.js → chunk-E46KPN6K.js} +251 -150
  25. package/dist/cli-delegate/{chunk-EEJUMCDZ.js → chunk-PLSG6UL5.js} +1 -1
  26. package/dist/cli-delegate/cmd_conformance.js +89 -13
  27. package/dist/cli-delegate/cmd_doctor.js +3 -3
  28. package/dist/cli-delegate/cmd_handoff.js +2 -2
  29. package/dist/cli-delegate/cmd_memory_get.js +1 -1
  30. package/dist/cli-delegate/cmd_route_audit.js +1 -1
  31. package/dist/cli-delegate/cmd_settings_get.js +1 -1
  32. package/dist/cli-delegate/cmd_settings_set.js +1 -1
  33. package/dist/discovery/deprecation-report.md +1 -1
  34. package/dist/discovery/discovery-manifest.json +37 -15
  35. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  36. package/dist/discovery/discovery-manifest.summary.md +3 -3
  37. package/dist/discovery/dormancy-report.md +1 -1
  38. package/dist/discovery/orphan-report.md +1 -1
  39. package/dist/discovery/packs.json +6 -5
  40. package/dist/discovery/trust-report.md +2 -2
  41. package/dist/discovery/workspaces.json +5 -4
  42. package/dist/hooks/dispatch.js +562 -204
  43. package/dist/mcp/registry-manifest.json +3 -3
  44. package/dist/mcp/server.json +2 -2
  45. package/dist/mcp/server.mjs +808 -331
  46. package/dist/scripts/_lib/claude_plugin.js +162 -0
  47. package/dist/scripts/_lib/claude_plugin.js.map +1 -0
  48. package/dist/scripts/_lib/environment_detector.js +397 -0
  49. package/dist/scripts/_lib/environment_detector.js.map +1 -0
  50. package/dist/scripts/_lib/spawn_env.js +129 -0
  51. package/dist/scripts/_lib/spawn_env.js.map +1 -0
  52. package/dist/scripts/ai_council/modes.js +199 -0
  53. package/dist/scripts/ai_council/modes.js.map +1 -0
  54. package/dist/scripts/ai_council/transport_resolver.js +418 -0
  55. package/dist/scripts/ai_council/transport_resolver.js.map +1 -0
  56. package/dist/server/routes/wizard.js +3 -2
  57. package/dist/server/routes/wizard.js.map +1 -1
  58. package/dist/ui/assets/index-Cxgy63kz.js +26 -0
  59. package/dist/ui/assets/index-Cxgy63kz.js.map +1 -0
  60. package/dist/ui/index.html +1 -1
  61. package/docs/guidelines/agent-infra/traceability-field-mechanics.md +50 -0
  62. package/docs/guidelines/agent-infra/untrusted-input-spotlighting.md +17 -0
  63. package/package.json +7 -3
  64. package/src/config/estate-count-budget.json +13 -744
  65. package/src/config/evaluator-budgets.json +4 -4
  66. package/src/config/gate-coverage.yml +247 -9
  67. package/src/config/gate-violation-baselines.json +72 -72
  68. package/src/config/publish-surface.json +60 -0
  69. package/src/config/requirements-trace-budget.json +32 -0
  70. package/src/config/rule-stub-ceilings.json +8 -1
  71. package/src/scripts/_dispatch.bash +7 -0
  72. package/src/scripts/_lib/base_tree.ts +175 -0
  73. package/src/scripts/_lib/billing_grant.ts +165 -0
  74. package/src/scripts/_lib/billing_grant_cli.ts +123 -0
  75. package/src/scripts/_lib/council_fallback_posture.ts +53 -6
  76. package/src/scripts/_lib/council_fallback_wiring.ts +61 -1
  77. package/src/scripts/_lib/host_capability.ts +59 -5
  78. package/src/scripts/_lib/quota_parked.ts +133 -0
  79. package/src/scripts/_lib/retrieval_sanitize.ts +62 -0
  80. package/src/scripts/_lib/review_telemetry.ts +196 -0
  81. package/src/scripts/_lib/subagent_response.ts +92 -0
  82. package/src/scripts/adr/regenerate_index.ts +14 -7
  83. package/src/scripts/ai_council/clients.ts +12 -1
  84. package/src/scripts/ai_council/config.ts +72 -115
  85. package/src/scripts/ai_council/fallback_config.ts +19 -7
  86. package/src/scripts/ai_council/mid_flight_fallback.ts +88 -7
  87. package/src/scripts/ai_council/orchestrator.ts +2 -2
  88. package/src/scripts/ai_council/py_format.ts +124 -0
  89. package/src/scripts/ai_council/transport_resolver.ts +65 -2
  90. package/src/scripts/audit_adr_coverage.ts +33 -6
  91. package/src/scripts/check_council_pin_staleness.ts +300 -0
  92. package/src/scripts/check_estate_count.ts +420 -293
  93. package/src/scripts/check_gate_coverage.ts +91 -0
  94. package/src/scripts/check_no_stub_inventory_table.ts +292 -0
  95. package/src/scripts/check_pack_size.ts +234 -1
  96. package/src/scripts/check_publish_surface.ts +297 -0
  97. package/src/scripts/check_requirements_trace.ts +378 -0
  98. package/src/scripts/check_secret_leak.ts +166 -12
  99. package/src/scripts/code_graph/cli.ts +44 -5
  100. package/src/scripts/code_graph/extract.ts +87 -0
  101. package/src/scripts/council_cli.ts +12 -16
  102. package/src/scripts/detect_ai_tells.ts +87 -0
  103. package/src/scripts/dispatch_r2_reviewer.ts +42 -0
  104. package/src/scripts/generate_capabilities_index.ts +41 -0
  105. package/src/scripts/git_authorization_hook.ts +54 -4
  106. package/src/scripts/hooks/block_unauthorized_git.ts +19 -1
  107. package/src/scripts/hooks/run_continuation_hook.ts +3 -1
  108. package/src/scripts/hooks/subagent_ledger_hook.ts +76 -11
  109. package/src/scripts/injection_scan_hook.ts +120 -10
  110. package/src/scripts/lint_adr_sweep_routing.ts +365 -0
  111. package/src/scripts/lint_workflow_security.ts +53 -10
  112. package/src/scripts/lint_workflow_security_allowlist.json +2 -18
  113. package/src/scripts/report_envelope_rate.ts +166 -0
  114. package/src/scripts/review_axis_report.ts +218 -0
  115. package/src/scripts/run_supervise.ts +46 -1
  116. package/src/scripts/schemas/evals.schema.json +5 -0
  117. package/src/scripts/sync_pr_branch.ts +14 -7
  118. package/dist/cli/commands/commands.candidates.test.js +0 -257
  119. package/dist/cli/commands/commands.candidates.test.js.map +0 -1
  120. package/dist/cli/commands/profiles.test.js +0 -88
  121. package/dist/cli/commands/profiles.test.js.map +0 -1
  122. package/dist/cli/commands/recordTriggerEval.test.js +0 -113
  123. package/dist/cli/commands/recordTriggerEval.test.js.map +0 -1
  124. package/dist/cli/configRoot.test.js +0 -97
  125. package/dist/cli/configRoot.test.js.map +0 -1
  126. package/dist/cli/mcp/content.test.js +0 -54
  127. package/dist/cli/mcp/content.test.js.map +0 -1
  128. package/dist/cli/mcp/dispatch.test.js +0 -108
  129. package/dist/cli/mcp/dispatch.test.js.map +0 -1
  130. package/dist/server/writeRoot.test.js +0 -91
  131. package/dist/server/writeRoot.test.js.map +0 -1
  132. package/dist/shared/capabilities.test.js +0 -39
  133. package/dist/shared/capabilities.test.js.map +0 -1
  134. package/dist/ui/assets/index-C1pBRm1f.js +0 -26
  135. package/dist/ui/assets/index-C1pBRm1f.js.map +0 -1
  136. /package/dist/cli-delegate/{chunk-N7CDDGI3.js → chunk-CYH5SP6M.js} +0 -0
@@ -0,0 +1,165 @@
1
+ /**
2
+ * billing_grant — the run-scoped answer to "plan quota is gone, may I spend?".
3
+ *
4
+ * The problem this closes is a billing-class switch nobody chose at the moment
5
+ * it happened. A council seat on a vendor CLI under a subscription login is
6
+ * unmetered; its api twin is metered USD. Until `api_on_quota: 'ask'` existed
7
+ * that switch was decided once, at configuration time, and then applied
8
+ * silently mid-round — see `transport_resolver.ts` § `FallbackPolicy`.
9
+ *
10
+ * A grant is the human's yes, and it is scoped to ONE run for two reasons.
11
+ *
12
+ * The first is that a run is the unit the question is answerable in. "May I
13
+ * spend money finishing this?" needs the remaining scope in view; a standing
14
+ * setting has no scope to show. The second is the failure a wall-clock TTL
15
+ * produces: the git-guard grant expired after 30 minutes, so a drain outliving
16
+ * its own grant re-asked mid-run — which is the interruption this whole
17
+ * mechanism exists to remove. So the TTL here is the RUN, and `revoke` is
18
+ * called from the path that already clears run-continuation state. A wall
19
+ * clock appears only as a backstop for a run that died without cleaning up.
20
+ *
21
+ * Transport is an env var (`AC_BILLING_GRANT`) plus a file under
22
+ * `agents/runtime/`. Both are needed and neither is redundant: the env var is
23
+ * what a spawned subagent can read without knowing the repo root, and the file
24
+ * is what makes the grant survive a subprocess boundary in the other
25
+ * direction and gives `revoke` something to delete. `hardenedSpawnEnv()`
26
+ * passes the `AC_` family through — verified, and pinned by a test in
27
+ * `tests/scripts/_lib/spawn_env.test.ts`, because a future deny-family entry
28
+ * would otherwise break the chain silently.
29
+ *
30
+ * PII-exclusion-by-construction: a grant record holds a run id, an ISO
31
+ * timestamp, and nothing else. There is no field capable of carrying a prompt,
32
+ * a path, or a credential, so there is no scrubbing pass here that could fail.
33
+ */
34
+
35
+ import * as fs from 'node:fs';
36
+ import * as path from 'node:path';
37
+
38
+ /** Env var the main session sets and every spawned worker reads. */
39
+ export const BILLING_GRANT_ENV = 'AC_BILLING_GRANT';
40
+
41
+ /** Directory, relative to the repo root, holding one file per live grant. */
42
+ export const BILLING_GRANT_DIR_REL = path.join('agents', 'runtime', 'billing-grants');
43
+
44
+ /**
45
+ * Backstop only. A run that exits through its normal path calls `revoke`; this
46
+ * bounds the damage of one that does not, and is deliberately far longer than
47
+ * any run so it can never be the thing that ends a live grant.
48
+ */
49
+ export const BILLING_GRANT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
50
+
51
+ export interface BillingGrant {
52
+ readonly run_id: string;
53
+ readonly issued_at: string;
54
+ }
55
+
56
+ /** Filesystem-safe filename for a run id. Mirrors `run_checkpoint.checkpointFile`. */
57
+ export function grantFile(repoRoot: string, runId: string): string {
58
+ return path.join(
59
+ repoRoot,
60
+ BILLING_GRANT_DIR_REL,
61
+ `${runId.replace(/[^A-Za-z0-9_-]/g, '_')}.json`,
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Record the human's yes for `runId` and return the env pair to hand to
67
+ * subagents. Idempotent: re-issuing keeps the original `issued_at`, so a
68
+ * second yes inside one run cannot extend the backstop window.
69
+ */
70
+ export function issueBillingGrant(
71
+ repoRoot: string,
72
+ runId: string,
73
+ now: () => Date = () => new Date(),
74
+ ): BillingGrant {
75
+ const file = grantFile(repoRoot, runId);
76
+ const existing = _read(file);
77
+ if (existing !== null && existing.run_id === runId) return existing;
78
+ const grant: BillingGrant = { run_id: runId, issued_at: now().toISOString() };
79
+ fs.mkdirSync(path.dirname(file), { recursive: true });
80
+ fs.writeFileSync(file, `${JSON.stringify(grant, null, 2)}\n`, 'utf8');
81
+ return grant;
82
+ }
83
+
84
+ /**
85
+ * Is a grant in force for `runId`?
86
+ *
87
+ * Both halves must agree, and the AND is the security property rather than
88
+ * belt-and-braces: an env var alone is settable by anything in the process
89
+ * tree, and a file alone would let a grant from a previous run authorise this
90
+ * one. Requiring the env var to NAME the run whose file exists is what makes
91
+ * a different run's grant unusable.
92
+ */
93
+ export function isBillingGrantActive(
94
+ repoRoot: string,
95
+ runId: string,
96
+ env: NodeJS.ProcessEnv = process.env,
97
+ now: () => Date = () => new Date(),
98
+ ): boolean {
99
+ if ((env[BILLING_GRANT_ENV] ?? '').trim() !== runId) return false;
100
+ const grant = _read(grantFile(repoRoot, runId));
101
+ if (grant === null || grant.run_id !== runId) return false;
102
+ const age = now().getTime() - Date.parse(grant.issued_at);
103
+ return Number.isFinite(age) && age >= 0 && age <= BILLING_GRANT_MAX_AGE_MS;
104
+ }
105
+
106
+ /**
107
+ * Ambient check for a caller that does not carry a run id — the council CLI
108
+ * reading config, for instance. The env var names the run, so the file it
109
+ * names is the one that must exist; there is no "any grant will do" branch.
110
+ */
111
+ export function hasBillingGrant(
112
+ repoRoot: string,
113
+ env: NodeJS.ProcessEnv = process.env,
114
+ now: () => Date = () => new Date(),
115
+ ): boolean {
116
+ const runId = (env[BILLING_GRANT_ENV] ?? '').trim();
117
+ if (runId === '') return false;
118
+ return isBillingGrantActive(repoRoot, runId, env, now);
119
+ }
120
+
121
+ /**
122
+ * Remove the grant for `runId`. Safe to call when none exists.
123
+ *
124
+ * Called from `run_continuation_hook.clearRunState` — the one place a run is
125
+ * declared over, and therefore the grant's real TTL. `clearRunState` is
126
+ * exported for that reason: reaching it through the concern chain would mean
127
+ * standing up the whole dispatch harness to assert one unlink.
128
+ */
129
+ export function revokeBillingGrant(repoRoot: string, runId: string): void {
130
+ try {
131
+ fs.unlinkSync(grantFile(repoRoot, runId));
132
+ } catch {
133
+ // Already gone is the success case, not an error worth surfacing.
134
+ }
135
+ }
136
+
137
+ function _read(file: string): BillingGrant | null {
138
+ try {
139
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
140
+ if (raw === null || typeof raw !== 'object') return null;
141
+ const o = raw as Record<string, unknown>;
142
+ if (typeof o.run_id !== 'string' || typeof o.issued_at !== 'string') return null;
143
+ return { run_id: o.run_id, issued_at: o.issued_at };
144
+ } catch {
145
+ return null;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * The id of the run a grant would be scoped to.
151
+ *
152
+ * Resolution order, first non-empty wins: `AC_BILLING_GRANT` (a grant already
153
+ * in force names its own run), then `AC_RUN_ID` (what an orchestrating session
154
+ * sets), then the host's session id. Returns `null` when none resolves — and
155
+ * `null` is rendered as a literal placeholder rather than a fabricated id,
156
+ * because a grant command carrying an invented run id would be a command that
157
+ * silently authorises nothing.
158
+ */
159
+ export function currentRunId(env: NodeJS.ProcessEnv = process.env): string | null {
160
+ for (const key of [BILLING_GRANT_ENV, 'AC_RUN_ID', 'CLAUDE_CODE_SESSION_ID']) {
161
+ const v = (env[key] ?? '').trim();
162
+ if (v !== '') return v;
163
+ }
164
+ return null;
165
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The `council:{grant-billing,revoke-billing}` verbs, and the round's closing
3
+ * Human Gate line.
4
+ *
5
+ * Lives here rather than in `council_cli.ts` for the reason that file's other
6
+ * extractions give: it is ~2,500 lines over the source ceiling and the
7
+ * documented remedy is extraction, not a raised baseline
8
+ * (`gate-violation-baselines.json` § check_source_size_budget).
9
+ *
10
+ * IO is injected rather than imported so this module stays testable without a
11
+ * process: `council_cli.ts` owns the repo root and the stdout/stderr pair.
12
+ */
13
+
14
+ import {
15
+ BILLING_GRANT_ENV,
16
+ currentRunId,
17
+ hasBillingGrant,
18
+ issueBillingGrant,
19
+ revokeBillingGrant,
20
+ } from './billing_grant.js';
21
+ import { renderBillingGateLines } from './council_fallback_posture.js';
22
+ import { writeQuotaParked } from './quota_parked.js';
23
+
24
+ export interface BillingCliDeps {
25
+ readonly repoRoot: string;
26
+ readonly stdout: (s: string) => void;
27
+ readonly stderr: (s: string) => void;
28
+ }
29
+
30
+ /** The verbs this module owns, spread into `council_cli`'s subcommand list. */
31
+ export const BILLING_SUBCOMMANDS = ['grant-billing', 'revoke-billing'] as const;
32
+
33
+ /**
34
+ * The arg spec for a billing verb, or `null` when `cmd` is not one.
35
+ *
36
+ * Consulted from `council_cli`'s `default:` arm rather than added as two more
37
+ * `case` labels there: the verb list already lives in this module, and a
38
+ * second copy of it in a switch is a copy that can drift.
39
+ */
40
+ export function billingArgSpec(
41
+ cmd: string,
42
+ ): { positionals: string[]; opts: never[]; requiredOpts: never[] } | null {
43
+ return (BILLING_SUBCOMMANDS as readonly string[]).includes(cmd)
44
+ ? { positionals: ['run_id'], opts: [], requiredOpts: [] }
45
+ : null;
46
+ }
47
+
48
+ /**
49
+ * Dispatch a billing verb, or return `null` when `cmd` is not one.
50
+ *
51
+ * A `null` return rather than a thrown or a boolean out-param: the caller's
52
+ * dispatch chain is a run of `if (cmd === x) return f()`, and this has to slot
53
+ * into it as two lines without teaching the caller which verbs exist.
54
+ */
55
+ export function handleBillingCommand(
56
+ cmd: string,
57
+ runId: unknown,
58
+ d: BillingCliDeps,
59
+ ): number | null {
60
+ if (cmd === 'grant-billing') return grantBilling(String(runId ?? ''), d);
61
+ if (cmd === 'revoke-billing') return revokeBilling(String(runId ?? ''), d);
62
+ return null;
63
+ }
64
+
65
+ /**
66
+ * Record the human's yes for one run.
67
+ *
68
+ * Writes the grant file and then prints the export line, because the file
69
+ * alone is not the grant: a grant is in force only when `AC_BILLING_GRANT`
70
+ * NAMES the run whose file exists (see `isBillingGrantActive`), and that AND
71
+ * is what stops a previous run's grant from authorising this one. Printing the
72
+ * export rather than setting it is not a limitation being apologised for — a
73
+ * process cannot set its parent's environment, and a command claiming to would
74
+ * be lying.
75
+ */
76
+ export function grantBilling(runId: string, d: BillingCliDeps): number {
77
+ if (runId.trim() === '') {
78
+ d.stderr('❌ council:grant-billing: a run id is required.\n');
79
+ return 2;
80
+ }
81
+ const g = issueBillingGrant(d.repoRoot, runId.trim());
82
+ d.stdout(`✅ billing grant recorded for run ${g.run_id} (issued ${g.issued_at})\n`);
83
+ d.stdout(` export ${BILLING_GRANT_ENV}=${g.run_id}\n`);
84
+ const live = hasBillingGrant(d.repoRoot) ? 'yes' : 'not until the export above is set';
85
+ d.stdout(` in force: ${live}\n`);
86
+ return 0;
87
+ }
88
+
89
+ /**
90
+ * End the grant. Exit 0 on an absent one: "there is no grant for this run" is
91
+ * the state the caller asked for, and failing on it would make the run-end
92
+ * cleanup path noisy on exactly the runs that never needed a grant.
93
+ */
94
+ export function revokeBilling(runId: string, d: BillingCliDeps): number {
95
+ if (runId.trim() === '') {
96
+ d.stderr('❌ council:revoke-billing: a run id is required.\n');
97
+ return 2;
98
+ }
99
+ revokeBillingGrant(d.repoRoot, runId.trim());
100
+ d.stdout(`✅ billing grant revoked for run ${runId.trim()}\n`);
101
+ return 0;
102
+ }
103
+
104
+ /**
105
+ * Print the round's closing question when `api_on_quota: 'ask'` parked seats.
106
+ * Silent when nothing parked, so the caller needs no branch.
107
+ */
108
+ export function printBillingGate(parked: readonly string[], d: BillingCliDeps): void {
109
+ const runId = currentRunId();
110
+ // Record before rendering. A parked round is the one moment this repository
111
+ // KNOWS plan quota is exhausted without needing a host signal, and the
112
+ // printed line reaches whoever is watching the terminal — which for an
113
+ // autonomous drain is nobody. The marker is what survives to the next
114
+ // `run:supervise` report. Skipped when no run id resolves: a marker with a
115
+ // fabricated key is worse than none, because nothing would ever match it.
116
+ if (parked.length > 0 && runId !== null) writeQuotaParked(d.repoRoot, runId, parked);
117
+ for (const line of renderBillingGateLines(parked, {
118
+ runId: runId ?? '<run-id>',
119
+ estimatedUsd: null,
120
+ })) {
121
+ d.stdout(`${line}\n`);
122
+ }
123
+ }
@@ -13,6 +13,8 @@
13
13
  * `council:status` is the one command that must stay free of side effects.
14
14
  */
15
15
 
16
+ import type { ApiOnQuota } from '../ai_council/transport_resolver.js';
17
+
16
18
  export type FallbackPosture = 'api' | 'none' | 'n/a';
17
19
 
18
20
  export interface PostureInput {
@@ -59,7 +61,7 @@ export function fallbackPostureFor(input: PostureInput): FallbackPosture {
59
61
  */
60
62
  export function renderPostureLines(
61
63
  postures: ReadonlyArray<readonly [string, FallbackPosture]>,
62
- apiOnQuota: boolean,
64
+ apiOnQuota: ApiOnQuota,
63
65
  ): string[] {
64
66
  const live = postures.filter(([, p]) => p !== 'n/a');
65
67
  if (live.length === 0) return [];
@@ -72,10 +74,55 @@ export function renderPostureLines(
72
74
  );
73
75
  // Separate from the per-seat lines: not a per-seat property but the one
74
76
  // billing-class decision, governing every seat at once.
75
- lines.push(
76
- ` fallback quota api_on_quota: ${apiOnQuota ? 'on' : 'off'}` +
77
- ` — an exhausted cli quota ${apiOnQuota ? 'MAY' : 'may not'}` +
78
- ' retry on the metered rung',
79
- );
77
+ // Three postures, rendered by name rather than by truthiness. `'ask'` is
78
+ // truthy, so an `apiOnQuota ? 'on' : 'off'` reading would print `on` for
79
+ // it — telling the operator that quota fall-through happens silently when
80
+ // the whole point of the value is that it does not.
81
+ const word = apiOnQuota === 'ask' ? 'ask' : apiOnQuota ? 'on' : 'off';
82
+ const consequence =
83
+ apiOnQuota === 'ask'
84
+ ? ' — an exhausted cli quota PARKS the seat and the round closes with a question,' +
85
+ ' unless a run-scoped billing grant is already in force'
86
+ : apiOnQuota
87
+ ? ' — an exhausted cli quota MAY retry on the metered rung'
88
+ : ' — an exhausted cli quota may not retry on the metered rung';
89
+ lines.push(` fallback quota api_on_quota: ${word}${consequence}`);
80
90
  return lines;
81
91
  }
92
+
93
+ /**
94
+ * The Human Gate a round closes with when `api_on_quota: 'ask'` parked seats.
95
+ *
96
+ * A correction to this roadmap step, recorded rather than quietly absorbed:
97
+ * the step said to render this "through the existing `renderPostureLines`
98
+ * path". That path is `council:status`, which runs before any round and can
99
+ * therefore never know which seats a round parked. So this is a sibling in the
100
+ * same module rather than a branch inside that function — same place, same
101
+ * vocabulary, different moment.
102
+ *
103
+ * Returns `[]` when nothing parked, so a caller may render unconditionally
104
+ * without a heading over an empty list.
105
+ */
106
+ export function renderBillingGateLines(
107
+ parked: readonly string[],
108
+ opts: { readonly runId: string; readonly estimatedUsd: number | null },
109
+ ): string[] {
110
+ if (parked.length === 0) return [];
111
+ const seats = [...new Set(parked)].sort();
112
+ const cost =
113
+ opts.estimatedUsd === null
114
+ ? 'unknown — no priced estimate for the retry'
115
+ : `~$${opts.estimatedUsd.toFixed(2)}`;
116
+ return [
117
+ '',
118
+ 'HUMAN GATE — plan quota exhausted, metered spend not authorised',
119
+ ` parked seats ${seats.join(', ')}`,
120
+ ` retry cost ${cost}`,
121
+ // The command is printed rather than described because the whole
122
+ // mechanism fails if answering it takes a lookup: an operator who has
123
+ // to go find the syntax is an operator who says yes tomorrow, on a run
124
+ // that has already ended.
125
+ ` to authorise agent-config council:grant-billing ${opts.runId}`,
126
+ ' to decline do nothing — the grant is never implied by silence',
127
+ ];
128
+ }
@@ -13,13 +13,18 @@
13
13
  */
14
14
 
15
15
  import type { CliFallbackOptions, FallbackEvent } from '../ai_council/mid_flight_fallback.js';
16
+ import type { ApiOnQuota } from '../ai_council/transport_resolver.js';
17
+ import { parseApiOnQuota } from '../ai_council/transport_resolver.js';
18
+ import { hasBillingGrant } from './billing_grant.js';
16
19
  import { CouncilConfigError } from '../ai_council/config.js';
17
20
 
18
21
  type Dict = Record<string, unknown>;
19
22
 
20
23
  /** Anything the twin factory needs that `council_cli.ts` owns. */
21
24
  export interface FallbackWiringDeps {
22
- readonly apiOnQuota: boolean;
25
+ readonly apiOnQuota: ApiOnQuota;
26
+ /** Run-scoped billing grant in force. Read only under `'ask'`. */
27
+ readonly billingGrant?: boolean;
23
28
  /** Does this provider have an api constructor at all? */
24
29
  readonly hasApiRung: (provider: string) => boolean;
25
30
  /** This provider's `members.<name>` block, or `{}`. */
@@ -38,6 +43,7 @@ export interface FallbackWiringDeps {
38
43
  ) => unknown;
39
44
  /** The events-log appender. */
40
45
  readonly emit: (record: Dict) => unknown;
46
+
41
47
  }
42
48
 
43
49
  /**
@@ -77,8 +83,15 @@ function isRefusal(exc: unknown): boolean {
77
83
  }
78
84
 
79
85
  export function buildFallbackOptions(deps: FallbackWiringDeps): CliFallbackOptions {
86
+ // Owned here, not passed in. `establishTwin` emits `awaiting_grant` and
87
+ // this is the nearest thing to it that outlives one call, so a caller
88
+ // wanting the closing question reads `options.parked` instead of
89
+ // threading a collector through the factory.
90
+ const parked: string[] = [];
80
91
  return {
81
92
  api_on_quota: deps.apiOnQuota,
93
+ billing_grant: deps.billingGrant === true,
94
+ parked,
82
95
  // The orchestrator is a pure library and holds no sink; this is it.
83
96
  // One line per establishing escalation, so attendance analysis can
84
97
  // tell a seat SAVED by the fallback from one that was natively api.
@@ -93,6 +106,7 @@ export function buildFallbackOptions(deps: FallbackWiringDeps): CliFallbackOptio
93
106
  // during a fallback kills the whole round, and the mechanism whose
94
107
  // entire purpose is to SAVE a seat becomes the thing that loses
95
108
  // every seat. Losing the log line is the strictly smaller failure.
109
+ if (e.outcome === 'awaiting_grant') parked.push(e.provider);
96
110
  try {
97
111
  deps.emit({
98
112
  action: 'transport_fallback',
@@ -124,3 +138,49 @@ export function buildFallbackOptions(deps: FallbackWiringDeps): CliFallbackOptio
124
138
  },
125
139
  };
126
140
  }
141
+
142
+ /** Everything `wireCouncilFallback` needs that `council_cli.ts` owns. */
143
+ export interface CallSiteDeps {
144
+ readonly repoRoot: string;
145
+ readonly isDict: (v: unknown) => v is Dict;
146
+ readonly membersCfg: Dict;
147
+ readonly overrides: Dict;
148
+ readonly hasApiRung: (provider: string) => boolean;
149
+ readonly constructApi: FallbackWiringDeps['constructApi'];
150
+ readonly emit: (record: Dict) => unknown;
151
+ }
152
+
153
+ /**
154
+ * Build the fallback factory from the raw `ai_council` block and hand it back
155
+ * through the out-param `build_members` threads.
156
+ *
157
+ * Extracted from `council_cli.ts` when the billing-grant read joined the two
158
+ * config reads already here: that file is ~2,500 lines over the source ceiling
159
+ * and the documented remedy is extraction rather than a raised baseline
160
+ * (`gate-violation-baselines.json` § check_source_size_budget). Keeping the
161
+ * derivation next to the factory it feeds is the better shape anyway — the
162
+ * caller had to know that an absent `fallback` block means `false` and that
163
+ * the grant is read per-run, neither of which is the caller's business.
164
+ */
165
+ export function wireCouncilFallback(
166
+ out: { options: CliFallbackOptions | null } | null,
167
+ ai: Dict,
168
+ d: CallSiteDeps,
169
+ ): void {
170
+ // The null check lives here, not at the call site: `fallback_out` is an
171
+ // optional out-param and "the caller passed no ref" is this function's
172
+ // business, not a branch every caller has to remember.
173
+ if (out === null) return;
174
+ // Absent/malformed block means `false`, never a throw. Why quota
175
+ // fall-through is opt-in: `FallbackPolicy.apiOnQuota`.
176
+ const cfg = d.isDict(ai['fallback']) ? ai['fallback'] : {};
177
+ out.options = buildFallbackOptions({
178
+ apiOnQuota: parseApiOnQuota(cfg['api_on_quota']),
179
+ billingGrant: hasBillingGrant(d.repoRoot),
180
+ hasApiRung: d.hasApiRung,
181
+ memberConfig: (p) => ((d.membersCfg[p] as Dict) || {}) as Dict,
182
+ modelOverride: (p) => (d.overrides[p] as string | undefined) ?? null,
183
+ constructApi: d.constructApi,
184
+ emit: d.emit,
185
+ });
186
+ }
@@ -120,11 +120,65 @@ export function normalizeHostManifest(input: unknown): HostCapabilityManifest {
120
120
  * host identity a hook/dispatch envelope carries).
121
121
  *
122
122
  * Each row is partial: an omitted field stays at the `SAFE_DEFAULT` `false`
123
- * when the row is applied. Claude Code is the one host this roadmap's
124
- * transcript evidence measured spawning and running subagents concurrently
125
- * (`Agent` tool dispatch, parallel tool-use blocks); polling and a separate
126
- * quota pool were never observed, so they stay `false` — add a field only
127
- * once it is itself observed, never by inference.
123
+ * when the row is applied — and an ABSENT field is the record for "never
124
+ * looked", which is a different state from a field written as `false`
125
+ * deliberately. Add a field only once it is itself observed, never by
126
+ * inference.
127
+ *
128
+ * ## Rows are written under the observation protocol
129
+ *
130
+ * `contexts/execution/host-capability-manifest.md` § Observation protocol states
131
+ * the per-field criterion and the four-part citation (host · host version ·
132
+ * transcript or artefact reference · date). A row without all four is not
133
+ * admissible, and no row may be filled from a host's documentation.
134
+ *
135
+ * ## REACHABILITY, 2026-08-22 — one of eight, and the other seven are recorded
136
+ *
137
+ * `hook_manifest.yaml` declares eight platform keys. Reachable means a real
138
+ * session can be started on the host, not that it is installable in principle.
139
+ *
140
+ * - `claude` — REACHABLE. Row below, re-cited under the protocol.
141
+ * - `augment` — not reachable from this session: a different editor host, no
142
+ * session available to the running agent.
143
+ * - `cowork` — not reachable from this session, same reason.
144
+ * - `cursor` — not reachable from this session, same reason.
145
+ * - `cline` — not reachable from this session, same reason.
146
+ * - `windsurf` — not reachable from this session, same reason.
147
+ * - `gemini` — not reachable from this session, same reason.
148
+ * - `copilot` — not reachable from this session, same reason; additionally
149
+ * `fallback_only` in the manifest.
150
+ *
151
+ * The seven have **no row**, so every field resolves to the safe default and
152
+ * `describeHostCapabilities` reports its source as `default`. That is the
153
+ * "never looked" state, and it is the honest one — a recorded silence rather
154
+ * than a table with gaps that reads as a table of negatives.
155
+ *
156
+ * ## The `claude` row, RE-CITED rather than grandfathered
157
+ *
158
+ * The row predated the protocol. Both its fields are now carried on transcript
159
+ * evidence, so it is brought up to the new shape rather than marked
160
+ * grandfathered — which was the other permitted disposition and would have left
161
+ * it looking like it passed a protocol it never ran.
162
+ *
163
+ * `subagent_spawn: true` — OBSERVED. claude (Claude Code, Opus 5 1M session,
164
+ * 2026-08-22). `agents/runtime/state/subagent-ledger/2026-08.jsonl`: **445**
165
+ * `subagent_start` records, and **420** stops carrying a measured
166
+ * `duration_ms` — i.e. 420 child legs whose start and stop pair, which is the
167
+ * criterion (a measurable child duration, not an inferred one).
168
+ *
169
+ * `parallel_spawn: true` — OBSERVED. Same host, session and artefact.
170
+ * **6,168** of 6,388 stop records carry `concurrent_open >= 2`, with a
171
+ * maximum of **30** concurrently open children. Overlapping intervals at one
172
+ * instant, which is the criterion — not two children in sequence.
173
+ *
174
+ * `status_polling`, `separate_quota_pool`, `worker_respawn` — **absent from the
175
+ * row, and that is deliberate.** The ledger does not instrument any of the
176
+ * three, so this is "never looked", NOT "observed absent". They stay at the
177
+ * safe default and report `default` provenance. Writing any of them as an
178
+ * explicit `false` would claim a measurement nobody took.
179
+ *
180
+ * `agent_teams` — out of scope for a row by construction; see its own field
181
+ * doc comment and the protocol section.
128
182
  */
129
183
  const HOST_CAPABILITY_REGISTRY: Readonly<Record<string, Partial<HostCapabilityManifest>>> = {
130
184
  claude: { subagent_spawn: true, parallel_spawn: true },
@@ -0,0 +1,133 @@
1
+ /**
2
+ * quota_parked — the marker that says a run stopped because plan quota ran out,
3
+ * rather than because it crashed.
4
+ *
5
+ * `run_supervise` can already tell a dead session from a live one, and a
6
+ * finished run from an unfinished one. What it cannot tell is WHY a run
7
+ * stopped, and for one cause that distinction decides the whole response: a run
8
+ * held back by an exhausted plan quota is not broken, it is early. Reported as
9
+ * `relaunchable` with "the session is gone" it reads as a crash, and the one
10
+ * fact an operator needs — that waiting is a strategy here and is not a
11
+ * strategy for a crash — is the fact that gets lost.
12
+ *
13
+ * **The trigger is ours, and that is the point.** Detecting the billing cliff
14
+ * inside Claude Code needs a host signal nobody has shown exists
15
+ * (`agents/roadmaps/later/road-to-billing-cliff-detection.md`). But the council
16
+ * establishes the same fact under its own roof: when `api_on_quota: 'ask'`
17
+ * parks a seat, plan quota for that provider is exhausted, measured by us, with
18
+ * no host surface involved. This marker is written from there.
19
+ *
20
+ * PII-exclusion-by-construction, the same shape as `billing_grant`: a record
21
+ * holds a run id, provider names, and an ISO stamp. There is no field capable
22
+ * of carrying a prompt, a path, or an error body, so there is no scrubbing pass
23
+ * here that could fail.
24
+ *
25
+ * **It records, it does not act.** Nothing here sleeps, probes, or relaunches.
26
+ * Unattended relaunch is a published refusal
27
+ * (road-to-long-horizon-execution 4.0, AI council 2026-08-19) whose reopen
28
+ * condition has since fired — see
29
+ * `agents/evidence/billing-cliff/spawn-reopen-condition.md` — and a fired
30
+ * condition reopens the question in the venue that closed it, never the
31
+ * capability by itself.
32
+ */
33
+
34
+ import * as fs from 'node:fs';
35
+ import * as path from 'node:path';
36
+
37
+ /** Directory, relative to the repo root, holding one marker per parked run. */
38
+ export const QUOTA_PARKED_DIR_REL = path.join('agents', 'runtime', 'state', 'quota-parked');
39
+
40
+ export interface QuotaParkedMarker {
41
+ readonly run_id: string;
42
+ /** Providers whose plan quota was exhausted, sorted and deduplicated. */
43
+ readonly providers: string[];
44
+ readonly parked_at: string;
45
+ }
46
+
47
+ /** Filesystem-safe path for a run's marker. Mirrors `billing_grant.grantFile`. */
48
+ export function markerFile(repoRoot: string, runId: string): string {
49
+ return path.join(
50
+ repoRoot,
51
+ QUOTA_PARKED_DIR_REL,
52
+ `${runId.replace(/[^A-Za-z0-9_-]/g, '_')}.json`,
53
+ );
54
+ }
55
+
56
+ /**
57
+ * Record that `runId` is held back by exhausted plan quota on `providers`.
58
+ *
59
+ * Idempotent on the timestamp: a second park inside one run keeps the original
60
+ * `parked_at` and merges the provider set, so "when did this run first hit the
61
+ * cliff" survives a round that parks twice.
62
+ */
63
+ export function writeQuotaParked(
64
+ repoRoot: string,
65
+ runId: string,
66
+ providers: readonly string[],
67
+ now: () => Date = () => new Date(),
68
+ ): QuotaParkedMarker {
69
+ const file = markerFile(repoRoot, runId);
70
+ const existing = readMarker(file);
71
+ const merged = [...new Set([...(existing?.providers ?? []), ...providers])].sort();
72
+ const marker: QuotaParkedMarker = {
73
+ run_id: runId,
74
+ providers: merged,
75
+ parked_at: existing?.parked_at ?? now().toISOString(),
76
+ };
77
+ fs.mkdirSync(path.dirname(file), { recursive: true });
78
+ fs.writeFileSync(file, `${JSON.stringify(marker, null, 2)}\n`, 'utf8');
79
+ return marker;
80
+ }
81
+
82
+ /** Remove a run's marker. Safe to call when none exists. */
83
+ export function clearQuotaParked(repoRoot: string, runId: string): void {
84
+ try {
85
+ fs.unlinkSync(markerFile(repoRoot, runId));
86
+ } catch {
87
+ // Already gone is the state the caller asked for.
88
+ }
89
+ }
90
+
91
+ /**
92
+ * The marker for a session, or `null`.
93
+ *
94
+ * Looks up by run id first, then scans. The scan is not redundant: the run id
95
+ * the council writes comes from `currentRunId`, whose chain is
96
+ * `AC_BILLING_GRANT` → `AC_RUN_ID` → `CLAUDE_CODE_SESSION_ID`, while the
97
+ * register's `session_id` comes from `AGENT_CONFIG_SESSION_ID` →
98
+ * `CLAUDE_CODE_SESSION_ID`. The two coincide in an ordinary Claude Code session
99
+ * and diverge the moment an orchestrator sets `AC_RUN_ID` — so a direct hit is
100
+ * the common case and the scan is what stops the uncommon one from silently
101
+ * reporting a parked run as a crashed one. The directory holds one small file
102
+ * per parked run, so the scan is cheap by construction.
103
+ */
104
+ export function findQuotaParked(repoRoot: string, sessionId: string): QuotaParkedMarker | null {
105
+ const direct = readMarker(markerFile(repoRoot, sessionId));
106
+ if (direct !== null) return direct;
107
+ let names: string[];
108
+ try {
109
+ names = fs.readdirSync(path.join(repoRoot, QUOTA_PARKED_DIR_REL));
110
+ } catch {
111
+ return null;
112
+ }
113
+ for (const name of names) {
114
+ if (!name.endsWith('.json')) continue;
115
+ const m = readMarker(path.join(repoRoot, QUOTA_PARKED_DIR_REL, name));
116
+ if (m !== null && m.run_id === sessionId) return m;
117
+ }
118
+ return null;
119
+ }
120
+
121
+ function readMarker(file: string): QuotaParkedMarker | null {
122
+ try {
123
+ const raw: unknown = JSON.parse(fs.readFileSync(file, 'utf8'));
124
+ if (raw === null || typeof raw !== 'object') return null;
125
+ const o = raw as Record<string, unknown>;
126
+ if (typeof o['run_id'] !== 'string' || typeof o['parked_at'] !== 'string') return null;
127
+ if (!Array.isArray(o['providers'])) return null;
128
+ const providers = o['providers'].filter((p): p is string => typeof p === 'string');
129
+ return { run_id: o['run_id'], providers, parked_at: o['parked_at'] };
130
+ } catch {
131
+ return null;
132
+ }
133
+ }