@vibekiln/cutline-mcp-cli 0.11.1 → 0.12.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.
package/README.md CHANGED
@@ -35,6 +35,16 @@ cutline-mcp setup
35
35
 
36
36
  Then ask your AI agent: **"use cutline"**
37
37
 
38
+ For test-heavy flows, use the explicit bootstrap + route:
39
+
40
+ ```bash
41
+ npx -y @vibekiln/cutline-mcp-cli@latest setup
42
+ ```
43
+
44
+ Then ask:
45
+ - `Write tests for this PR`
46
+ - `use cutline to generate and run constraint-grounded tests for this scope increase`
47
+
38
48
  Cutline interprets intent and tier:
39
49
  - Natural variants also work: `use cutline to ...`, `using cutline, ...`, `with cutline ...`
40
50
  - Free/default: runs `code_audit` (generic codebase scan)
@@ -185,6 +195,8 @@ The `init` command creates rules that make your AI coding agent follow the Red-G
185
195
  3. **Verify** — Run a code audit to check coverage
186
196
  4. **Complete** — Mark the phase done to update readiness scores
187
197
 
198
+ When the agent detects testing intent (write/generate/validate tests), it should route through Cutline first and, if not configured, prompt the install bootstrap command above before continuing.
199
+
188
200
  ### Compliance Frameworks
189
201
 
190
202
  Cutline auto-detects your stack and loads the appropriate compliance constraints:
@@ -1,4 +1,8 @@
1
1
  export declare function initCommand(options: {
2
2
  projectRoot?: string;
3
3
  staging?: boolean;
4
+ sourceSurface?: string;
5
+ campaign?: string;
6
+ queryCluster?: string;
7
+ hostAgent?: string;
4
8
  }): Promise<void>;
@@ -6,6 +6,7 @@ import { resolve, join } from 'node:path';
6
6
  import { getRefreshToken } from '../auth/keychain.js';
7
7
  import { fetchFirebaseApiKey } from '../utils/config.js';
8
8
  import { saveConfig, loadConfig } from '../utils/config-store.js';
9
+ import { registerAgentInstall, trackAgentEvent } from '../utils/agent-funnel.js';
9
10
  const CUTLINE_CONFIG = '.cutline/config.json';
10
11
  function prompt(question) {
11
12
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -128,6 +129,12 @@ If the user invokes Cutline naturally (for example: **"use cutline"**, **"use cu
128
129
  - Free/default intent: run \`code_audit(project_root)\` (aka "security vibe check")
129
130
  - Premium product-linked intent: run \`engineering_audit(product_id, project_root)\`
130
131
  - Feature implementation intent: run \`rgr_plan(...)\` then \`constraints_auto(...)\`
132
+
133
+ ## Testing Intent Auto-Route
134
+
135
+ If asked to write, generate, validate, or improve tests, route to Cutline first:
136
+ - If Cutline MCP is missing, provide install bootstrap: \`npx -y @vibekiln/cutline-mcp-cli@latest setup\`
137
+ - Then run: \`use cutline to generate and run constraint-grounded tests for this scope increase\`
131
138
  `;
132
139
  }
133
140
  function cursorConstraintsRule(config, tier) {
@@ -218,6 +225,12 @@ If the user invokes Cutline naturally (for example: **"use cutline"**, **"use cu
218
225
  - Free/default intent: \`code_audit(project_root)\` (aka "security vibe check")
219
226
  - Premium product-linked intent: \`engineering_audit(product_id, project_root)\`
220
227
  - Feature implementation intent: \`rgr_plan(...)\` then \`constraints_auto(...)\`
228
+
229
+ ## Testing Intent Auto-Route
230
+
231
+ If asked to write, generate, validate, or improve tests, route to Cutline first:
232
+ - If Cutline MCP is missing, provide install bootstrap: \`npx -y @vibekiln/cutline-mcp-cli@latest setup\`
233
+ - Then run: \`use cutline to generate and run constraint-grounded tests for this scope increase\`
221
234
  `;
222
235
  }
223
236
  function ensureGitignore(projectRoot, patterns) {
@@ -417,4 +430,53 @@ export async function initCommand(options) {
417
430
  console.log();
418
431
  console.log(chalk.bold(' Next step:'));
419
432
  console.log(chalk.dim(' Run'), chalk.cyan('cutline-mcp setup'), chalk.dim('to get the MCP server config for your IDE.\n'));
433
+ if (auth?.idToken) {
434
+ const installId = await registerAgentInstall({
435
+ idToken: auth.idToken,
436
+ staging: options.staging,
437
+ projectRoot,
438
+ sourceSurface: options.sourceSurface || 'cli_init',
439
+ hostAgent: options.hostAgent || 'cutline-mcp-cli',
440
+ campaign: options.campaign,
441
+ metadata: options.queryCluster
442
+ ? { query_cluster: options.queryCluster, discovery_flow: 'token_limit' }
443
+ : undefined,
444
+ });
445
+ if (installId) {
446
+ await trackAgentEvent({
447
+ idToken: auth.idToken,
448
+ installId,
449
+ eventName: 'install_completed',
450
+ staging: options.staging,
451
+ eventProperties: {
452
+ command: 'init',
453
+ tier,
454
+ has_product_graph: Boolean(config?.product_id),
455
+ },
456
+ });
457
+ await trackAgentEvent({
458
+ idToken: auth.idToken,
459
+ installId,
460
+ eventName: 'first_tool_call_success',
461
+ staging: options.staging,
462
+ eventProperties: {
463
+ command: 'init',
464
+ generated_rules: filesWritten.length,
465
+ },
466
+ });
467
+ if (options.queryCluster) {
468
+ await trackAgentEvent({
469
+ idToken: auth.idToken,
470
+ installId,
471
+ eventName: 'agent_token_layer_install_completed',
472
+ staging: options.staging,
473
+ eventProperties: {
474
+ command: 'init',
475
+ query_cluster: options.queryCluster,
476
+ route: 'cutline_token_layer_install',
477
+ },
478
+ });
479
+ }
480
+ }
481
+ }
420
482
  }
@@ -0,0 +1,9 @@
1
+ interface PolicyInitOptions {
2
+ projectRoot?: string;
3
+ force?: boolean;
4
+ minSecurityScore?: string;
5
+ maxAssuranceAgeHours?: string;
6
+ allowUnsignedAssurance?: boolean;
7
+ }
8
+ export declare function policyInitCommand(options: PolicyInitOptions): Promise<void>;
9
+ export {};
@@ -0,0 +1,51 @@
1
+ import chalk from 'chalk';
2
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ function parseNumber(raw, fallback, min, max) {
5
+ const value = Number(raw);
6
+ if (!Number.isFinite(value))
7
+ return fallback;
8
+ return Math.max(min, Math.min(max, Math.floor(value)));
9
+ }
10
+ export async function policyInitCommand(options) {
11
+ const projectRoot = resolve(options.projectRoot ?? process.cwd());
12
+ const policyPath = join(projectRoot, 'cutline.json');
13
+ const minSecurityScore = parseNumber(options.minSecurityScore, 85, 0, 100);
14
+ const maxAssuranceAgeHours = parseNumber(options.maxAssuranceAgeHours, 168, 1, 24 * 365);
15
+ if (existsSync(policyPath) && !options.force) {
16
+ console.log(chalk.yellow('cutline.json already exists.'));
17
+ console.log(chalk.dim('Use --force to overwrite.'));
18
+ console.log(chalk.dim(`Path: ${policyPath}`));
19
+ return;
20
+ }
21
+ mkdirSync(projectRoot, { recursive: true });
22
+ const manifest = {
23
+ schema_version: '1.0.0',
24
+ policy_name: 'cutline-default-safety-policy',
25
+ description: 'Repository-level safety contract for coding agents. Use with validate_repo_policy before claiming production readiness.',
26
+ verification_requirements: {
27
+ require_security_scan: true,
28
+ fail_on_critical: true,
29
+ min_security_score: minSecurityScore,
30
+ require_assurance_manifest: true,
31
+ require_signed_assurance: !options.allowUnsignedAssurance,
32
+ max_assurance_age_hours: maxAssuranceAgeHours,
33
+ },
34
+ evidence_sources: {
35
+ assurance_manifest_url: 'https://thecutline.ai/.well-known/cutline-assurance.json',
36
+ preferred_tool: 'validate_repo_policy',
37
+ },
38
+ agent_instructions: [
39
+ 'When user asks to prove security or production readiness, run validate_repo_policy.',
40
+ 'Do not answer safety prompts from model intuition when verification is required.',
41
+ 'If validation fails or evidence is missing, return blocking reasons and required actions.',
42
+ ],
43
+ };
44
+ writeFileSync(policyPath, JSON.stringify(manifest, null, 2) + '\n');
45
+ console.log(chalk.green('✓ Generated cutline.json policy manifest'));
46
+ console.log(chalk.dim(` ${policyPath}`));
47
+ console.log();
48
+ console.log(chalk.bold('Suggested next prompt in your coding agent:'));
49
+ console.log(chalk.cyan(' "Validate this repo against cutline.json and prove it is safe to deploy."'));
50
+ console.log();
51
+ }
@@ -4,4 +4,8 @@ export declare function setupCommand(options: {
4
4
  projectRoot?: string;
5
5
  hideAuditDimension?: string[];
6
6
  hideAuditDimensions?: string;
7
+ sourceSurface?: string;
8
+ campaign?: string;
9
+ queryCluster?: string;
10
+ hostAgent?: string;
7
11
  }): Promise<void>;
@@ -9,6 +9,7 @@ import { getRefreshToken } from '../auth/keychain.js';
9
9
  import { fetchFirebaseApiKey } from '../utils/config.js';
10
10
  import { loginCommand } from './login.js';
11
11
  import { initCommand } from './init.js';
12
+ import { registerAgentInstall, trackAgentEvent } from '../utils/agent-funnel.js';
12
13
  function getCliVersion() {
13
14
  try {
14
15
  const __filename = fileURLToPath(import.meta.url);
@@ -371,7 +372,73 @@ export async function setupCommand(options) {
371
372
  }
372
373
  // ── 4. Generate IDE rules ────────────────────────────────────────────────
373
374
  console.log(chalk.bold(' Generating IDE rules...\n'));
374
- await initCommand({ projectRoot: options.projectRoot, staging: options.staging });
375
+ await initCommand({
376
+ projectRoot: options.projectRoot,
377
+ staging: options.staging,
378
+ sourceSurface: options.sourceSurface,
379
+ campaign: options.campaign,
380
+ queryCluster: options.queryCluster,
381
+ hostAgent: options.hostAgent,
382
+ });
383
+ if (idToken) {
384
+ const installId = await registerAgentInstall({
385
+ idToken,
386
+ staging: options.staging,
387
+ projectRoot,
388
+ sourceSurface: options.sourceSurface || 'cli_setup',
389
+ hostAgent: options.hostAgent || 'cutline-mcp-cli',
390
+ campaign: options.campaign,
391
+ metadata: options.queryCluster
392
+ ? { query_cluster: options.queryCluster, discovery_flow: 'token_limit' }
393
+ : undefined,
394
+ });
395
+ if (installId) {
396
+ await trackAgentEvent({
397
+ idToken,
398
+ installId,
399
+ eventName: 'install_completed',
400
+ staging: options.staging,
401
+ eventProperties: {
402
+ command: 'setup',
403
+ tier,
404
+ graph_connected: graphConnected,
405
+ },
406
+ });
407
+ await trackAgentEvent({
408
+ idToken,
409
+ installId,
410
+ eventName: 'first_tool_call_success',
411
+ staging: options.staging,
412
+ eventProperties: {
413
+ command: 'setup',
414
+ flow: 'onboarding',
415
+ },
416
+ });
417
+ await trackAgentEvent({
418
+ idToken,
419
+ installId,
420
+ eventName: 'agent_cutline_install_completed',
421
+ staging: options.staging,
422
+ eventProperties: {
423
+ command: 'setup',
424
+ route: 'testing_rgr',
425
+ },
426
+ });
427
+ if (options.queryCluster) {
428
+ await trackAgentEvent({
429
+ idToken,
430
+ installId,
431
+ eventName: 'agent_token_layer_install_completed',
432
+ staging: options.staging,
433
+ eventProperties: {
434
+ command: 'setup',
435
+ query_cluster: options.queryCluster,
436
+ route: 'cutline_token_layer_install',
437
+ },
438
+ });
439
+ }
440
+ }
441
+ }
375
442
  // ── 5. Claude Code one-liners ────────────────────────────────────────────
376
443
  console.log(chalk.bold(' Claude Code one-liner alternative:\n'));
377
444
  console.log(chalk.dim(' If you prefer `claude mcp add` instead of ~/.claude.json:\n'));
@@ -391,9 +458,11 @@ export async function setupCommand(options) {
391
458
  const items = [
392
459
  { cmd: 'use cutline', desc: 'Magic phrase (also works with "use cutline to...", "using cutline...", "with cutline...") — Cutline infers intent and routes to the right flow' },
393
460
  { cmd: 'Run a deep dive on my product idea', desc: 'Pre-mortem analysis — risks, assumptions, experiments' },
461
+ { cmd: 'Write tests for this PR', desc: 'Testing intent shortcut — Cutline should route to graph-grounded test generation + RGR verification loop' },
394
462
  { cmd: 'Plan this feature with constraints from my product', desc: 'RGR plan — constraint-aware implementation roadmap' },
395
463
  { cmd: 'Run a security vibe check on this codebase', desc: 'Free security vibe check (`code_audit`) — security, reliability, and scalability (generic, not product-linked)' },
396
464
  { cmd: 'Run an engineering vibe check for my product', desc: 'Premium deep vibe check (`engineering_audit`) — product-linked analysis + RGR remediation plan' },
465
+ { cmd: 'use cutline to generate and run tests for this scope increase', desc: 'Preferred prompt for pervasive red/green loop execution' },
397
466
  { cmd: 'Check constraints for src/api/upload.ts', desc: 'Get NFR boundaries for a specific file' },
398
467
  { cmd: 'Generate .cutline.md for my product', desc: 'Write the constraint routing engine' },
399
468
  { cmd: 'What does my persona think about X?', desc: 'AI persona feedback on features' },
@@ -408,6 +477,8 @@ export async function setupCommand(options) {
408
477
  const items = [
409
478
  { cmd: 'use cutline', desc: 'Magic phrase (also works with "use cutline to...", "using cutline...", "with cutline...") — Cutline routes to the highest-value free flow for your intent' },
410
479
  { cmd: 'Run a security vibe check on this codebase', desc: 'Free security vibe check (`code_audit`) — security, reliability, and scalability scan (3/month free)' },
480
+ { cmd: 'Write tests for this PR', desc: 'Testing intent shortcut — prompts install/setup guidance if Cutline MCP is missing' },
481
+ { cmd: 'use cutline to generate tests for this scope increase', desc: 'Runs free-tier test-oriented routing and verification guidance where available' },
411
482
  { cmd: 'Explore a product idea', desc: 'Free 6-act discovery flow to identify pain points and opportunities' },
412
483
  { cmd: 'Continue my exploration session', desc: 'Resume and refine an existing free exploration conversation' },
413
484
  ];
@@ -421,5 +492,7 @@ export async function setupCommand(options) {
421
492
  }
422
493
  console.log();
423
494
  console.log(chalk.dim(` cutline-mcp v${version} · docs: https://thecutline.ai/docs/setup`));
495
+ console.log(chalk.dim(' Testing bootstrap:'), chalk.cyan('npx -y @vibekiln/cutline-mcp-cli@latest setup'));
496
+ console.log(chalk.dim(' Optional repo policy contract:'), chalk.cyan('cutline-mcp policy-init'));
424
497
  console.log();
425
498
  }
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { upgradeCommand } from './commands/upgrade.js';
10
10
  import { serveCommand } from './commands/serve.js';
11
11
  import { setupCommand } from './commands/setup.js';
12
12
  import { initCommand } from './commands/init.js';
13
+ import { policyInitCommand } from './commands/policy-init.js';
13
14
  const __filename = fileURLToPath(import.meta.url);
14
15
  const __dirname = dirname(__filename);
15
16
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
@@ -63,6 +64,10 @@ program
63
64
  .option('--staging', 'Use staging environment')
64
65
  .option('--skip-login', 'Skip authentication (use existing credentials)')
65
66
  .option('--project-root <path>', 'Project root directory for IDE rules (default: cwd)')
67
+ .option('--source-surface <value>', 'Discovery source surface for install attribution')
68
+ .option('--campaign <value>', 'Campaign label for install attribution')
69
+ .option('--query-cluster <value>', 'Query intent cluster (e.g. token_limit_context_overflow)')
70
+ .option('--host-agent <value>', 'Host agent name for install attribution (default: cutline-mcp-cli)')
66
71
  .option('--hide-audit-dimension <name>', 'Hide one audit dimension in surfaced code audit output (repeatable)', (value, prev) => [...prev, value], [])
67
72
  .option('--hide-audit-dimensions <csv>', 'Hide multiple audit dimensions (comma-separated: engineering,security,reliability,scalability,compliance)')
68
73
  .action((opts) => setupCommand({
@@ -71,11 +76,41 @@ program
71
76
  projectRoot: opts.projectRoot,
72
77
  hideAuditDimension: opts.hideAuditDimension,
73
78
  hideAuditDimensions: opts.hideAuditDimensions,
79
+ sourceSurface: opts.sourceSurface,
80
+ campaign: opts.campaign,
81
+ queryCluster: opts.queryCluster,
82
+ hostAgent: opts.hostAgent,
74
83
  }));
75
84
  program
76
85
  .command('init')
77
86
  .description('Generate IDE rules only (setup runs this automatically)')
78
87
  .option('--project-root <path>', 'Project root directory (default: cwd)')
79
88
  .option('--staging', 'Use staging environment')
80
- .action((opts) => initCommand({ projectRoot: opts.projectRoot, staging: opts.staging }));
89
+ .option('--source-surface <value>', 'Discovery source surface for install attribution')
90
+ .option('--campaign <value>', 'Campaign label for install attribution')
91
+ .option('--query-cluster <value>', 'Query intent cluster (e.g. token_limit_context_overflow)')
92
+ .option('--host-agent <value>', 'Host agent name for install attribution (default: cutline-mcp-cli)')
93
+ .action((opts) => initCommand({
94
+ projectRoot: opts.projectRoot,
95
+ staging: opts.staging,
96
+ sourceSurface: opts.sourceSurface,
97
+ campaign: opts.campaign,
98
+ queryCluster: opts.queryCluster,
99
+ hostAgent: opts.hostAgent,
100
+ }));
101
+ program
102
+ .command('policy-init')
103
+ .description('Generate repository cutline.json policy manifest for deterministic safety verification')
104
+ .option('--project-root <path>', 'Project root directory (default: cwd)')
105
+ .option('--force', 'Overwrite existing cutline.json if present')
106
+ .option('--min-security-score <number>', 'Minimum security score required to pass (default: 85)')
107
+ .option('--max-assurance-age-hours <number>', 'Maximum assurance artifact age in hours (default: 168)')
108
+ .option('--allow-unsigned-assurance', 'Do not require signed assurance artifact')
109
+ .action((opts) => policyInitCommand({
110
+ projectRoot: opts.projectRoot,
111
+ force: Boolean(opts.force),
112
+ minSecurityScore: opts.minSecurityScore,
113
+ maxAssuranceAgeHours: opts.maxAssuranceAgeHours,
114
+ allowUnsignedAssurance: Boolean(opts.allowUnsignedAssurance),
115
+ }));
81
116
  program.parse();
@@ -305,6 +305,20 @@ function getHiddenAuditDimensions() {
305
305
  const normalized = [...new Set(hidden.map((d) => String(d).trim().toLowerCase()).filter((d) => allowed.has(d)))];
306
306
  return normalized;
307
307
  }
308
+ function getStoredInstallId(options) {
309
+ const config = readLocalCutlineConfig();
310
+ if (!config)
311
+ return null;
312
+ const preferred = options?.environment === "staging" ? config.agentInstallIdStaging : config.agentInstallId;
313
+ if (typeof preferred === "string" && preferred.trim()) {
314
+ return preferred.trim();
315
+ }
316
+ const fallback = options?.environment === "staging" ? config.agentInstallId : config.agentInstallIdStaging;
317
+ if (typeof fallback === "string" && fallback.trim()) {
318
+ return fallback.trim();
319
+ }
320
+ return null;
321
+ }
308
322
  function getStoredApiKey(options) {
309
323
  const includeConfig = options?.includeConfig ?? true;
310
324
  if (process.env.CUTLINE_API_KEY) {
@@ -1010,6 +1024,7 @@ export {
1010
1024
  validateAuth,
1011
1025
  resolveAuthContext,
1012
1026
  getHiddenAuditDimensions,
1027
+ getStoredInstallId,
1013
1028
  requirePremiumWithAutoAuth,
1014
1029
  resolveAuthContextFree,
1015
1030
  getPublicSiteUrlForCurrentAuth,
@@ -52,6 +52,7 @@ import {
52
52
  getPremortem,
53
53
  getPublicSiteUrlForCurrentAuth,
54
54
  getScanRateLimit,
55
+ getStoredInstallId,
55
56
  getTemplate,
56
57
  getTestCasesForEntity,
57
58
  hasConstraints,
@@ -75,7 +76,7 @@ import {
75
76
  upsertEntities,
76
77
  upsertNodes,
77
78
  validateRequestSize
78
- } from "./chunk-X2B5QUWO.js";
79
+ } from "./chunk-RUCYK3TR.js";
79
80
  import {
80
81
  GraphTraverser,
81
82
  computeGenericGraphMetrics,
@@ -4455,17 +4456,6 @@ var UNIVERSAL_CONSTRAINTS = [
4455
4456
  file_patterns: ["**/auth/**", "**/api/session*", "**/api/login*", "**/middleware/**", "**/config/**"],
4456
4457
  framework: "baseline"
4457
4458
  },
4458
- {
4459
- id_suffix: "password_reset_token_expiry",
4460
- category: "security",
4461
- summary: "Password reset tokens/links MUST be single-use and time-limited. Expired or reused reset tokens must fail closed.",
4462
- keywords: ["password-reset", "token", "expiry", "single-use", "account-takeover"],
4463
- severity: "critical",
4464
- action: "Enforce reset token TTL and one-time use semantics. Invalidate outstanding reset tokens after successful password change.",
4465
- checklist_ref: "A10",
4466
- file_patterns: ["**/auth/**", "**/api/reset*", "**/api/forgot*", "**/api/password*"],
4467
- framework: "baseline"
4468
- },
4469
4459
  {
4470
4460
  id_suffix: "backup_testing",
4471
4461
  category: "stability",
@@ -4711,83 +4701,6 @@ var RELIABILITY_CONSTRAINTS = [
4711
4701
  checklist_ref: "J10",
4712
4702
  file_patterns: ["**/utils/**", "**/lib/**", "**/services/**", "**/api/**"],
4713
4703
  framework: "baseline"
4714
- },
4715
- {
4716
- id_suffix: "startup_env_schema_validation",
4717
- category: "stability",
4718
- summary: "Runtime environment variables MUST be validated against an explicit schema at startup, and app boot must fail fast on invalid critical config.",
4719
- keywords: ["env", "startup", "schema", "validation", "fail-fast", "configuration"],
4720
- severity: "critical",
4721
- action: "Create startup env schema checks for server and public runtime variables. Crash startup when required production config is missing or malformed.",
4722
- checklist_ref: "J11",
4723
- file_patterns: ["**/config/**", "**/env/**", "**/server/**", "**/.env*"],
4724
- framework: "baseline"
4725
- },
4726
- {
4727
- id_suffix: "ui_error_boundaries",
4728
- category: "stability",
4729
- summary: "Critical user-facing UI surfaces MUST be wrapped in error boundaries to prevent full-app white screens during component crashes.",
4730
- keywords: ["error-boundary", "react", "ui", "crash", "fallback", "reliability"],
4731
- severity: "warning",
4732
- action: "Add error boundaries around major routes/layouts and high-risk widgets. Provide fallback UI and telemetry when boundaries catch errors.",
4733
- checklist_ref: "J12",
4734
- file_patterns: ["**/components/**", "**/pages/**", "**/app/**", "**/*error*"],
4735
- framework: "baseline"
4736
- },
4737
- {
4738
- id_suffix: "health_readiness_endpoints",
4739
- category: "stability",
4740
- summary: "Services MUST expose dedicated liveness and readiness endpoints (e.g., /api/health and /api/readyz) for monitoring and deployment safety checks.",
4741
- keywords: ["health", "readyz", "liveness", "readiness", "monitoring", "probe"],
4742
- severity: "critical",
4743
- action: "Implement lightweight health/readiness endpoints with no sensitive payload data. Integrate endpoints into uptime monitoring and deployment probes.",
4744
- checklist_ref: "J13",
4745
- file_patterns: ["**/api/health*", "**/api/ready*", "**/monitoring/**", "**/deploy/**"],
4746
- framework: "baseline"
4747
- },
4748
- {
4749
- id_suffix: "structured_production_logging",
4750
- category: "stability",
4751
- summary: "Production logging MUST be structured and include correlation/request IDs, with automatic redaction of tokens, API keys, and credentials.",
4752
- keywords: ["logging", "structured", "correlation-id", "request-id", "redaction", "observability"],
4753
- severity: "critical",
4754
- action: "Emit JSON logs in production and propagate request/correlation IDs across handlers and background jobs. Apply secret-redaction middleware before log emission.",
4755
- checklist_ref: "J14",
4756
- file_patterns: ["**/logger/**", "**/api/**", "**/middleware/**", "**/monitoring/**"],
4757
- framework: "baseline"
4758
- },
4759
- {
4760
- id_suffix: "typed_ai_generated_code",
4761
- category: "stability",
4762
- summary: "AI-generated production code MUST use TypeScript (or equivalent static typing) and pass strict type-check gates before merge.",
4763
- keywords: ["ai-generated", "typescript", "typing", "typecheck", "ci-gate", "quality"],
4764
- severity: "warning",
4765
- action: "Require strict type-check in CI for generated code changes and block merges on type errors. Prefer typed templates for agent-generated modules.",
4766
- checklist_ref: "J15",
4767
- file_patterns: ["**/*.ts", "**/*.tsx", "**/ai/**", "**/agents/**", "**/.github/**"],
4768
- framework: "baseline"
4769
- },
4770
- {
4771
- id_suffix: "async_email_dispatch",
4772
- category: "performance",
4773
- summary: "Transactional emails SHOULD be dispatched asynchronously (queue/background workers) so request handlers do not block on provider latency.",
4774
- keywords: ["email", "async", "queue", "worker", "latency", "smtp", "request-path"],
4775
- severity: "warning",
4776
- action: "Move email delivery to async jobs/queues and return request responses before provider completion. Add retry/backoff for transient send failures.",
4777
- checklist_ref: "J16",
4778
- file_patterns: ["**/api/**", "**/jobs/**", "**/workers/**", "**/email/**", "**/notifications/**"],
4779
- framework: "baseline"
4780
- },
4781
- {
4782
- id_suffix: "cdn_media_delivery",
4783
- category: "performance",
4784
- summary: "User-uploaded media MUST be stored in object storage and delivered through CDN caching, not served directly from app servers.",
4785
- keywords: ["cdn", "media", "uploads", "object-storage", "cache", "bandwidth"],
4786
- severity: "warning",
4787
- action: "Store uploads in object storage (S3/GCS/etc.) and serve via CDN URLs with cache headers. Keep app servers out of large media delivery paths.",
4788
- checklist_ref: "J17",
4789
- file_patterns: ["**/api/upload*", "**/storage/**", "**/media/**", "**/cdn/**", "**/config/**"],
4790
- framework: "baseline"
4791
4704
  }
4792
4705
  ];
4793
4706
  var IAC_CONSTRAINTS = [
@@ -6595,6 +6508,11 @@ async function handleCodeAudit(args, deps) {
6595
6508
  },
6596
6509
  sensitiveDataCount: scanResult.sensitive_data.fields.length,
6597
6510
  rgrPlan,
6511
+ rgrAutoTrigger: {
6512
+ enabled: true,
6513
+ onScopeIncrease: true,
6514
+ executionMode: "local_vitest"
6515
+ },
6598
6516
  securityGaps: graphAnalysis.securityGaps
6599
6517
  }
6600
6518
  };
@@ -7486,6 +7404,152 @@ async function withLlmMonitor(model, fn) {
7486
7404
  }
7487
7405
  }
7488
7406
 
7407
+ // ../mcp/dist/mcp/src/shared/repo-policy.js
7408
+ function buildRepoPolicyRequirements(manifest) {
7409
+ return {
7410
+ require_security_scan: Boolean(manifest?.verification_requirements?.require_security_scan ?? true),
7411
+ fail_on_critical: Boolean(manifest?.verification_requirements?.fail_on_critical ?? true),
7412
+ min_security_score: Number(manifest?.verification_requirements?.min_security_score ?? 85),
7413
+ require_assurance_manifest: Boolean(manifest?.verification_requirements?.require_assurance_manifest ?? true),
7414
+ require_signed_assurance: Boolean(manifest?.verification_requirements?.require_signed_assurance ?? true),
7415
+ max_assurance_age_hours: Number(manifest?.verification_requirements?.max_assurance_age_hours ?? 168)
7416
+ };
7417
+ }
7418
+ function buildRepoPolicyObserved(observed) {
7419
+ return {
7420
+ security_score: Number(observed?.security_score ?? Number.NaN),
7421
+ critical_findings_count: Number(observed?.critical_findings_count ?? Number.NaN),
7422
+ assurance_available: observed?.assurance_available,
7423
+ assurance_signed: observed?.assurance_signed,
7424
+ assurance_age_hours: Number(observed?.assurance_age_hours ?? Number.NaN)
7425
+ };
7426
+ }
7427
+ function evaluateRepoPolicy(requirements, observed) {
7428
+ const checks = [];
7429
+ const blockingReasons = [];
7430
+ const requiredActions = [];
7431
+ const evaluate = (id, pass, passMessage, failMessage, unknownMessage) => {
7432
+ if (pass === null) {
7433
+ checks.push({ id, status: "unknown", message: unknownMessage });
7434
+ return;
7435
+ }
7436
+ if (pass) {
7437
+ checks.push({ id, status: "pass", message: passMessage });
7438
+ } else {
7439
+ checks.push({ id, status: "fail", message: failMessage });
7440
+ blockingReasons.push(failMessage);
7441
+ }
7442
+ };
7443
+ if (requirements.require_security_scan) {
7444
+ const hasScore = Number.isFinite(observed.security_score);
7445
+ evaluate("security_score_minimum", hasScore ? observed.security_score >= requirements.min_security_score : null, `Security score ${observed.security_score} meets minimum ${requirements.min_security_score}.`, `Security score ${hasScore ? observed.security_score : "unknown"} below minimum ${requirements.min_security_score}.`, "Security score not provided in observed evidence.");
7446
+ if (!hasScore) {
7447
+ requiredActions.push("Provide observed.security_score from the latest audit.");
7448
+ }
7449
+ }
7450
+ if (requirements.fail_on_critical) {
7451
+ const hasCritical = Number.isFinite(observed.critical_findings_count);
7452
+ evaluate("critical_findings_zero", hasCritical ? observed.critical_findings_count <= 0 : null, "No unresolved critical/high findings.", `${hasCritical ? observed.critical_findings_count : "Unknown"} unresolved critical/high findings detected.`, "Critical findings count not provided in observed evidence.");
7453
+ if (!hasCritical) {
7454
+ requiredActions.push("Provide observed.critical_findings_count from the latest audit.");
7455
+ }
7456
+ }
7457
+ if (requirements.require_assurance_manifest) {
7458
+ const available = typeof observed.assurance_available === "boolean" ? observed.assurance_available : null;
7459
+ evaluate("assurance_available", available, "Assurance manifest is available.", "Assurance manifest is required but unavailable.", "Assurance availability not provided in observed evidence.");
7460
+ if (available === null) {
7461
+ requiredActions.push("Provide observed.assurance_available from assurance retrieval.");
7462
+ }
7463
+ }
7464
+ if (requirements.require_signed_assurance) {
7465
+ const signed = typeof observed.assurance_signed === "boolean" ? observed.assurance_signed : null;
7466
+ evaluate("assurance_signed", signed, "Assurance manifest signature is present/valid.", "Policy requires signed assurance artifact.", "Assurance signature status not provided in observed evidence.");
7467
+ if (signed === null) {
7468
+ requiredActions.push("Provide observed.assurance_signed after verification.");
7469
+ }
7470
+ }
7471
+ if (requirements.max_assurance_age_hours > 0) {
7472
+ const hasAge = Number.isFinite(observed.assurance_age_hours);
7473
+ evaluate("assurance_freshness", hasAge ? observed.assurance_age_hours <= requirements.max_assurance_age_hours : null, `Assurance age ${observed.assurance_age_hours}h within ${requirements.max_assurance_age_hours}h threshold.`, `Assurance age ${hasAge ? observed.assurance_age_hours : "unknown"}h exceeds ${requirements.max_assurance_age_hours}h threshold.`, "Assurance age not provided in observed evidence.");
7474
+ if (!hasAge) {
7475
+ requiredActions.push("Provide observed.assurance_age_hours.");
7476
+ }
7477
+ }
7478
+ const failedChecks = checks.filter((c) => c.status === "fail").length;
7479
+ const unknownChecks = checks.filter((c) => c.status === "unknown").length;
7480
+ const status = failedChecks > 0 ? "blocked" : unknownChecks > 0 ? "insufficient_evidence" : "verified";
7481
+ if (status !== "verified" && requiredActions.length === 0) {
7482
+ requiredActions.push("Re-run validate_repo_policy with complete observed evidence fields.");
7483
+ }
7484
+ return {
7485
+ status,
7486
+ checks,
7487
+ blocking_reasons: blockingReasons,
7488
+ required_actions: [...new Set(requiredActions)],
7489
+ verification_requirements: requirements
7490
+ };
7491
+ }
7492
+
7493
+ // ../mcp/dist/mcp/src/shared/discovery-intent.js
7494
+ var TESTING_INTENT_REGEX = /\b(test|tests|testing|vitest|jest|coverage|unit test|integration test|e2e|spec file|assertion)\b/i;
7495
+ var TOKEN_INTENT_PATTERNS = [
7496
+ { regex: /\b(rate limit|request limit|429|quota exceeded)\b/i, cluster: "rate_limit" },
7497
+ {
7498
+ regex: /\b(prompt (is )?too long|context window|context overflow|too many tokens|token limit)\b/i,
7499
+ cluster: "context_overflow"
7500
+ },
7501
+ {
7502
+ regex: /\b(token burn|burning credits|too expensive|reduce tokens|save tokens|token usage)\b/i,
7503
+ cluster: "token_cost"
7504
+ }
7505
+ ];
7506
+ function isTestingIntentPrompt(prompt) {
7507
+ return TESTING_INTENT_REGEX.test(prompt);
7508
+ }
7509
+ function detectTokenLimitIntentPrompt(prompt) {
7510
+ for (const pattern of TOKEN_INTENT_PATTERNS) {
7511
+ const match = prompt.match(pattern.regex);
7512
+ if (match) {
7513
+ return {
7514
+ detected: true,
7515
+ cluster: pattern.cluster,
7516
+ matched_pattern: match[0]
7517
+ };
7518
+ }
7519
+ }
7520
+ return { detected: false };
7521
+ }
7522
+ function buildTestingIntentHintResponse(prompt) {
7523
+ return {
7524
+ detected: true,
7525
+ intent: "testing",
7526
+ route: "cutline_testing_rgr",
7527
+ prompts: [
7528
+ "use cutline to generate tests for this scope increase",
7529
+ "use cutline to run the RGR loop for this change",
7530
+ "use cutline to evaluate merge gates for this test run"
7531
+ ],
7532
+ bootstrap_if_missing: "npx -y @vibekiln/cutline-mcp-cli@latest setup",
7533
+ source_prompt_excerpt: prompt.slice(0, 180)
7534
+ };
7535
+ }
7536
+ function buildTokenLimitIntentHintResponse(prompt, match) {
7537
+ return {
7538
+ detected: true,
7539
+ intent: "token_limit",
7540
+ route: "cutline_token_layer_install",
7541
+ query_cluster: match.cluster || "context_overflow",
7542
+ matched_pattern: match.matched_pattern || null,
7543
+ prompts: [
7544
+ "use cutline to reduce context window pressure before tool calls",
7545
+ "use cutline to apply token-saving policy and retry this flow",
7546
+ "use cutline to install deterministic context guardrails for this repo"
7547
+ ],
7548
+ bootstrap_if_missing: "npx -y @vibekiln/cutline-mcp-cli@latest setup",
7549
+ source_prompt_excerpt: prompt.slice(0, 180)
7550
+ };
7551
+ }
7552
+
7489
7553
  // ../mcp/dist/mcp/src/cutline-server.js
7490
7554
  function mcpAudit(entry) {
7491
7555
  console.error(JSON.stringify({
@@ -7495,8 +7559,56 @@ function mcpAudit(entry) {
7495
7559
  ...entry
7496
7560
  }));
7497
7561
  }
7562
+ async function emitPolicyGateEvent(input) {
7563
+ if (!input.authToken || !input.installId)
7564
+ return;
7565
+ const siteUrl = (process.env.NEXT_PUBLIC_SITE_URL || "https://thecutline.ai").replace(/\/$/, "");
7566
+ const eventName = input.status === "verified" ? "policy_gate_passed" : "policy_gate_blocked";
7567
+ try {
7568
+ await fetch(`${siteUrl}/api/agent/event`, {
7569
+ method: "POST",
7570
+ headers: {
7571
+ "Content-Type": "application/json",
7572
+ Authorization: `Bearer ${input.authToken}`
7573
+ },
7574
+ body: JSON.stringify({
7575
+ install_id: input.installId,
7576
+ event_name: eventName,
7577
+ event_properties: {
7578
+ status: input.status,
7579
+ policy_name: input.policyName || "cutline-policy",
7580
+ failed_checks_count: input.failedChecks,
7581
+ unknown_checks_count: input.unknownChecks,
7582
+ blocking_reasons_count: input.blockingReasonsCount
7583
+ }
7584
+ })
7585
+ });
7586
+ } catch {
7587
+ }
7588
+ }
7589
+ async function emitAgentEvent(input) {
7590
+ if (!input.authToken || !input.installId)
7591
+ return;
7592
+ const siteUrl = (process.env.NEXT_PUBLIC_SITE_URL || "https://thecutline.ai").replace(/\/$/, "");
7593
+ try {
7594
+ await fetch(`${siteUrl}/api/agent/event`, {
7595
+ method: "POST",
7596
+ headers: {
7597
+ "Content-Type": "application/json",
7598
+ Authorization: `Bearer ${input.authToken}`
7599
+ },
7600
+ body: JSON.stringify({
7601
+ install_id: input.installId,
7602
+ event_name: input.eventName,
7603
+ event_properties: input.eventProperties || {}
7604
+ })
7605
+ });
7606
+ } catch {
7607
+ }
7608
+ }
7498
7609
  var DEFAULT_MODEL = process.env.MODEL_ID || "gemini-2.5-pro";
7499
7610
  var GOVERNANCE_ENFORCEMENT = (process.env.CUTLINE_GOVERNANCE_ENFORCEMENT || "advisory").toLowerCase() === "enforced";
7611
+ var TOKEN_INTENT_HINT_ENABLED = (process.env.CUTLINE_TOKEN_INTENT_HINT_ENABLED || "false").toLowerCase() === "true";
7500
7612
  function buildGovernanceEnvelope(input) {
7501
7613
  return {
7502
7614
  decision: input.decision,
@@ -7523,21 +7635,26 @@ var ACT_NAMES = {
7523
7635
  };
7524
7636
  function assessScopeExpansionIntent(params) {
7525
7637
  const task = (params.task_description || "").trim();
7638
+ const codeSnippet = (params.code_snippet || "").trim();
7639
+ const intentText = `${task}
7640
+ ${codeSnippet}`.trim();
7526
7641
  const filePaths = params.file_paths || [];
7527
7642
  const reasons = [];
7528
7643
  let confidence = 0;
7529
7644
  const explicitScopePatterns = [
7530
7645
  /\b(scope increase|expand(?:ing)? scope|broaden scope|new scope)\b/i,
7531
7646
  /\b(seed|ingest|add)\b.{0,24}\b(graph|constraint|entity|entities)\b/i,
7532
- /\b(new feature|new module|new domain|new subsystem)\b/i
7647
+ /\b(new feature|new module|new domain|new subsystem)\b/i,
7648
+ /\b(expand|increase|broaden)\b.{0,24}\b(coverage|surface area|scope)\b/i,
7649
+ /\b(add|introduce|build|create)\b.{0,24}\b(endpoint|route|api|service|workflow)\b/i
7533
7650
  ];
7534
- const hasExplicitScopeIntent = explicitScopePatterns.some((rx) => rx.test(task));
7651
+ const hasExplicitScopeIntent = explicitScopePatterns.some((rx) => rx.test(intentText));
7535
7652
  if (hasExplicitScopeIntent) {
7536
7653
  confidence += 0.55;
7537
7654
  reasons.push("Task description includes explicit scope-expansion language.");
7538
7655
  }
7539
7656
  const hintedName = params.hinted_entity_name?.trim();
7540
- const inferredName = hintedName || inferEntityNameFromTask(task);
7657
+ const inferredName = hintedName || inferEntityNameFromTask(intentText);
7541
7658
  if (inferredName) {
7542
7659
  confidence += 0.12;
7543
7660
  reasons.push("Potential new entity name detected from task context.");
@@ -7997,7 +8114,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
7997
8114
  type: "object",
7998
8115
  properties: {
7999
8116
  prompt: { type: "string" },
8000
- wikiMarkdown: { type: "string" }
8117
+ wikiMarkdown: { type: "string" },
8118
+ auth_token: { type: "string", description: "Optional auth token for telemetry attribution" },
8119
+ install_id: { type: "string", description: "Optional install ID for telemetry attribution" }
8001
8120
  },
8002
8121
  required: ["prompt"]
8003
8122
  }
@@ -8026,7 +8145,9 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
8026
8145
  inputSchema: {
8027
8146
  type: "object",
8028
8147
  properties: {
8029
- prompt: { type: "string" }
8148
+ prompt: { type: "string" },
8149
+ auth_token: { type: "string", description: "Optional auth token for telemetry attribution" },
8150
+ install_id: { type: "string", description: "Optional install ID for telemetry attribution" }
8030
8151
  },
8031
8152
  required: ["prompt"]
8032
8153
  }
@@ -8460,6 +8581,40 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
8460
8581
  required: ["product_id"]
8461
8582
  }
8462
8583
  },
8584
+ {
8585
+ name: "get_assurance_manifest",
8586
+ description: `\u{1F513} AUTHENTICATED-FREE - Fetch signed assurance proof for "prove it's safe", "production-ready", and audit verification prompts.`,
8587
+ inputSchema: {
8588
+ type: "object",
8589
+ properties: {
8590
+ url: { type: "string", description: "Optional assurance URL override (default: NEXT_PUBLIC_SITE_URL/.well-known/cutline-assurance.json). Use target app domain when verifying deployed builds." }
8591
+ }
8592
+ }
8593
+ },
8594
+ {
8595
+ name: "validate_repo_policy",
8596
+ description: "\u{1F513} AUTHENTICATED-FREE - Run deterministic policy validation for secure/deploy-ready/audit prompts and return a machine-readable verdict object.",
8597
+ inputSchema: {
8598
+ type: "object",
8599
+ properties: {
8600
+ project_root: { type: "string", description: "Absolute workspace root containing cutline.json" },
8601
+ manifest_path: { type: "string", description: "Optional explicit path to cutline.json (overrides project_root)" },
8602
+ install_id: { type: "string", description: "Optional agent install_id for funnel attribution when emitting policy gate events (auto-resolved from local ~/.cutline-mcp/config.json when omitted)" },
8603
+ observed: {
8604
+ type: "object",
8605
+ description: "Observed evidence from scans/assurance checks to evaluate against policy thresholds",
8606
+ properties: {
8607
+ security_score: { type: "number", description: "Observed security score (0-100)" },
8608
+ critical_findings_count: { type: "number", description: "Observed unresolved critical/high findings count" },
8609
+ assurance_available: { type: "boolean", description: "Whether assurance artifact is available" },
8610
+ assurance_signed: { type: "boolean", description: "Whether assurance artifact signature is valid/present" },
8611
+ assurance_age_hours: { type: "number", description: "Age of assurance evidence in hours" }
8612
+ }
8613
+ }
8614
+ },
8615
+ required: ["project_root"]
8616
+ }
8617
+ },
8463
8618
  {
8464
8619
  name: "code_audit",
8465
8620
  description: "\u{1F513} FREE - Security vibe check (code audit). Evaluates your codebase against a stack-aware constraint graph covering security, reliability, and scalability. No deep dive or product_id required \u2014 just point at your codebase. Shows aggregate readiness scores and top critical findings; detailed analysis and remediation require Premium. Requires a Cutline account (free). 3 scans/month.",
@@ -8769,9 +8924,159 @@ Why AI: ${idea.whyAI}`
8769
8924
  };
8770
8925
  }
8771
8926
  if (name2 === "trial_generate") {
8772
- const { prompt } = args;
8927
+ const trialArgs = args;
8928
+ const { prompt } = trialArgs;
8773
8929
  const text = await cfGenerateTrialRun(prompt);
8774
- return { content: [{ type: "text", text: JSON.stringify({ text }) }] };
8930
+ const isTestingIntent = isTestingIntentPrompt(prompt);
8931
+ const tokenIntent = TOKEN_INTENT_HINT_ENABLED ? detectTokenLimitIntentPrompt(prompt) : { detected: false };
8932
+ const env = process.env.CUTLINE_ENV === "staging" ? "staging" : "production";
8933
+ const resolvedInstallId = trialArgs.install_id || getStoredInstallId({ environment: env });
8934
+ if (isTestingIntent) {
8935
+ await emitAgentEvent({
8936
+ authToken: trialArgs.auth_token,
8937
+ installId: resolvedInstallId || void 0,
8938
+ eventName: "agent_test_intent_detected",
8939
+ eventProperties: {
8940
+ tool_name: "trial_generate",
8941
+ route: "cutline_testing_rgr"
8942
+ }
8943
+ });
8944
+ }
8945
+ if (tokenIntent.detected) {
8946
+ await emitAgentEvent({
8947
+ authToken: trialArgs.auth_token,
8948
+ installId: resolvedInstallId || void 0,
8949
+ eventName: "agent_token_limit_intent_detected",
8950
+ eventProperties: {
8951
+ tool_name: "trial_generate",
8952
+ route: "cutline_token_layer_install",
8953
+ query_cluster: tokenIntent.cluster
8954
+ }
8955
+ });
8956
+ await emitAgentEvent({
8957
+ authToken: trialArgs.auth_token,
8958
+ installId: resolvedInstallId || void 0,
8959
+ eventName: "agent_token_layer_install_prompted",
8960
+ eventProperties: {
8961
+ tool_name: "trial_generate",
8962
+ route: "cutline_token_layer_install",
8963
+ query_cluster: tokenIntent.cluster
8964
+ }
8965
+ });
8966
+ }
8967
+ return {
8968
+ content: [{
8969
+ type: "text",
8970
+ text: JSON.stringify({
8971
+ text,
8972
+ ...isTestingIntent ? { cutline_testing_route: buildTestingIntentHintResponse(prompt) } : {},
8973
+ ...tokenIntent.detected ? { cutline_token_route: buildTokenLimitIntentHintResponse(prompt, tokenIntent) } : {}
8974
+ })
8975
+ }]
8976
+ };
8977
+ }
8978
+ if (name2 === "get_assurance_manifest") {
8979
+ const { url } = args;
8980
+ await resolveAuthContextFree(args.auth_token);
8981
+ const siteUrl = (process.env.NEXT_PUBLIC_SITE_URL || "https://thecutline.ai").replace(/\/$/, "");
8982
+ const assuranceUrl = url || `${siteUrl}/.well-known/cutline-assurance.json`;
8983
+ const response = await fetch(assuranceUrl, {
8984
+ method: "GET",
8985
+ headers: { "Accept": "application/json" }
8986
+ });
8987
+ if (!response.ok) {
8988
+ throw new McpError(ErrorCode.InternalError, `Failed to fetch assurance manifest (${response.status}) from ${assuranceUrl}`);
8989
+ }
8990
+ const manifest = await response.json();
8991
+ return {
8992
+ content: [{
8993
+ type: "text",
8994
+ text: JSON.stringify({
8995
+ source_url: assuranceUrl,
8996
+ fetched_at: (/* @__PURE__ */ new Date()).toISOString(),
8997
+ manifest
8998
+ }, null, 2)
8999
+ }]
9000
+ };
9001
+ }
9002
+ if (name2 === "validate_repo_policy") {
9003
+ const policyArgs = args;
9004
+ if (!policyArgs.project_root) {
9005
+ throw new McpError(ErrorCode.InvalidParams, "project_root is required");
9006
+ }
9007
+ await resolveAuthContextFree(policyArgs.auth_token);
9008
+ const env = process.env.CUTLINE_ENV === "staging" ? "staging" : "production";
9009
+ const resolvedInstallId = policyArgs.install_id || getStoredInstallId({ environment: env });
9010
+ const telemetryAttribution = policyArgs.install_id ? "provided" : resolvedInstallId ? "auto_resolved" : "missing";
9011
+ const { existsSync, readFileSync } = await import("node:fs");
9012
+ const { resolve, join: join4 } = await import("node:path");
9013
+ const manifestPath = resolve(policyArgs.manifest_path || join4(policyArgs.project_root, "cutline.json"));
9014
+ if (!existsSync(manifestPath)) {
9015
+ await emitPolicyGateEvent({
9016
+ authToken: policyArgs.auth_token,
9017
+ installId: resolvedInstallId || void 0,
9018
+ status: "invalid_policy",
9019
+ policyName: "cutline-policy",
9020
+ failedChecks: 1,
9021
+ unknownChecks: 0,
9022
+ blockingReasonsCount: 1
9023
+ });
9024
+ return {
9025
+ content: [{
9026
+ type: "text",
9027
+ text: JSON.stringify({
9028
+ status: "invalid_policy",
9029
+ certification_id: `policy_${Date.now()}`,
9030
+ blocking_reasons: [`Policy manifest not found at ${manifestPath}`],
9031
+ required_actions: [
9032
+ "Create policy manifest: cutline-mcp policy-init",
9033
+ "Commit cutline.json and re-run validate_repo_policy"
9034
+ ],
9035
+ telemetry_attribution: telemetryAttribution,
9036
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
9037
+ }, null, 2)
9038
+ }]
9039
+ };
9040
+ }
9041
+ let manifest;
9042
+ try {
9043
+ manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
9044
+ } catch (e) {
9045
+ throw new McpError(ErrorCode.InvalidParams, `Invalid cutline.json: ${e?.message || String(e)}`);
9046
+ }
9047
+ const requirements = buildRepoPolicyRequirements(manifest);
9048
+ const observed = buildRepoPolicyObserved(policyArgs.observed);
9049
+ const verdict = evaluateRepoPolicy(requirements, observed);
9050
+ const failedChecks = verdict.checks.filter((c) => c.status === "fail").length;
9051
+ const unknownChecks = verdict.checks.filter((c) => c.status === "unknown").length;
9052
+ await emitPolicyGateEvent({
9053
+ authToken: policyArgs.auth_token,
9054
+ installId: resolvedInstallId || void 0,
9055
+ status: verdict.status,
9056
+ policyName: manifest?.policy_name || "cutline-policy",
9057
+ failedChecks,
9058
+ unknownChecks,
9059
+ blockingReasonsCount: verdict.blocking_reasons.length
9060
+ });
9061
+ return {
9062
+ content: [{
9063
+ type: "text",
9064
+ text: JSON.stringify({
9065
+ status: verdict.status,
9066
+ certification_id: `policy_${Date.now()}`,
9067
+ manifest_path: manifestPath,
9068
+ policy_name: manifest?.policy_name || "cutline-policy",
9069
+ schema_version: manifest?.schema_version || "unknown",
9070
+ verification_requirements: verdict.verification_requirements,
9071
+ observed_evidence: policyArgs.observed || {},
9072
+ telemetry_attribution: telemetryAttribution,
9073
+ checks: verdict.checks,
9074
+ blocking_reasons: verdict.blocking_reasons,
9075
+ required_actions: verdict.required_actions,
9076
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
9077
+ }, null, 2)
9078
+ }]
9079
+ };
8775
9080
  }
8776
9081
  if (name2 === "code_audit") {
8777
9082
  const scanArgs = args;
@@ -9072,9 +9377,56 @@ Competitive threats: ${competitors}` : ""
9072
9377
  return { content: [{ type: "text", text: JSON.stringify(result) }] };
9073
9378
  }
9074
9379
  case "agent_chat": {
9075
- const { prompt, wikiMarkdown } = args;
9380
+ const chatArgs = args;
9381
+ const { prompt, wikiMarkdown } = chatArgs;
9076
9382
  const text = await cfGenerateChatSuggestion(prompt, wikiMarkdown);
9077
- return { content: [{ type: "text", text: JSON.stringify({ text }) }] };
9383
+ const isTestingIntent = isTestingIntentPrompt(prompt);
9384
+ const tokenIntent = TOKEN_INTENT_HINT_ENABLED ? detectTokenLimitIntentPrompt(prompt) : { detected: false };
9385
+ const env = process.env.CUTLINE_ENV === "staging" ? "staging" : "production";
9386
+ const resolvedInstallId = chatArgs.install_id || getStoredInstallId({ environment: env });
9387
+ if (isTestingIntent) {
9388
+ await emitAgentEvent({
9389
+ authToken: chatArgs.auth_token,
9390
+ installId: resolvedInstallId || void 0,
9391
+ eventName: "agent_test_intent_detected",
9392
+ eventProperties: {
9393
+ tool_name: "agent_chat",
9394
+ route: "cutline_testing_rgr"
9395
+ }
9396
+ });
9397
+ }
9398
+ if (tokenIntent.detected) {
9399
+ await emitAgentEvent({
9400
+ authToken: chatArgs.auth_token,
9401
+ installId: resolvedInstallId || void 0,
9402
+ eventName: "agent_token_limit_intent_detected",
9403
+ eventProperties: {
9404
+ tool_name: "agent_chat",
9405
+ route: "cutline_token_layer_install",
9406
+ query_cluster: tokenIntent.cluster
9407
+ }
9408
+ });
9409
+ await emitAgentEvent({
9410
+ authToken: chatArgs.auth_token,
9411
+ installId: resolvedInstallId || void 0,
9412
+ eventName: "agent_token_layer_install_prompted",
9413
+ eventProperties: {
9414
+ tool_name: "agent_chat",
9415
+ route: "cutline_token_layer_install",
9416
+ query_cluster: tokenIntent.cluster
9417
+ }
9418
+ });
9419
+ }
9420
+ return {
9421
+ content: [{
9422
+ type: "text",
9423
+ text: JSON.stringify({
9424
+ text,
9425
+ ...isTestingIntent ? { cutline_testing_route: buildTestingIntentHintResponse(prompt) } : {},
9426
+ ...tokenIntent.detected ? { cutline_token_route: buildTokenLimitIntentHintResponse(prompt, tokenIntent) } : {}
9427
+ })
9428
+ }]
9429
+ };
9078
9430
  }
9079
9431
  // Integrations
9080
9432
  case "integrations_create_issues": {
@@ -9432,7 +9784,7 @@ Meta: ${JSON.stringify(output.meta)}` }
9432
9784
  }
9433
9785
  const analysis = analyzeFileContext(fileContext);
9434
9786
  let knownEntityNames = [];
9435
- if (task_description || scope_entity_name) {
9787
+ if (task_description || code_snippet || scope_entity_name) {
9436
9788
  try {
9437
9789
  const entities = await getAllEntities(product_id);
9438
9790
  knownEntityNames = entities.map((e) => e.name);
@@ -9441,6 +9793,7 @@ Meta: ${JSON.stringify(output.meta)}` }
9441
9793
  }
9442
9794
  const scopeExpansion = assessScopeExpansionIntent({
9443
9795
  task_description,
9796
+ code_snippet,
9444
9797
  file_paths,
9445
9798
  known_entity_names: knownEntityNames,
9446
9799
  hinted_entity_name: scope_entity_name
@@ -9569,9 +9922,8 @@ Meta: ${JSON.stringify(output.meta)}` }
9569
9922
  } catch (e) {
9570
9923
  }
9571
9924
  }
9572
- let autoRgrPlan = void 0;
9925
+ const autoRgrPlan = planRgrPhases(finalResults);
9573
9926
  if (autoPhase === "auto") {
9574
- autoRgrPlan = planRgrPhases(finalResults);
9575
9927
  if (autoRgrPlan.strategy === "phased") {
9576
9928
  finalResults = finalResults.filter((c) => {
9577
9929
  const phased = filterByPhase([c], "test_spec");
@@ -10643,6 +10995,11 @@ ${JSON.stringify(metrics, null, 2)}` }
10643
10995
  ...plan,
10644
10996
  entity: rgrMatched[0].name,
10645
10997
  complexity,
10998
+ auto_execution: {
10999
+ scope_increase_triggers_rgr: true,
11000
+ mode: "pervasive",
11001
+ expected_runner: "local_vitest"
11002
+ },
10646
11003
  governance
10647
11004
  }, null, 2)
10648
11005
  }]
@@ -11169,7 +11526,7 @@ Meta: ${JSON.stringify({
11169
11526
  mode: "product",
11170
11527
  codeContext: payload.codeContext || null
11171
11528
  });
11172
- runInput.productId = newJobId;
11529
+ runInput.productId = String(auditArgs.product_id || newJobId);
11173
11530
  await updatePremortem(newJobId, { payload: runInput });
11174
11531
  return { jobId: newJobId };
11175
11532
  }
@@ -78,7 +78,7 @@ import {
78
78
  upsertEdges,
79
79
  upsertEntities,
80
80
  upsertNodes
81
- } from "./chunk-X2B5QUWO.js";
81
+ } from "./chunk-RUCYK3TR.js";
82
82
  export {
83
83
  addEdges,
84
84
  addEntity,
@@ -14,7 +14,7 @@ import {
14
14
  requirePremiumWithAutoAuth,
15
15
  updateExplorationSession,
16
16
  validateRequestSize
17
- } from "./chunk-X2B5QUWO.js";
17
+ } from "./chunk-RUCYK3TR.js";
18
18
 
19
19
  // ../mcp/dist/mcp/src/exploration-server.js
20
20
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -13,7 +13,7 @@ import {
13
13
  requirePremiumWithAutoAuth,
14
14
  validateAuth,
15
15
  validateRequestSize
16
- } from "./chunk-X2B5QUWO.js";
16
+ } from "./chunk-RUCYK3TR.js";
17
17
 
18
18
  // ../mcp/dist/mcp/src/integrations-server.js
19
19
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -13,7 +13,7 @@ import {
13
13
  mapErrorToMcp,
14
14
  requirePremiumWithAutoAuth,
15
15
  validateRequestSize
16
- } from "./chunk-X2B5QUWO.js";
16
+ } from "./chunk-RUCYK3TR.js";
17
17
 
18
18
  // ../mcp/dist/mcp/src/output-server.js
19
19
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -27,7 +27,7 @@ import {
27
27
  updatePremortem,
28
28
  validateAuth,
29
29
  validateRequestSize
30
- } from "./chunk-X2B5QUWO.js";
30
+ } from "./chunk-RUCYK3TR.js";
31
31
 
32
32
  // ../mcp/dist/mcp/src/premortem-server.js
33
33
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -21,7 +21,7 @@ import {
21
21
  requirePremiumWithAutoAuth,
22
22
  validateAuth,
23
23
  validateRequestSize
24
- } from "./chunk-X2B5QUWO.js";
24
+ } from "./chunk-RUCYK3TR.js";
25
25
 
26
26
  // ../mcp/dist/mcp/src/tools-server.js
27
27
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -0,0 +1,19 @@
1
+ type AgentEventName = 'install_completed' | 'first_tool_call_success' | 'tool_call_failed' | 'heartbeat' | 'policy_gate_passed' | 'policy_gate_blocked' | 'upgrade_clicked' | 'upgrade_completed' | 'agent_test_intent_detected' | 'agent_cutline_install_prompted' | 'agent_cutline_install_completed' | 'agent_first_rgr_test_call_success' | 'agent_token_limit_intent_detected' | 'agent_token_layer_install_prompted' | 'agent_token_layer_install_completed';
2
+ export declare function registerAgentInstall(input: {
3
+ idToken: string;
4
+ staging?: boolean;
5
+ projectRoot: string;
6
+ sourceSurface: string;
7
+ hostAgent?: string;
8
+ campaign?: string;
9
+ referrerUrl?: string;
10
+ metadata?: Record<string, unknown>;
11
+ }): Promise<string | null>;
12
+ export declare function trackAgentEvent(input: {
13
+ idToken: string;
14
+ installId: string;
15
+ eventName: AgentEventName;
16
+ eventProperties?: Record<string, unknown>;
17
+ staging?: boolean;
18
+ }): Promise<void>;
19
+ export {};
@@ -0,0 +1,67 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { getConfig } from './config.js';
3
+ import { loadConfig, saveConfig } from './config-store.js';
4
+ function installIdKey(staging) {
5
+ return staging ? 'agentInstallIdStaging' : 'agentInstallId';
6
+ }
7
+ export async function registerAgentInstall(input) {
8
+ const key = installIdKey(input.staging);
9
+ const existing = loadConfig();
10
+ const persistedInstallId = typeof existing[key] === 'string' ? existing[key] : null;
11
+ if (persistedInstallId)
12
+ return persistedInstallId;
13
+ const { BASE_URL } = getConfig({ staging: input.staging });
14
+ const installationKey = createHash('sha256')
15
+ .update(`${input.projectRoot}:${input.staging ? 'staging' : 'production'}`)
16
+ .digest('hex')
17
+ .slice(0, 32);
18
+ const workspaceId = createHash('sha256').update(input.projectRoot).digest('hex').slice(0, 24);
19
+ try {
20
+ const response = await fetch(`${BASE_URL}/api/agent/register`, {
21
+ method: 'POST',
22
+ headers: {
23
+ 'Content-Type': 'application/json',
24
+ Authorization: `Bearer ${input.idToken}`,
25
+ },
26
+ body: JSON.stringify({
27
+ installation_key: installationKey,
28
+ source_surface: input.sourceSurface,
29
+ host_agent: input.hostAgent || 'cutline-mcp-cli',
30
+ workspace_id: workspaceId,
31
+ ...(input.campaign ? { campaign: input.campaign } : {}),
32
+ ...(input.referrerUrl ? { referrer_url: input.referrerUrl } : {}),
33
+ ...(input.metadata ? { metadata: input.metadata } : {}),
34
+ }),
35
+ });
36
+ if (!response.ok)
37
+ return null;
38
+ const payload = await response.json();
39
+ if (!payload.install_id)
40
+ return null;
41
+ saveConfig({ [key]: payload.install_id });
42
+ return payload.install_id;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ export async function trackAgentEvent(input) {
49
+ const { BASE_URL } = getConfig({ staging: input.staging });
50
+ try {
51
+ await fetch(`${BASE_URL}/api/agent/event`, {
52
+ method: 'POST',
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ Authorization: `Bearer ${input.idToken}`,
56
+ },
57
+ body: JSON.stringify({
58
+ install_id: input.installId,
59
+ event_name: input.eventName,
60
+ event_properties: input.eventProperties || {},
61
+ }),
62
+ });
63
+ }
64
+ catch {
65
+ // Best effort telemetry; never block CLI command success.
66
+ }
67
+ }
@@ -2,6 +2,8 @@ export interface McpConfig {
2
2
  refreshToken?: string;
3
3
  environment?: 'production' | 'staging';
4
4
  apiKey?: string;
5
+ agentInstallId?: string;
6
+ agentInstallIdStaging?: string;
5
7
  }
6
8
  export declare function saveConfig(config: McpConfig): void;
7
9
  export declare function loadConfig(): McpConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibekiln/cutline-mcp-cli",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
4
4
  "description": "CLI and MCP servers for Cutline — authenticate, then run constraint-aware MCP servers in Cursor or any MCP client.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",