@claude-flow/cli 3.25.6 → 3.26.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 (104) hide show
  1. package/.claude/.proven-config-version +1 -0
  2. package/.claude/helpers/.helpers-version +1 -1
  3. package/.claude/helpers/helpers.manifest.json +5 -4
  4. package/.claude/helpers/hook-handler.cjs +129 -0
  5. package/.claude/helpers/statusline.cjs +771 -505
  6. package/.claude/proven-config.json +42 -0
  7. package/catalog-manifest.json +12 -0
  8. package/dist/src/commands/advisor.d.ts +15 -0
  9. package/dist/src/commands/advisor.js +94 -0
  10. package/dist/src/commands/doctor.js +77 -3
  11. package/dist/src/commands/funnel.d.ts +13 -0
  12. package/dist/src/commands/funnel.js +103 -0
  13. package/dist/src/commands/hooks.js +112 -46
  14. package/dist/src/commands/index.js +10 -0
  15. package/dist/src/commands/init.js +44 -0
  16. package/dist/src/commands/proxy.d.ts +21 -0
  17. package/dist/src/commands/proxy.js +310 -0
  18. package/dist/src/commands/security.js +29 -0
  19. package/dist/src/commands/settings.d.ts +19 -0
  20. package/dist/src/commands/settings.js +180 -0
  21. package/dist/src/commands/version.d.ts +42 -0
  22. package/dist/src/commands/version.js +106 -0
  23. package/dist/src/funnel/advisor-tip.d.ts +58 -0
  24. package/dist/src/funnel/advisor-tip.js +92 -0
  25. package/dist/src/funnel/attribution.d.ts +37 -0
  26. package/dist/src/funnel/attribution.js +101 -0
  27. package/dist/src/funnel/consent.d.ts +22 -0
  28. package/dist/src/funnel/consent.js +55 -0
  29. package/dist/src/funnel/credit-errors.d.ts +31 -0
  30. package/dist/src/funnel/credit-errors.js +88 -0
  31. package/dist/src/funnel/credit-notifier.d.ts +44 -0
  32. package/dist/src/funnel/credit-notifier.js +74 -0
  33. package/dist/src/funnel/disclosure.d.ts +46 -0
  34. package/dist/src/funnel/disclosure.js +97 -0
  35. package/dist/src/funnel/enrollment.d.ts +36 -0
  36. package/dist/src/funnel/enrollment.js +64 -0
  37. package/dist/src/funnel/environment.d.ts +17 -0
  38. package/dist/src/funnel/environment.js +39 -0
  39. package/dist/src/funnel/event-transport.d.ts +51 -0
  40. package/dist/src/funnel/event-transport.js +199 -0
  41. package/dist/src/funnel/events.d.ts +42 -0
  42. package/dist/src/funnel/events.js +150 -0
  43. package/dist/src/funnel/index.d.ts +20 -0
  44. package/dist/src/funnel/index.js +20 -0
  45. package/dist/src/funnel/insights.d.ts +49 -0
  46. package/dist/src/funnel/insights.js +120 -0
  47. package/dist/src/funnel/local-signals.d.ts +15 -0
  48. package/dist/src/funnel/local-signals.js +68 -0
  49. package/dist/src/funnel/message-transport.d.ts +51 -0
  50. package/dist/src/funnel/message-transport.js +149 -0
  51. package/dist/src/funnel/messages.d.ts +55 -0
  52. package/dist/src/funnel/messages.js +160 -0
  53. package/dist/src/funnel/power-saver-notifier.d.ts +44 -0
  54. package/dist/src/funnel/power-saver-notifier.js +92 -0
  55. package/dist/src/funnel/precedence.d.ts +16 -0
  56. package/dist/src/funnel/precedence.js +85 -0
  57. package/dist/src/funnel/promo.d.ts +41 -0
  58. package/dist/src/funnel/promo.js +144 -0
  59. package/dist/src/funnel/rate-limit-notifier.d.ts +55 -0
  60. package/dist/src/funnel/rate-limit-notifier.js +102 -0
  61. package/dist/src/funnel/rotation.d.ts +19 -0
  62. package/dist/src/funnel/rotation.js +70 -0
  63. package/dist/src/funnel/state.d.ts +13 -0
  64. package/dist/src/funnel/state.js +52 -0
  65. package/dist/src/funnel/toggle-cooldown.d.ts +17 -0
  66. package/dist/src/funnel/toggle-cooldown.js +32 -0
  67. package/dist/src/funnel/types.d.ts +86 -0
  68. package/dist/src/funnel/types.js +26 -0
  69. package/dist/src/init/executor.js +9 -3
  70. package/dist/src/init/helper-refresh.d.ts +33 -2
  71. package/dist/src/init/helper-refresh.js +102 -12
  72. package/dist/src/init/helpers-generator.js +52 -0
  73. package/dist/src/init/statusline-generator.js +282 -116
  74. package/dist/src/services/daemon-autostart.js +28 -5
  75. package/dist/src/services/fable-harness.d.ts +39 -0
  76. package/dist/src/services/fable-harness.js +41 -0
  77. package/package.json +13 -4
  78. package/dist/src/ruvector/lattice-wasm.d.ts +0 -14
  79. package/dist/src/ruvector/lattice-wasm.js +0 -144
  80. package/plugins/ruflo-metaharness/.claude-flow/daemon-state.json +0 -178
  81. package/plugins/ruflo-metaharness/.claude-flow/daemon.pid +0 -1
  82. package/plugins/ruflo-metaharness/.claude-flow/data/pending-insights.jsonl +0 -5
  83. package/plugins/ruflo-metaharness/.claude-flow/logs/daemon.log +0 -43
  84. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783604774864_ozbujc_prompt.log +0 -19
  85. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783604774864_ozbujc_result.log +0 -108
  86. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783605513587_ulvmpb_prompt.log +0 -19
  87. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783605513587_ulvmpb_result.log +0 -209
  88. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783606368867_ahysui_prompt.log +0 -19
  89. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/audit_1783606368867_ahysui_result.log +0 -192
  90. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/optimize_1783604894861_v6n3ut_prompt.log +0 -14
  91. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/optimize_1783604894861_v6n3ut_result.log +0 -66
  92. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/optimize_1783605934532_9h8ikb_prompt.log +0 -14
  93. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/optimize_1783605934532_9h8ikb_result.log +0 -68
  94. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/testgaps_1783605134860_9jssz9_prompt.log +0 -14
  95. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/testgaps_1783605134860_9jssz9_result.log +0 -69
  96. package/plugins/ruflo-metaharness/.claude-flow/logs/headless/testgaps_1783606516743_zftbaa_prompt.log +0 -14
  97. package/plugins/ruflo-metaharness/.claude-flow/metrics/backup.json +0 -7
  98. package/plugins/ruflo-metaharness/.claude-flow/metrics/codebase-map.json +0 -11
  99. package/plugins/ruflo-metaharness/.claude-flow/metrics/consolidation.json +0 -16
  100. package/plugins/ruflo-metaharness/.claude-flow/metrics/harness-loop.json +0 -83
  101. package/plugins/ruflo-metaharness/.claude-flow/metrics/performance.json +0 -67
  102. package/plugins/ruflo-metaharness/.claude-flow/metrics/security-audit.json +0 -191
  103. package/plugins/ruflo-metaharness/.claude-flow/metrics/test-gaps.json +0 -68
  104. package/plugins/ruflo-metaharness/.claude-flow/neural/stats.json +0 -6
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Remote message transport — best-effort fetch of the ADR-311 message
3
+ * feed, cached locally, validated through the ADR-301 content pipeline
4
+ * BEFORE any message is displayed.
5
+ *
6
+ * Design discipline:
7
+ * 1. **Never blocks the render.** The statusline reads only the local
8
+ * cache. This module refreshes the cache in the background; a fresh
9
+ * install shows the in-code fallback pool until the first refresh
10
+ * lands (usually seconds after CLI startup).
11
+ * 2. **Content pipeline stays authoritative.** Every message the server
12
+ * returns is validated by `isValidMessage()` from `messages.ts` —
13
+ * same schema, same host allowlist, same control-char strip, same
14
+ * 80-column cap. A tampered or accidentally-broken remote feed can
15
+ * pollute nothing.
16
+ * 3. **Fail silent.** Any network/parse/validation failure leaves the
17
+ * previously-cached (or in-code) pool intact.
18
+ * 4. **Bounded cache size.** ≤ 128 KiB and ≤ 200 messages — matches
19
+ * ADR-309's bounded-local-queue discipline.
20
+ * 5. **Kill switch.** `RUFLO_FUNNEL_MESSAGES=0` (or `RUFLO_FUNNEL=0`)
21
+ * disables the fetcher entirely.
22
+ * 6. **Signature-verification hook.** Reserved for a future ADR-311
23
+ * amendment; currently the transport-layer TLS + host allowlist is
24
+ * the trust boundary. All content is treated as untrusted regardless.
25
+ */
26
+ import * as https from 'https';
27
+ import { URL as NodeUrl } from 'url';
28
+ import { isValidMessage } from './messages.js';
29
+ import { readStateJson, writeStateJson } from './state.js';
30
+ const CACHE_FILE = 'funnel-messages-cache.json';
31
+ const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — matches server Cache-Control
32
+ const CACHE_MAX_BYTES = 128 * 1024;
33
+ const CACHE_MAX_MESSAGES = 200;
34
+ const FETCH_TIMEOUT_MS = 4_000;
35
+ /** Endpoint the client hits — overridable for staging / self-hosted. */
36
+ export const DEFAULT_MESSAGES_ENDPOINT = process.env.RUFLO_FUNNEL_MESSAGES_ENDPOINT ?? 'https://funnel.ruv.io/v1/messages';
37
+ function readCache() {
38
+ const raw = readStateJson(CACHE_FILE);
39
+ if (!raw || !Array.isArray(raw.messages))
40
+ return { fresh: false, messages: [] };
41
+ const age = Date.now() - (raw._ts ?? 0);
42
+ return { fresh: age < CACHE_TTL_MS, messages: raw.messages };
43
+ }
44
+ function writeCache(messages) {
45
+ // Bound the cache before persisting — messages come from an untrusted
46
+ // source, so we cap size regardless of server behavior.
47
+ let trimmed = messages.slice(0, CACHE_MAX_MESSAGES);
48
+ let body = JSON.stringify({ _ts: Date.now(), messages: trimmed });
49
+ while (Buffer.byteLength(body, 'utf-8') > CACHE_MAX_BYTES && trimmed.length > 0) {
50
+ trimmed = trimmed.slice(0, trimmed.length - 1);
51
+ body = JSON.stringify({ _ts: Date.now(), messages: trimmed });
52
+ }
53
+ writeStateJson(CACHE_FILE, { _ts: Date.now(), messages: trimmed });
54
+ }
55
+ function httpsGet(url) {
56
+ return new Promise((resolve) => {
57
+ let target;
58
+ try {
59
+ target = new NodeUrl(url);
60
+ }
61
+ catch {
62
+ resolve({ status: 0, body: 'bad-url' });
63
+ return;
64
+ }
65
+ if (target.protocol !== 'https:') {
66
+ resolve({ status: 0, body: 'non-https' });
67
+ return;
68
+ }
69
+ const req = https.request({
70
+ hostname: target.hostname,
71
+ port: target.port || 443,
72
+ path: target.pathname + target.search,
73
+ method: 'GET',
74
+ headers: {
75
+ 'User-Agent': 'ruflo-funnel/messages',
76
+ 'Accept': 'application/json',
77
+ },
78
+ }, (res) => {
79
+ let chunks = '';
80
+ res.setEncoding('utf-8');
81
+ res.on('data', (chunk) => { chunks += chunk; });
82
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: chunks }));
83
+ });
84
+ req.setTimeout(FETCH_TIMEOUT_MS, () => {
85
+ req.destroy();
86
+ resolve({ status: 0, body: 'timeout' });
87
+ });
88
+ req.on('error', () => resolve({ status: 0, body: 'error' }));
89
+ req.end();
90
+ });
91
+ }
92
+ function killSwitched(env = process.env) {
93
+ const kill = (v) => v !== undefined && /^(0|false|off|no)$/i.test(v.trim());
94
+ return kill(env.RUFLO_FUNNEL_MESSAGES) || kill(env.RUFLO_FUNNEL);
95
+ }
96
+ /**
97
+ * Best-effort refresh of the cache. Safe to call at any point in the
98
+ * CLI lifecycle — returns a summary; never throws; never blocks longer
99
+ * than FETCH_TIMEOUT_MS + write time.
100
+ */
101
+ export async function refreshRemoteMessages(opts) {
102
+ const env = opts?.env ?? process.env;
103
+ if (killSwitched(env))
104
+ return { refreshed: false, skipped: 'kill-switch' };
105
+ const cache = readCache();
106
+ if (!opts?.force && cache.fresh)
107
+ return { refreshed: false, skipped: 'fresh-cache' };
108
+ const endpoint = opts?.endpoint ?? DEFAULT_MESSAGES_ENDPOINT;
109
+ const res = await httpsGet(endpoint);
110
+ if (res.status !== 200)
111
+ return { refreshed: false, skipped: `http-${res.status}`, status: res.status };
112
+ let parsed;
113
+ try {
114
+ parsed = JSON.parse(res.body);
115
+ }
116
+ catch {
117
+ return { refreshed: false, skipped: 'json-parse-error' };
118
+ }
119
+ if (!parsed || typeof parsed !== 'object')
120
+ return { refreshed: false, skipped: 'not-object' };
121
+ const raw = parsed.messages;
122
+ if (!Array.isArray(raw))
123
+ return { refreshed: false, skipped: 'no-messages-field' };
124
+ // Every message goes through the SAME pipeline the in-code pool uses.
125
+ // This is where trust boundary enforcement actually lives.
126
+ const now = new Date();
127
+ const accepted = [];
128
+ let rejected = 0;
129
+ for (const candidate of raw) {
130
+ if (isValidMessage(candidate, now)) {
131
+ accepted.push(candidate);
132
+ }
133
+ else {
134
+ rejected += 1;
135
+ }
136
+ }
137
+ writeCache(accepted);
138
+ return { refreshed: true, accepted: accepted.length, rejected, status: res.status };
139
+ }
140
+ /**
141
+ * Read the cached remote pool. Returns [] when the cache is empty or
142
+ * stale enough to distrust — callers should merge with the in-code
143
+ * fallback pool.
144
+ */
145
+ export function getRemoteMessages() {
146
+ const cache = readCache();
147
+ return cache.messages;
148
+ }
149
+ //# sourceMappingURL=message-transport.js.map
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Funnel message registry and content pipeline — ADR-301 signed content
3
+ * boundaries.
4
+ *
5
+ * Messages are inert data. Regardless of how a message reached this process
6
+ * (in-package today; the signed helper channel later), the renderer treats
7
+ * it as untrusted and enforces, before display:
8
+ * - schema validation (invalid → dropped, never repaired)
9
+ * - length bound (≤ 80 display columns → over-length dropped)
10
+ * - URL host allowlist (exact hosts, in code — lookalikes/IPs dropped)
11
+ * - expiry
12
+ * - zero terminal control sequences (any control char, ANSI/OSC/DCS
13
+ * escape, or bidi override → dropped, not stripped-and-shown)
14
+ *
15
+ * There is no eval path and no styling in the payload: color comes only
16
+ * from the renderer's own fixed styles.
17
+ */
18
+ import type { FunnelMessage } from './types.js';
19
+ export declare const MAX_MESSAGE_COLUMNS = 80;
20
+ export declare function containsForbiddenSequences(text: string): boolean;
21
+ /** Approximate terminal display width: wide CJK/emoji count 2. */
22
+ export declare function displayWidth(text: string): number;
23
+ export declare function isAllowedUrl(url: string): boolean;
24
+ /**
25
+ * Full validation gate. Returns true only when every ADR-301 content
26
+ * boundary passes. Failures are silent drops by design — a bad message
27
+ * must never produce a visible error in the statusline.
28
+ */
29
+ export declare function isValidMessage(msg: unknown, now?: Date): msg is FunnelMessage;
30
+ /**
31
+ * Local promo/message content: INTENTIONALLY EMPTY (ADR-311 amendment).
32
+ *
33
+ * All rotation content (educational tips, promotional messages, and the
34
+ * disclosure notice) is served exclusively from the remote message feed
35
+ * (GET /v1/messages -> message-transport.ts -> Firestore). Zero message
36
+ * text or URLs ship in the CLI package.
37
+ *
38
+ * Fail-closed by design: if the remote feed is unreachable (network down,
39
+ * cert issue, server outage) and no prior successful fetch has populated
40
+ * the local cache, the rotation has nothing to show and the promo row
41
+ * simply does not render that cycle. There is no local content to fall
42
+ * back to -- this is a deliberate choice, not an oversight.
43
+ */
44
+ export declare const MESSAGES: FunnelMessage[];
45
+ /** Messages that survive every content boundary right now. */
46
+ export declare function eligibleMessages(now?: Date): FunnelMessage[];
47
+ /**
48
+ * Merge the remote (cached) message pool with the in-code fallback pool.
49
+ * The remote pool is authoritative when populated; the in-code pool
50
+ * covers cold starts and API-down periods. Deduplication is by `id` —
51
+ * remote wins over in-code for a given id so admins can override without
52
+ * a client release.
53
+ */
54
+ export declare function eligibleMessagesFromPools(inCodePool: readonly FunnelMessage[], remotePool: readonly FunnelMessage[], now?: Date): FunnelMessage[];
55
+ //# sourceMappingURL=messages.d.ts.map
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Funnel message registry and content pipeline — ADR-301 signed content
3
+ * boundaries.
4
+ *
5
+ * Messages are inert data. Regardless of how a message reached this process
6
+ * (in-package today; the signed helper channel later), the renderer treats
7
+ * it as untrusted and enforces, before display:
8
+ * - schema validation (invalid → dropped, never repaired)
9
+ * - length bound (≤ 80 display columns → over-length dropped)
10
+ * - URL host allowlist (exact hosts, in code — lookalikes/IPs dropped)
11
+ * - expiry
12
+ * - zero terminal control sequences (any control char, ANSI/OSC/DCS
13
+ * escape, or bidi override → dropped, not stripped-and-shown)
14
+ *
15
+ * There is no eval path and no styling in the payload: color comes only
16
+ * from the renderer's own fixed styles.
17
+ */
18
+ export const MAX_MESSAGE_COLUMNS = 80;
19
+ /**
20
+ * Exact-host allowlist (ADR-301). Ships in code, never in the payload.
21
+ * github.com is allowed only under /ruvnet/.
22
+ */
23
+ const ALLOWED_URL_HOSTS = new Set([
24
+ 'cognitum.one', 'www.cognitum.one', 'docs.cognitum.one',
25
+ // agentics.org — the rUv-authored OSS foundation. Distinct sponsor from
26
+ // cognitum.one; carries its own promotional messages in the rotation.
27
+ 'agentics.org', 'www.agentics.org',
28
+ ]);
29
+ const GITHUB_HOST = 'github.com';
30
+ const GITHUB_PATH_PREFIX = '/ruvnet/';
31
+ /**
32
+ * C0/C1 controls (incl. ESC, so every ANSI/OSC/DCS sequence trips this),
33
+ * DEL, and Unicode bidirectional overrides/isolates.
34
+ */
35
+ // eslint-disable-next-line no-control-regex
36
+ const FORBIDDEN_CHARS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/;
37
+ export function containsForbiddenSequences(text) {
38
+ return FORBIDDEN_CHARS.test(text);
39
+ }
40
+ /** Approximate terminal display width: wide CJK/emoji count 2. */
41
+ export function displayWidth(text) {
42
+ let width = 0;
43
+ for (const ch of text) {
44
+ const cp = ch.codePointAt(0) ?? 0;
45
+ if (cp === 0xfe0f || cp === 0x200d)
46
+ continue; // variation selector / ZWJ
47
+ const wide = (cp >= 0x1100 && cp <= 0x115f) ||
48
+ (cp >= 0x2e80 && cp <= 0xa4cf) ||
49
+ (cp >= 0xac00 && cp <= 0xd7a3) ||
50
+ (cp >= 0xf900 && cp <= 0xfaff) ||
51
+ (cp >= 0xff00 && cp <= 0xff60) ||
52
+ (cp >= 0x1f000 && cp <= 0x1faff) ||
53
+ (cp >= 0x20000 && cp <= 0x3fffd);
54
+ width += wide ? 2 : 1;
55
+ }
56
+ return width;
57
+ }
58
+ export function isAllowedUrl(url) {
59
+ let parsed;
60
+ try {
61
+ parsed = new URL(url);
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ if (parsed.protocol !== 'https:')
67
+ return false;
68
+ if (ALLOWED_URL_HOSTS.has(parsed.hostname))
69
+ return true;
70
+ if (parsed.hostname === GITHUB_HOST && parsed.pathname.startsWith(GITHUB_PATH_PREFIX))
71
+ return true;
72
+ return false;
73
+ }
74
+ /**
75
+ * Full validation gate. Returns true only when every ADR-301 content
76
+ * boundary passes. Failures are silent drops by design — a bad message
77
+ * must never produce a visible error in the statusline.
78
+ */
79
+ export function isValidMessage(msg, now = new Date()) {
80
+ if (typeof msg !== 'object' || msg === null)
81
+ return false;
82
+ const m = msg;
83
+ if (m.schemaVersion !== 1)
84
+ return false;
85
+ if (typeof m.id !== 'string' || m.id.length === 0 || m.id.length > 64)
86
+ return false;
87
+ if (m.class !== 'educational' && m.class !== 'promotional' && m.class !== 'disclosure')
88
+ return false;
89
+ if (typeof m.text !== 'string' || m.text.length === 0)
90
+ return false;
91
+ if (containsForbiddenSequences(m.text))
92
+ return false;
93
+ if (displayWidth(m.text) > MAX_MESSAGE_COLUMNS)
94
+ return false;
95
+ // Disclosure messages MUST carry the exact ADR-301 manage-instruction tail
96
+ // — losing that on a truncated/malformed remote message is an invariant
97
+ // violation, not a cosmetic issue. Never repaired; dropped instead.
98
+ if (m.class === 'disclosure' && !m.text.includes(' · manage: ruflo settings'))
99
+ return false;
100
+ if (m.url !== undefined) {
101
+ if (typeof m.url !== 'string' || !isAllowedUrl(m.url))
102
+ return false;
103
+ }
104
+ if (m.expiresAt !== undefined) {
105
+ if (typeof m.expiresAt !== 'string')
106
+ return false;
107
+ const exp = Date.parse(m.expiresAt);
108
+ if (Number.isNaN(exp) || exp <= now.getTime())
109
+ return false;
110
+ }
111
+ return true;
112
+ }
113
+ /**
114
+ * Local promo/message content: INTENTIONALLY EMPTY (ADR-311 amendment).
115
+ *
116
+ * All rotation content (educational tips, promotional messages, and the
117
+ * disclosure notice) is served exclusively from the remote message feed
118
+ * (GET /v1/messages -> message-transport.ts -> Firestore). Zero message
119
+ * text or URLs ship in the CLI package.
120
+ *
121
+ * Fail-closed by design: if the remote feed is unreachable (network down,
122
+ * cert issue, server outage) and no prior successful fetch has populated
123
+ * the local cache, the rotation has nothing to show and the promo row
124
+ * simply does not render that cycle. There is no local content to fall
125
+ * back to -- this is a deliberate choice, not an oversight.
126
+ */
127
+ export const MESSAGES = [];
128
+ /** Messages that survive every content boundary right now. */
129
+ export function eligibleMessages(now = new Date()) {
130
+ return MESSAGES.filter((m) => isValidMessage(m, now));
131
+ }
132
+ /**
133
+ * Merge the remote (cached) message pool with the in-code fallback pool.
134
+ * The remote pool is authoritative when populated; the in-code pool
135
+ * covers cold starts and API-down periods. Deduplication is by `id` —
136
+ * remote wins over in-code for a given id so admins can override without
137
+ * a client release.
138
+ */
139
+ export function eligibleMessagesFromPools(inCodePool, remotePool, now = new Date()) {
140
+ const seen = new Set();
141
+ const out = [];
142
+ for (const m of remotePool) {
143
+ if (!isValidMessage(m, now))
144
+ continue;
145
+ if (seen.has(m.id))
146
+ continue;
147
+ seen.add(m.id);
148
+ out.push(m);
149
+ }
150
+ for (const m of inCodePool) {
151
+ if (!isValidMessage(m, now))
152
+ continue;
153
+ if (seen.has(m.id))
154
+ continue;
155
+ seen.add(m.id);
156
+ out.push(m);
157
+ }
158
+ return out;
159
+ }
160
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Power-saver notifier — ADR-314 §A out-of-band signal path.
3
+ *
4
+ * Structural mirror of rate-limit-notifier.ts, same self-reported/manual
5
+ * constraint (ADR-312's detection gap applies unchanged — ruflo cannot read
6
+ * "your account is at 20%" any more than it can read "you are rate
7
+ * limited"). Deliberately a SEPARATE flag from rate-limited: "running low,
8
+ * want to proactively conserve" (still have capacity) and "blocked" (zero
9
+ * capacity left) are different urgencies — conflating them would mean
10
+ * power-saver mode never fires until you're already blocked (too late to
11
+ * have conserved anything).
12
+ *
13
+ * State is cheap and durable:
14
+ * ~/.ruflo/quota-status.json = { low: bool, since: ISO, cleared: ISO|null, lastToggleAt: ISO|null }
15
+ *
16
+ * Same 6h TTL rationale as rate-limit-notifier.ts, and the same ADR-314 §D1
17
+ * toggle cooldown (10 min) — a self-reported flag with zero server-side
18
+ * verification needs at least this much client-side friction against
19
+ * casual always-on gaming.
20
+ */
21
+ export declare const QUOTA_STATUS_FILE = "quota-status.json";
22
+ /** Auto-expire a forgotten manual flag after 6h (see module doc). */
23
+ export declare const QUOTA_LOW_TTL_MS: number;
24
+ export interface QuotaLowStatus {
25
+ low: boolean;
26
+ since: string | null;
27
+ cleared: string | null;
28
+ lastToggleAt: string | null;
29
+ }
30
+ /** Read the current power-saver status. Never throws. Applies the TTL. */
31
+ export declare function readQuotaLowStatus(now?: Date): QuotaLowStatus;
32
+ /**
33
+ * Mark quota as running low — idempotent, cooldown-gated (ADR-314 §D1).
34
+ * Returns false when the cooldown blocks the flip (not yet applied).
35
+ */
36
+ export declare function markQuotaLow(now?: Date): boolean;
37
+ /** Clear power-saver status. Cooldown-gated the same way as the mark direction. */
38
+ export declare function clearQuotaLowStatus(now?: Date): boolean;
39
+ /**
40
+ * User-facing single-line summary — plain text, no ANSI. Returns null when
41
+ * not flagged low (no surface).
42
+ */
43
+ export declare function quotaLowNotice(now?: Date): string | null;
44
+ //# sourceMappingURL=power-saver-notifier.d.ts.map
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Power-saver notifier — ADR-314 §A out-of-band signal path.
3
+ *
4
+ * Structural mirror of rate-limit-notifier.ts, same self-reported/manual
5
+ * constraint (ADR-312's detection gap applies unchanged — ruflo cannot read
6
+ * "your account is at 20%" any more than it can read "you are rate
7
+ * limited"). Deliberately a SEPARATE flag from rate-limited: "running low,
8
+ * want to proactively conserve" (still have capacity) and "blocked" (zero
9
+ * capacity left) are different urgencies — conflating them would mean
10
+ * power-saver mode never fires until you're already blocked (too late to
11
+ * have conserved anything).
12
+ *
13
+ * State is cheap and durable:
14
+ * ~/.ruflo/quota-status.json = { low: bool, since: ISO, cleared: ISO|null, lastToggleAt: ISO|null }
15
+ *
16
+ * Same 6h TTL rationale as rate-limit-notifier.ts, and the same ADR-314 §D1
17
+ * toggle cooldown (10 min) — a self-reported flag with zero server-side
18
+ * verification needs at least this much client-side friction against
19
+ * casual always-on gaming.
20
+ */
21
+ import { readStateJson, writeStateJson } from './state.js';
22
+ import { cooldownActive } from './toggle-cooldown.js';
23
+ export const QUOTA_STATUS_FILE = 'quota-status.json';
24
+ /** Auto-expire a forgotten manual flag after 6h (see module doc). */
25
+ export const QUOTA_LOW_TTL_MS = 6 * 60 * 60 * 1000;
26
+ /** Read the current power-saver status. Never throws. Applies the TTL. */
27
+ export function readQuotaLowStatus(now = new Date()) {
28
+ const raw = readStateJson(QUOTA_STATUS_FILE);
29
+ const status = {
30
+ low: raw?.low ?? false,
31
+ since: raw?.since ?? null,
32
+ cleared: raw?.cleared ?? null,
33
+ lastToggleAt: raw?.lastToggleAt ?? null,
34
+ };
35
+ if (status.low && status.since) {
36
+ const since = Date.parse(status.since);
37
+ if (!Number.isNaN(since) && now.getTime() - since >= QUOTA_LOW_TTL_MS) {
38
+ return { low: false, since: status.since, cleared: now.toISOString(), lastToggleAt: status.lastToggleAt };
39
+ }
40
+ }
41
+ return status;
42
+ }
43
+ /**
44
+ * Mark quota as running low — idempotent, cooldown-gated (ADR-314 §D1).
45
+ * Returns false when the cooldown blocks the flip (not yet applied).
46
+ */
47
+ export function markQuotaLow(now = new Date()) {
48
+ const current = readQuotaLowStatus(now);
49
+ if (current.low && current.since)
50
+ return true; // already flagged, not a change
51
+ if (cooldownActive(current.lastToggleAt, now))
52
+ return false;
53
+ writeStateJson(QUOTA_STATUS_FILE, {
54
+ low: true,
55
+ since: current.since ?? now.toISOString(),
56
+ cleared: null,
57
+ lastToggleAt: now.toISOString(),
58
+ });
59
+ return true;
60
+ }
61
+ /** Clear power-saver status. Cooldown-gated the same way as the mark direction. */
62
+ export function clearQuotaLowStatus(now = new Date()) {
63
+ const current = readQuotaLowStatus(now);
64
+ if (!current.low)
65
+ return true; // already clear, not a change
66
+ if (cooldownActive(current.lastToggleAt, now))
67
+ return false;
68
+ writeStateJson(QUOTA_STATUS_FILE, {
69
+ low: false,
70
+ since: current.since,
71
+ cleared: now.toISOString(),
72
+ lastToggleAt: now.toISOString(),
73
+ });
74
+ return true;
75
+ }
76
+ /**
77
+ * User-facing single-line summary — plain text, no ANSI. Returns null when
78
+ * not flagged low (no surface).
79
+ */
80
+ export function quotaLowNotice(now = new Date()) {
81
+ const status = readQuotaLowStatus(now);
82
+ if (!status.low)
83
+ return null;
84
+ const since = status.since ? Date.parse(status.since) : NaN;
85
+ if (Number.isNaN(since)) {
86
+ return 'Power saver mode active · manage: ruflo proxy power-saver-disable';
87
+ }
88
+ const ageMin = Math.max(0, Math.round((now.getTime() - since) / (60 * 1000)));
89
+ const when = ageMin < 1 ? 'just now' : ageMin < 60 ? `${ageMin}m ago` : `${Math.round(ageMin / 60)}h ago`;
90
+ return `Power saver mode active (${when}) · manage: ruflo proxy power-saver-disable`;
91
+ }
92
+ //# sourceMappingURL=power-saver-notifier.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Control precedence resolver — ADR-305 (normative).
3
+ *
4
+ * 1. RUFLO_FUNNEL=0 (environment)
5
+ * 2. Enterprise managed policy
6
+ * 3. User config (funnel.enabled — user-level and project-level)
7
+ * 4. Package default
8
+ * 5. Remote signed policy (only when the freshness feed is enabled)
9
+ *
10
+ * A lower-precedence source must never re-enable a higher-precedence
11
+ * disable — implemented as a strict AND chain: every source can veto,
12
+ * none can override a veto above it.
13
+ */
14
+ import type { FunnelEnabledDecision } from './types.js';
15
+ export declare function resolveFunnelEnabled(cwd?: string, env?: NodeJS.ProcessEnv): FunnelEnabledDecision;
16
+ //# sourceMappingURL=precedence.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Control precedence resolver — ADR-305 (normative).
3
+ *
4
+ * 1. RUFLO_FUNNEL=0 (environment)
5
+ * 2. Enterprise managed policy
6
+ * 3. User config (funnel.enabled — user-level and project-level)
7
+ * 4. Package default
8
+ * 5. Remote signed policy (only when the freshness feed is enabled)
9
+ *
10
+ * A lower-precedence source must never re-enable a higher-precedence
11
+ * disable — implemented as a strict AND chain: every source can veto,
12
+ * none can override a veto above it.
13
+ */
14
+ import * as fs from 'fs';
15
+ import * as path from 'path';
16
+ import { readStateJson } from './state.js';
17
+ import { getDisclosure } from './disclosure.js';
18
+ function envDisabled(env) {
19
+ const v = env.RUFLO_FUNNEL;
20
+ return v !== undefined && /^(0|false|off|no)$/i.test(v.trim());
21
+ }
22
+ function enterprisePolicyDisabled(env) {
23
+ const candidates = [];
24
+ if (env.RUFLO_ENTERPRISE_POLICY)
25
+ candidates.push(env.RUFLO_ENTERPRISE_POLICY);
26
+ if (process.platform === 'win32') {
27
+ if (env.ProgramData)
28
+ candidates.push(path.join(env.ProgramData, 'ruflo', 'policy.json'));
29
+ }
30
+ else {
31
+ candidates.push('/etc/ruflo/policy.json');
32
+ }
33
+ for (const p of candidates) {
34
+ try {
35
+ const policy = JSON.parse(fs.readFileSync(p, 'utf-8'));
36
+ if (policy?.funnel?.enabled === false)
37
+ return true;
38
+ }
39
+ catch {
40
+ // unreadable/absent policy is not a policy
41
+ }
42
+ }
43
+ return false;
44
+ }
45
+ function userConfigDisabled() {
46
+ const cfg = readStateJson('funnel.json');
47
+ return cfg?.enabled === false;
48
+ }
49
+ function projectConfigDisabled(cwd) {
50
+ try {
51
+ const cfg = JSON.parse(fs.readFileSync(path.join(cwd, 'claude-flow.config.json'), 'utf-8'));
52
+ return cfg?.funnel?.enabled === false;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Remote signed policy (ADR-305 freshness kill switch). The feed is opt-in
60
+ * and OFF by default; when a validated policy has been stored locally it can
61
+ * only disable — sitting at the bottom of the chain guarantees it can never
62
+ * re-enable anything a higher source turned off.
63
+ */
64
+ function remotePolicyDisabled() {
65
+ const policy = readStateJson('funnel-remote-policy.json');
66
+ return policy?.funnelEnabled === false;
67
+ }
68
+ export function resolveFunnelEnabled(cwd = process.cwd(), env = process.env) {
69
+ if (envDisabled(env))
70
+ return { enabled: false, decidedBy: 'env' };
71
+ if (enterprisePolicyDisabled(env))
72
+ return { enabled: false, decidedBy: 'enterprise-policy' };
73
+ if (userConfigDisabled())
74
+ return { enabled: false, decidedBy: 'user-config' };
75
+ if (projectConfigDisabled(cwd))
76
+ return { enabled: false, decidedBy: 'project-config' };
77
+ // Declining the disclosure disables all funnel surfaces (ADR-301 invariant).
78
+ if (getDisclosure().state === 'disclosed_disabled') {
79
+ return { enabled: false, decidedBy: 'disclosure-declined' };
80
+ }
81
+ if (remotePolicyDisabled())
82
+ return { enabled: false, decidedBy: 'remote-policy' };
83
+ return { enabled: true, decidedBy: 'package-default' };
84
+ }
85
+ //# sourceMappingURL=precedence.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Promo-row orchestrator — the single entry point the statusline hook calls
3
+ * (ADR-301). Applies, in order:
4
+ *
5
+ * 1. Control precedence (env / enterprise / user / project / remote) —
6
+ * any disable → nothing renders, ever.
7
+ * 2. Environment gates — CI never sees funnel content.
8
+ * 3. Disclosure gate — an upgraded install shows the disclosure text
9
+ * (with the disable instruction) before any message; promotional
10
+ * content only after the grace window.
11
+ * 4. ADR-313 sponsored-downtime override — preempts everything below
12
+ * while rate-limited (unconditional, not slot-based).
13
+ * 5. Local insight ticker (insights.ts) — a reserved 1-in-5 slot shows an
14
+ * environment/task-aware suggestion (CVEs, uncommitted changes,
15
+ * power-saver state) when one exists; otherwise falls through.
16
+ * 6. Rotation — 4:1 educational:promotional, 30-min promo repeat cap.
17
+ *
18
+ * Output is plain text (no ANSI — the renderer applies its own fixed
19
+ * style), ≤ 80 columns, already sanitized by the message pipeline.
20
+ */
21
+ import type { PromoRow } from './types.js';
22
+ import { type LocalInsightContext } from './insights.js';
23
+ export interface PromoContext {
24
+ cwd?: string;
25
+ env?: NodeJS.ProcessEnv;
26
+ now?: Date;
27
+ /**
28
+ * Whether the calling surface is an interactive session. The statusline
29
+ * hook is spawned with piped stdio by an interactive host, so the caller
30
+ * asserts interactivity; directly-run non-TTY invocations pass false.
31
+ */
32
+ interactive: boolean;
33
+ /**
34
+ * Local environment/task signal for the insight ticker (insights.ts) —
35
+ * optional and additive. Callers that don't pass it simply never see a
36
+ * local insight; the remote rotation is entirely unaffected either way.
37
+ */
38
+ localInsights?: LocalInsightContext;
39
+ }
40
+ export declare function getFunnelPromo(ctx: PromoContext): PromoRow | null;
41
+ //# sourceMappingURL=promo.d.ts.map