ft-scout 9.5.7 → 9.5.9

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
@@ -1,4 +1,4 @@
1
- # scout (FrontTerrain CLI v9.5.7)
1
+ # scout (FrontTerrain CLI v9.5.9)
2
2
 
3
3
  **FrontTerrain (`scout`)** The Autonomous AI Principal Software Engineer & Codebase Co-Pilot in your terminal.
4
4
 
@@ -1,7 +1,7 @@
1
1
  export interface BenchmarkTarget {
2
2
  id: string;
3
3
  label: string;
4
- provider: 'NVIDIA' | 'Google' | 'OpenAI' | 'BYOK';
4
+ provider: 'FrontTerrain' | 'NVIDIA' | 'Google' | 'OpenAI' | 'BYOK';
5
5
  apiKeyEnv: string;
6
6
  }
7
7
  export declare const BENCHMARK_MODELS: BenchmarkTarget[];
@@ -8,6 +8,8 @@ const FT_DIR = path.join(process.cwd(), '.ft', 'scout');
8
8
  const BENCHMARK_DIR = path.join(FT_DIR);
9
9
  const BENCHMARK_FILE = path.join(BENCHMARK_DIR, 'benchmark.json');
10
10
  export const BENCHMARK_MODELS = [
11
+ { id: 'frontterrain/harp-1.5b-coder', label: 'HARP 1.5B Coder (Aligned)', provider: 'FrontTerrain', apiKeyEnv: 'HARP_API_URL' },
12
+ { id: 'frontterrain/HARP-1B-Instruct', label: 'HARP 1B (Original TensorLib)', provider: 'FrontTerrain', apiKeyEnv: 'HARP_API_URL' },
11
13
  { id: 'nvidia/nemotron-3.5-bolt-e4b', label: 'Nemotron 3.5 Bolt (Primary)', provider: 'NVIDIA', apiKeyEnv: 'NVIDIA_API_KEY' },
12
14
  { id: 'nvidia/nemotron-3.5-lightning-30b-a3b', label: 'Nemotron 3.5 Lightning 30B', provider: 'NVIDIA', apiKeyEnv: 'NVIDIA_API_KEY' },
13
15
  { id: 'nvidia/nemotron-3-ultra-550b-a55b', label: 'Nemotron 3 Ultra 550B', provider: 'NVIDIA', apiKeyEnv: 'NVIDIA_API_KEY' },
@@ -16,7 +18,8 @@ export const BENCHMARK_MODELS = [
16
18
  ];
17
19
  async function measureModelPerformance(target) {
18
20
  const auth = loadAuthConfig();
19
- const hasKey = Boolean(process.env[target.apiKeyEnv] ||
21
+ const hasKey = Boolean(target.provider === 'FrontTerrain' ||
22
+ process.env[target.apiKeyEnv] ||
20
23
  process.env.NVCF_API_KEY ||
21
24
  (auth.byokEnabled && auth.customApiKey));
22
25
  if (!hasKey) {
@@ -0,0 +1,6 @@
1
+ export interface ReplayCommandOptions {
2
+ list?: boolean;
3
+ export?: boolean;
4
+ }
5
+ export declare function handleReplay(taskId?: string, options?: ReplayCommandOptions): Promise<void>;
6
+ //# sourceMappingURL=replay.d.ts.map
@@ -0,0 +1,64 @@
1
+ import chalk from 'chalk';
2
+ import { intro, outro, spinner } from '@clack/prompts';
3
+ import { defaultTaskReplayManager } from '../engine/production/index.js';
4
+ export async function handleReplay(taskId, options) {
5
+ intro(chalk.bold.cyan('šŸŽ¬ FrontTerrain Scout — Task Replay & Telemetry Engine'));
6
+ if (options?.list || !taskId) {
7
+ const traces = defaultTaskReplayManager.listDiskTraces();
8
+ if (traces.length === 0) {
9
+ console.log(chalk.yellow('\nā„¹ļø No recorded task traces found in .ft/traces/ or memory.'));
10
+ console.log(chalk.gray('Run any autonomous agent task (e.g. `scout agent "fix bug"`) to record a trace.\n'));
11
+ outro(chalk.cyan('Replay session complete.'));
12
+ return;
13
+ }
14
+ console.log(chalk.bold(`\nAvailable Task Traces (${traces.length}):`));
15
+ for (const id of traces) {
16
+ const trace = defaultTaskReplayManager.getTrace(id);
17
+ if (trace) {
18
+ const statusColor = trace.finalStatus === 'completed' ? chalk.green : chalk.red;
19
+ console.log(` • ${chalk.bold.cyan(id)}: "${trace.objective.slice(0, 45)}" ` +
20
+ `(${trace.steps.length} steps, ${statusColor(trace.finalStatus)}, ${(trace.totalDurationMs / 1000).toFixed(1)}s)`);
21
+ }
22
+ else {
23
+ console.log(` • ${chalk.bold.cyan(id)}`);
24
+ }
25
+ }
26
+ console.log(chalk.gray(`\nTo replay a trace: scout replay <taskId>`));
27
+ console.log(chalk.gray(`To export a trace JSON: scout replay <taskId> --export\n`));
28
+ outro(chalk.cyan('Replay trace index complete.'));
29
+ return;
30
+ }
31
+ const trace = defaultTaskReplayManager.getTrace(taskId);
32
+ if (!trace) {
33
+ console.error(chalk.red(`\nāŒ Trace not found for task ID: "${taskId}".`));
34
+ console.log(chalk.yellow(`Use \`scout replay --list\` to view available task traces.\n`));
35
+ process.exit(1);
36
+ }
37
+ if (options?.export) {
38
+ const json = defaultTaskReplayManager.exportTraceJson(taskId);
39
+ console.log(json);
40
+ return;
41
+ }
42
+ console.log(chalk.bold(`\nTask ID: ${chalk.cyan(trace.taskId)}`));
43
+ console.log(chalk.bold(`Objective: ${trace.objective}`));
44
+ console.log(chalk.bold(`Recorded: ${trace.startTime} (${trace.steps.length} steps, status: ${trace.finalStatus})\n`));
45
+ const s = spinner();
46
+ s.start(`Replaying ${trace.steps.length} steps deterministically...`);
47
+ const result = await defaultTaskReplayManager.replay(taskId, async (step) => {
48
+ // Step execution verification
49
+ return step.success;
50
+ });
51
+ s.stop(chalk.green(`Replay completed in ${(result.durationMs / 1000).toFixed(2)}s.`));
52
+ console.log(chalk.bold('\nStep Replay Breakdown:'));
53
+ for (const stepRes of result.stepResults) {
54
+ const icon = stepRes.success ? chalk.green('āœ”') : chalk.red('āœ–');
55
+ const desc = `${stepRes.action}${stepRes.tool && stepRes.tool !== stepRes.action ? ` (${stepRes.tool})` : ''}`;
56
+ console.log(` ${icon} Step ${stepRes.stepIndex}: ${chalk.bold(desc)} [${stepRes.durationMs}ms]`);
57
+ if (stepRes.error) {
58
+ console.log(chalk.red(` ↳ Error: ${stepRes.error}`));
59
+ }
60
+ }
61
+ console.log(chalk.bold(`\nResults: ${chalk.green(`${result.matches} matched`)}, ${result.failures > 0 ? chalk.red(`${result.failures} failures`) : chalk.gray('0 failures')} (Total: ${result.totalReplayed})\n`));
62
+ outro(chalk.cyan('Task replay complete.'));
63
+ }
64
+ //# sourceMappingURL=replay.js.map
@@ -3,7 +3,6 @@ import chalk from 'chalk';
3
3
  import { safeNote } from '../utils/markdown.js';
4
4
  import { saveAuthConfig } from '../utils/auth.js';
5
5
  import { firebaseSignUp, FIREBASE_TENANT_ID } from '../utils/firebaseAuth.js';
6
- import { dispatchAmbientWelcomeEmail } from '../utils/email.js';
7
6
  export async function handleSignup(options) {
8
7
  let name = options?.name?.trim();
9
8
  let email = options?.email?.trim();
@@ -93,14 +92,6 @@ export async function handleSignup(options) {
93
92
  user: authRes.user,
94
93
  loggedInAt: new Date().toISOString(),
95
94
  });
96
- // Dispatch Welcome Email asynchronously
97
- await dispatchAmbientWelcomeEmail({
98
- name,
99
- email,
100
- userId: authRes.user.id,
101
- idToken: authRes.token,
102
- tenantId: FIREBASE_TENANT_ID,
103
- });
104
95
  s.stop(chalk.green(` ${isHoloseneMode ? 'Holosene' : 'FrontTerrain'} account registered successfully!`));
105
96
  safeNote(`${chalk.bold.green('Account Created for ' + name + '!')}\n\n` +
106
97
  `Account Email: ${chalk.bold.cyan(email)}\n` +
@@ -108,5 +108,6 @@ export declare class AgentExecutionLoop {
108
108
  private extractJsonToolCall;
109
109
  private extractCleanReasoning;
110
110
  private dispatchToolCall;
111
+ private executeToolCallInternal;
111
112
  }
112
113
  //# sourceMappingURL=agentEngine.d.ts.map
@@ -24,6 +24,7 @@ import { getMCPManager } from '../mcp/index.js';
24
24
  import { writeTelemetry } from '../utils/qrBridge.js';
25
25
  import { compress, LEVEL_FAST } from 'codrop';
26
26
  import { CheckpointManager } from './checkpoints/checkpointManager.js';
27
+ import { defaultTaskReplayManager } from './production/index.js';
27
28
  import { renderStepHeader, renderThoughtBox, renderToolCall, renderToolResult, renderTaskCompletedCard, ensureCompleteSentence, getActionFriendlyDescription, } from '../utils/claudeUI.js';
28
29
  import { loadWorkspaceRules } from '../utils/rules.js';
29
30
  import { InterruptManager } from '../utils/interruptHandler.js';
@@ -865,6 +866,8 @@ When returning tool calls, use standard OpenAI function calling format or JSON t
865
866
  this.taskStateManager.createTaskState(userGoal);
866
867
  this.executionIntent = inferExecutionIntent(userGoal);
867
868
  this.taskStateManager.setObjective(userGoal);
869
+ const activeTaskId = this.taskStateManager.getCurrentState().taskId;
870
+ defaultTaskReplayManager.startTrace(activeTaskId, userGoal, { cwd: this.cwd, tier: this.userTier });
868
871
  this.syncTelemetry('running', `scout: autonomous execution started for "${userGoal.slice(0, 55)}"`);
869
872
  if (this.computerController.setExpectedApplication && this.executionIntent.requiredApplications.length > 0) {
870
873
  this.computerController.setExpectedApplication(this.executionIntent.requiredApplications[0] ?? null);
@@ -1568,6 +1571,12 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1568
1571
  }
1569
1572
  finally {
1570
1573
  interruptManager.detach();
1574
+ try {
1575
+ const currentStatus = this.taskStateManager.getCurrentState().status;
1576
+ const activeTaskId = this.taskStateManager.getCurrentState().taskId;
1577
+ defaultTaskReplayManager.finalizeTrace(activeTaskId, currentStatus === 'completed' ? 'completed' : 'failed');
1578
+ }
1579
+ catch { }
1571
1580
  }
1572
1581
  }
1573
1582
  extractJsonToolCall(content) {
@@ -1650,6 +1659,38 @@ You MUST output exactly ONE JSON code block per tool call. Do NOT describe what
1650
1659
  return ensureCompleteSentence(candidate, fallbackDesc);
1651
1660
  }
1652
1661
  async dispatchToolCall(name, args) {
1662
+ const toolStartTime = Date.now();
1663
+ const taskId = this.taskStateManager.getCurrentState().taskId;
1664
+ try {
1665
+ const res = await this.executeToolCallInternal(name, args);
1666
+ const durationMs = Date.now() - toolStartTime;
1667
+ defaultTaskReplayManager.recordStep(taskId, {
1668
+ stepIndex: this.currentStep,
1669
+ action: name,
1670
+ tool: name,
1671
+ args,
1672
+ result: res.result,
1673
+ success: !res.result.startsWith('Error:'),
1674
+ durationMs,
1675
+ });
1676
+ return res;
1677
+ }
1678
+ catch (err) {
1679
+ const durationMs = Date.now() - toolStartTime;
1680
+ defaultTaskReplayManager.recordStep(taskId, {
1681
+ stepIndex: this.currentStep,
1682
+ action: name,
1683
+ tool: name,
1684
+ args,
1685
+ result: null,
1686
+ error: err?.message || String(err),
1687
+ success: false,
1688
+ durationMs,
1689
+ });
1690
+ throw err;
1691
+ }
1692
+ }
1693
+ async executeToolCallInternal(name, args) {
1653
1694
  this.totalToolCalls++;
1654
1695
  let actionDesc = '';
1655
1696
  if (name === 'read_file')
@@ -73,7 +73,7 @@ export class BrowserActionEngine {
73
73
  else if (cleanUrl.startsWith('http')) {
74
74
  try {
75
75
  const res = await fetch(cleanUrl, {
76
- headers: { 'User-Agent': 'Scout-ActionEngine/9.5.7' },
76
+ headers: { 'User-Agent': 'Scout-ActionEngine/9.5.9' },
77
77
  signal: AbortSignal.timeout(15000),
78
78
  });
79
79
  if (res.ok) {
@@ -20,7 +20,7 @@ export class BrowserObserver {
20
20
  if (!html && url.startsWith('http')) {
21
21
  try {
22
22
  const res = await fetch(url, {
23
- headers: { 'User-Agent': 'Scout-BrowserObserver/9.5.7' },
23
+ headers: { 'User-Agent': 'Scout-BrowserObserver/9.5.9' },
24
24
  signal: AbortSignal.timeout(10000),
25
25
  });
26
26
  if (res.ok) {
@@ -27,6 +27,15 @@ export class CheckpointManager {
27
27
  if (!fs.existsSync(this.checkpointDir)) {
28
28
  fs.mkdirSync(this.checkpointDir, { recursive: true });
29
29
  }
30
+ if (process.platform === 'win32') {
31
+ try {
32
+ const rootFt = path.join(this.workspaceDir, '.ft');
33
+ if (fs.existsSync(rootFt)) {
34
+ execSync(`attrib +h "${rootFt}"`, { windowsHide: true, stdio: 'ignore' });
35
+ }
36
+ }
37
+ catch { }
38
+ }
30
39
  }
31
40
  catch { }
32
41
  }
@@ -114,9 +114,15 @@ export declare class SystemComputerController implements IComputerController {
114
114
  private activeWindow;
115
115
  private driverExePath;
116
116
  private driverInitAttempted;
117
+ private serverProcess;
118
+ private serverStdoutBuffer;
119
+ private serverQueue;
117
120
  constructor(workspaceDir?: string);
118
121
  setExpectedApplication(app: string | null): void;
119
122
  getExpectedApplication(): string | null;
123
+ dispose(): void;
124
+ private killServerProcess;
125
+ private ensureServerProcess;
120
126
  /**
121
127
  * Resolves or builds the native scout_driver.exe for Windows.
122
128
  */
@@ -48,6 +48,9 @@ export class SystemComputerController {
48
48
  activeWindow = null;
49
49
  driverExePath = null;
50
50
  driverInitAttempted = false;
51
+ serverProcess = null;
52
+ serverStdoutBuffer = '';
53
+ serverQueue = [];
51
54
  constructor(workspaceDir = process.cwd()) {
52
55
  this.workspaceDir = workspaceDir;
53
56
  this.screenshotsDir = path.join(this.workspaceDir, '.ft', 'screenshots');
@@ -57,6 +60,8 @@ export class SystemComputerController {
57
60
  }
58
61
  }
59
62
  catch { }
63
+ // Clean up persistent driver server on process exit
64
+ process.on('exit', () => this.killServerProcess());
60
65
  }
61
66
  setExpectedApplication(app) {
62
67
  this.expectedApplication = app;
@@ -64,6 +69,75 @@ export class SystemComputerController {
64
69
  getExpectedApplication() {
65
70
  return this.expectedApplication;
66
71
  }
72
+ dispose() {
73
+ this.killServerProcess();
74
+ }
75
+ killServerProcess() {
76
+ if (this.serverProcess) {
77
+ try {
78
+ this.serverProcess.stdin?.write('exit\n');
79
+ this.serverProcess.kill();
80
+ }
81
+ catch { }
82
+ this.serverProcess = null;
83
+ }
84
+ this.serverStdoutBuffer = '';
85
+ while (this.serverQueue.length > 0) {
86
+ const item = this.serverQueue.shift();
87
+ if (item) {
88
+ clearTimeout(item.timeout);
89
+ item.reject(new Error('Driver server process terminated'));
90
+ }
91
+ }
92
+ }
93
+ async ensureServerProcess(driverPath) {
94
+ if (this.serverProcess && !this.serverProcess.killed) {
95
+ return true;
96
+ }
97
+ try {
98
+ const cp = spawn(driverPath, ['--server'], {
99
+ windowsHide: true,
100
+ stdio: ['pipe', 'pipe', 'ignore'],
101
+ });
102
+ cp.stdout?.setEncoding('utf-8');
103
+ cp.stdout?.on('data', (chunk) => {
104
+ this.serverStdoutBuffer += chunk;
105
+ let newlineIdx;
106
+ while ((newlineIdx = this.serverStdoutBuffer.indexOf('\n')) !== -1) {
107
+ const line = this.serverStdoutBuffer.slice(0, newlineIdx).trim();
108
+ this.serverStdoutBuffer = this.serverStdoutBuffer.slice(newlineIdx + 1);
109
+ if (!line)
110
+ continue;
111
+ const item = this.serverQueue.shift();
112
+ if (item) {
113
+ clearTimeout(item.timeout);
114
+ try {
115
+ if (line.startsWith('{') && line.endsWith('}')) {
116
+ item.resolve(JSON.parse(line));
117
+ }
118
+ else {
119
+ item.resolve({ success: true, output: line });
120
+ }
121
+ }
122
+ catch {
123
+ item.resolve({ success: true, output: line });
124
+ }
125
+ }
126
+ }
127
+ });
128
+ cp.on('error', () => {
129
+ this.killServerProcess();
130
+ });
131
+ cp.on('exit', () => {
132
+ this.killServerProcess();
133
+ });
134
+ this.serverProcess = cp;
135
+ return true;
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ }
67
141
  /**
68
142
  * Resolves or builds the native scout_driver.exe for Windows.
69
143
  */
@@ -142,6 +216,36 @@ export class SystemComputerController {
142
216
  const driver = await this.ensureDriver();
143
217
  const strArgs = args.map((a) => String(a));
144
218
  if (driver) {
219
+ // Fast path: Persistent driver server IPC (sub-2ms response time)
220
+ try {
221
+ const serverReady = await this.ensureServerProcess(driver);
222
+ if (serverReady && this.serverProcess?.stdin?.writable) {
223
+ const formattedArgs = strArgs.map(arg => {
224
+ if (arg.includes(' ') || arg.includes('\t') || arg.includes('"')) {
225
+ return `"${arg.replace(/"/g, '\\"')}"`;
226
+ }
227
+ return arg;
228
+ });
229
+ const cmdLine = [action, ...formattedArgs].join(' ');
230
+ const res = await new Promise((resolve, reject) => {
231
+ const timeout = setTimeout(() => {
232
+ const idx = this.serverQueue.findIndex(q => q.timeout === timeout);
233
+ if (idx !== -1) {
234
+ this.serverQueue.splice(idx, 1);
235
+ }
236
+ reject(new Error(`Server IPC timeout for action "${action}"`));
237
+ }, 5000);
238
+ this.serverQueue.push({ resolve, reject, timeout });
239
+ this.serverProcess.stdin.write(cmdLine + '\n');
240
+ });
241
+ return res;
242
+ }
243
+ }
244
+ catch {
245
+ // If server IPC fails or times out, gracefully fall back to one-shot execution
246
+ this.killServerProcess();
247
+ }
248
+ // Fallback: One-shot process execution
145
249
  try {
146
250
  const { stdout } = await execFileAsync(driver, [action, ...strArgs], {
147
251
  windowsHide: true,
@@ -779,9 +883,10 @@ if ($act -eq "move") {
779
883
  try {
780
884
  const startTarget = isGenericBrowser ? 'https://www.google.com' : canonicalCmd;
781
885
  const startArgs = isGenericBrowser ? [] : finalArgs;
782
- const child = spawn('cmd.exe', ['/c', 'start', '', startTarget, ...startArgs], {
886
+ const child = spawn('cmd.exe', ['/c', 'start', '""', startTarget, ...startArgs], {
783
887
  detached: true,
784
888
  stdio: 'ignore',
889
+ windowsHide: true,
785
890
  });
786
891
  child.unref();
787
892
  launched = true;
@@ -16,7 +16,7 @@ const openaiApiKey = process.env.OPENAI_API_KEY;
16
16
  const geminiApiKey = process.env.GEMINI_API_KEY;
17
17
  const nvidiaApiKey = process.env.NVIDIA_API_KEY || process.env.NVCF_API_KEY;
18
18
  const ftApiKey = process.env.FRONTTERRAIN_API_KEY || process.env.FT_API_KEY;
19
- const ftApiBase = process.env.FRONTTERRAIN_API_BASE || process.env.FT_API_BASE || 'https://api.frontterrain.com/v1';
19
+ const ftApiBase = process.env.FRONTTERRAIN_API_BASE || process.env.FT_API_BASE || 'https://frontterrain.com/api/v1';
20
20
  const authConfig = loadAuthConfig();
21
21
  const byokApiKey = authConfig.byokEnabled ? authConfig.customApiKey?.trim() : undefined;
22
22
  const byokProvider = authConfig.customLlmProvider?.trim().toLowerCase();
@@ -40,7 +40,7 @@ export function getClientForModel(modelName) {
40
40
  }
41
41
  const modelLower = (modelName || '').toLowerCase();
42
42
  // FrontTerrain Native Custom Models (Plug & Play when trained/hosted)
43
- if (modelLower.startsWith('frontterrain/') || modelLower.startsWith('ft/') || modelLower.includes('frontterrain')) {
43
+ if (modelLower.startsWith('frontterrain/') || modelLower.startsWith('ft/') || modelLower.includes('frontterrain') || modelLower.includes('harp')) {
44
44
  const key = ftApiKey || authConfig.customApiKey || nvidiaApiKey || 'ft-native';
45
45
  const base = ftApiBase;
46
46
  if (!clientCache.has('frontterrain')) {
@@ -7,6 +7,7 @@ export interface ReplayStep {
7
7
  observationAfter?: any | undefined;
8
8
  result: any;
9
9
  success: boolean;
10
+ error?: string | undefined;
10
11
  durationMs: number;
11
12
  timestamp: string;
12
13
  }
@@ -20,18 +21,36 @@ export interface TaskReplayTrace {
20
21
  totalDurationMs: number;
21
22
  metadata?: Record<string, any> | undefined;
22
23
  }
24
+ export interface ReplayStepResult {
25
+ stepIndex: number;
26
+ action: string;
27
+ tool?: string | undefined;
28
+ success: boolean;
29
+ error?: string | undefined;
30
+ durationMs: number;
31
+ }
32
+ export interface ReplayExecutionResult {
33
+ totalReplayed: number;
34
+ matches: number;
35
+ failures: number;
36
+ stepResults: ReplayStepResult[];
37
+ durationMs: number;
38
+ }
23
39
  export declare class TaskReplayManager {
24
40
  private traces;
41
+ private storageDir;
42
+ constructor(storageDir?: string);
43
+ private ensureStorageDir;
25
44
  startTrace(taskId: string, objective: string, metadata?: Record<string, any> | undefined): TaskReplayTrace;
26
45
  recordStep(taskId: string, step: Omit<ReplayStep, 'timestamp'>): void;
27
46
  finalizeTrace(taskId: string, status: TaskReplayTrace['finalStatus']): TaskReplayTrace | undefined;
28
47
  getTrace(taskId: string): TaskReplayTrace | undefined;
29
48
  exportTraceJson(taskId: string): string;
30
49
  importTraceJson(jsonContent: string): TaskReplayTrace;
31
- replay(taskId: string, stepExecutor?: (step: ReplayStep) => Promise<boolean>): Promise<{
32
- totalReplayed: number;
33
- matches: number;
34
- failures: number;
35
- }>;
50
+ saveTraceToDisk(taskId: string, customDir?: string): string;
51
+ loadTraceFromDisk(taskId: string, customDir?: string): TaskReplayTrace | undefined;
52
+ listDiskTraces(customDir?: string): string[];
53
+ replay(taskId: string, stepExecutor?: (step: ReplayStep) => Promise<boolean>): Promise<ReplayExecutionResult>;
36
54
  }
55
+ export declare const defaultTaskReplayManager: TaskReplayManager;
37
56
  //# sourceMappingURL=taskReplay.d.ts.map
@@ -1,5 +1,30 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
1
4
  export class TaskReplayManager {
2
5
  traces = new Map();
6
+ storageDir;
7
+ constructor(storageDir) {
8
+ this.storageDir = storageDir || path.resolve(process.cwd(), '.ft', 'traces');
9
+ }
10
+ ensureStorageDir() {
11
+ try {
12
+ if (!fs.existsSync(this.storageDir)) {
13
+ fs.mkdirSync(this.storageDir, { recursive: true });
14
+ }
15
+ if (process.platform === 'win32') {
16
+ try {
17
+ const { execSync } = require('child_process');
18
+ const rootFt = path.resolve(this.storageDir, '..');
19
+ if (path.basename(rootFt) === '.ft' && fs.existsSync(rootFt)) {
20
+ execSync(`attrib +h "${rootFt}"`, { windowsHide: true, stdio: 'ignore' });
21
+ }
22
+ }
23
+ catch { }
24
+ }
25
+ }
26
+ catch { }
27
+ }
3
28
  startTrace(taskId, objective, metadata) {
4
29
  const trace = {
5
30
  taskId,
@@ -14,60 +39,179 @@ export class TaskReplayManager {
14
39
  return trace;
15
40
  }
16
41
  recordStep(taskId, step) {
17
- const trace = this.traces.get(taskId);
18
- if (!trace)
19
- return;
42
+ let trace = this.traces.get(taskId);
43
+ if (!trace) {
44
+ // Attempt to restore from disk if trace was started earlier
45
+ trace = this.loadTraceFromDisk(taskId);
46
+ if (!trace) {
47
+ // Auto-create trace container if recording directly
48
+ trace = this.startTrace(taskId, `Task ${taskId}`);
49
+ }
50
+ }
20
51
  trace.steps.push({
21
52
  ...step,
22
53
  timestamp: new Date().toISOString(),
23
54
  });
24
55
  }
25
56
  finalizeTrace(taskId, status) {
26
- const trace = this.traces.get(taskId);
57
+ const trace = this.traces.get(taskId) || this.loadTraceFromDisk(taskId);
27
58
  if (!trace)
28
59
  return undefined;
29
60
  trace.endTime = new Date().toISOString();
30
61
  trace.finalStatus = status;
31
62
  trace.totalDurationMs = Date.now() - new Date(trace.startTime).getTime();
63
+ // Automatically persist finalized trace to disk
64
+ try {
65
+ this.saveTraceToDisk(taskId);
66
+ }
67
+ catch { }
32
68
  return trace;
33
69
  }
34
70
  getTrace(taskId) {
35
- return this.traces.get(taskId);
71
+ let trace = this.traces.get(taskId);
72
+ if (!trace) {
73
+ trace = this.loadTraceFromDisk(taskId);
74
+ }
75
+ return trace;
36
76
  }
37
77
  exportTraceJson(taskId) {
38
- const trace = this.traces.get(taskId);
78
+ const trace = this.getTrace(taskId);
39
79
  if (!trace)
40
80
  throw new Error(`Trace not found for task ${taskId}`);
41
81
  return JSON.stringify(trace, null, 2);
42
82
  }
43
83
  importTraceJson(jsonContent) {
44
84
  const trace = JSON.parse(jsonContent);
85
+ if (!trace || !trace.taskId) {
86
+ throw new Error('Invalid trace JSON payload: missing taskId');
87
+ }
45
88
  this.traces.set(trace.taskId, trace);
46
89
  return trace;
47
90
  }
91
+ saveTraceToDisk(taskId, customDir) {
92
+ const trace = this.getTrace(taskId);
93
+ if (!trace)
94
+ throw new Error(`Trace not found for task ${taskId}`);
95
+ const dir = customDir || this.storageDir;
96
+ if (!fs.existsSync(dir)) {
97
+ fs.mkdirSync(dir, { recursive: true });
98
+ }
99
+ const filePath = path.join(dir, `${taskId}.json`);
100
+ fs.writeFileSync(filePath, JSON.stringify(trace, null, 2), 'utf-8');
101
+ return filePath;
102
+ }
103
+ loadTraceFromDisk(taskId, customDir) {
104
+ const dir = customDir || this.storageDir;
105
+ const filePath = path.join(dir, `${taskId}.json`);
106
+ if (!fs.existsSync(filePath)) {
107
+ // Also check global fallback ~/.ft/traces
108
+ const globalFilePath = path.join(os.homedir(), '.ft', 'traces', `${taskId}.json`);
109
+ if (fs.existsSync(globalFilePath)) {
110
+ try {
111
+ const content = fs.readFileSync(globalFilePath, 'utf-8');
112
+ const trace = JSON.parse(content);
113
+ this.traces.set(trace.taskId, trace);
114
+ return trace;
115
+ }
116
+ catch { }
117
+ }
118
+ return undefined;
119
+ }
120
+ try {
121
+ const content = fs.readFileSync(filePath, 'utf-8');
122
+ const trace = JSON.parse(content);
123
+ this.traces.set(trace.taskId, trace);
124
+ return trace;
125
+ }
126
+ catch {
127
+ return undefined;
128
+ }
129
+ }
130
+ listDiskTraces(customDir) {
131
+ const dir = customDir || this.storageDir;
132
+ if (!fs.existsSync(dir))
133
+ return [];
134
+ try {
135
+ return fs.readdirSync(dir)
136
+ .filter(f => f.endsWith('.json'))
137
+ .map(f => f.replace(/\.json$/, ''));
138
+ }
139
+ catch {
140
+ return [];
141
+ }
142
+ }
48
143
  async replay(taskId, stepExecutor) {
49
- const trace = this.traces.get(taskId);
144
+ const trace = this.getTrace(taskId);
50
145
  if (!trace)
51
146
  throw new Error(`Trace not found for task ${taskId}`);
147
+ const startTime = Date.now();
52
148
  let matches = 0;
53
149
  let failures = 0;
150
+ const stepResults = [];
54
151
  for (const step of trace.steps) {
152
+ const stepStartTime = Date.now();
55
153
  if (stepExecutor) {
56
- const ok = await stepExecutor(step);
57
- if (ok) {
58
- matches++;
154
+ try {
155
+ const ok = await stepExecutor(step);
156
+ const durationMs = Date.now() - stepStartTime;
157
+ if (ok) {
158
+ matches++;
159
+ stepResults.push({
160
+ stepIndex: step.stepIndex,
161
+ action: step.action,
162
+ tool: step.tool,
163
+ success: true,
164
+ durationMs,
165
+ });
166
+ }
167
+ else {
168
+ failures++;
169
+ stepResults.push({
170
+ stepIndex: step.stepIndex,
171
+ action: step.action,
172
+ tool: step.tool,
173
+ success: false,
174
+ error: 'Step executor returned false (verification failed)',
175
+ durationMs,
176
+ });
177
+ }
59
178
  }
60
- else {
179
+ catch (err) {
180
+ const durationMs = Date.now() - stepStartTime;
61
181
  failures++;
182
+ stepResults.push({
183
+ stepIndex: step.stepIndex,
184
+ action: step.action,
185
+ tool: step.tool,
186
+ success: false,
187
+ error: err?.message || String(err),
188
+ durationMs,
189
+ });
62
190
  }
63
191
  }
64
192
  else {
65
193
  // Deterministic verification against recorded success
194
+ const durationMs = step.durationMs || 0;
66
195
  if (step.success) {
67
196
  matches++;
197
+ stepResults.push({
198
+ stepIndex: step.stepIndex,
199
+ action: step.action,
200
+ tool: step.tool,
201
+ success: true,
202
+ durationMs,
203
+ });
68
204
  }
69
205
  else {
70
206
  failures++;
207
+ stepResults.push({
208
+ stepIndex: step.stepIndex,
209
+ action: step.action,
210
+ tool: step.tool,
211
+ success: false,
212
+ error: step.error || 'Recorded step was unsuccessful',
213
+ durationMs,
214
+ });
71
215
  }
72
216
  }
73
217
  }
@@ -75,7 +219,10 @@ export class TaskReplayManager {
75
219
  totalReplayed: trace.steps.length,
76
220
  matches,
77
221
  failures,
222
+ stepResults,
223
+ durationMs: Date.now() - startTime,
78
224
  };
79
225
  }
80
226
  }
227
+ export const defaultTaskReplayManager = new TaskReplayManager();
81
228
  //# sourceMappingURL=taskReplay.js.map
@@ -1332,6 +1332,7 @@ Action Rules:
1332
1332
  fs.mkdirSync(path.dirname(fullPath), { recursive: true });
1333
1333
  fs.writeFileSync(fullPath, content, 'utf-8');
1334
1334
  this.modifiedFiles.add(targetPath);
1335
+ this.readFilesHistory.delete(targetPath);
1335
1336
  this.workspace.recordArtifact({
1336
1337
  filename: path.basename(targetPath),
1337
1338
  path: targetPath,
@@ -1362,6 +1363,7 @@ Action Rules:
1362
1363
  }
1363
1364
  fs.writeFileSync(fullPath, replaceRes.updatedContent, 'utf-8');
1364
1365
  this.modifiedFiles.add(targetPath);
1366
+ this.readFilesHistory.delete(targetPath);
1365
1367
  this.workspace.addObservation({ tool: name, resultSummary: `Edited file ${targetPath}`, verified: true, target: targetPath });
1366
1368
  return { result: `Successfully updated "${targetPath}".` };
1367
1369
  }
@@ -505,6 +505,13 @@ export class AgentWorkspace {
505
505
  try {
506
506
  const ftDir = path.join(this.workspaceDir, '.ft');
507
507
  fs.mkdirSync(ftDir, { recursive: true });
508
+ if (process.platform === 'win32') {
509
+ try {
510
+ const { execSync } = require('child_process');
511
+ execSync(`attrib +h "${ftDir}"`, { windowsHide: true, stdio: 'ignore' });
512
+ }
513
+ catch { }
514
+ }
508
515
  fs.writeFileSync(path.join(ftDir, 'scratchpad.md'), this.data.scratchpadNotes, 'utf-8');
509
516
  try {
510
517
  fs.writeFileSync(path.join(ftDir, 'scratchpad.cdp'), compress(Buffer.from(this.data.scratchpadNotes, 'utf-8'), LEVEL_FAST));
package/bin/src/index.js CHANGED
@@ -29,6 +29,7 @@ import { handleMcpList, handleMcpAdd, handleMcpRemove, handleMcpConnect, handleM
29
29
  import { handleCheckpoint, handleRollback, handleListCheckpoints } from './commands/checkpoint.js';
30
30
  import { handleWatch } from './commands/watch.js';
31
31
  import { handlePrCommand } from './commands/pr.js';
32
+ import { handleReplay } from './commands/replay.js';
32
33
  import { renderBranding } from './utils/branding.js';
33
34
  import { checkForUpdates } from './utils/updateCheck.js';
34
35
  import { maybeShowDiscoveryMessage } from './discovery/display.js';
@@ -39,16 +40,16 @@ program
39
40
  .name('scout')
40
41
  .alias('ft')
41
42
  .description('FrontTerrain The Onboarding Co-Pilot for New Codebases')
42
- .version('9.5.7');
43
+ .version('9.5.9');
43
44
  // Header UI on execution with FrontTerrain proprietary logo & version auto-checker
44
45
  program.hook('preAction', async (_thisCommand, actionCommand) => {
45
- intro(renderBranding('9.5.7'));
46
+ intro(renderBranding('9.5.9'));
46
47
  const cmdName = actionCommand ? actionCommand.name() : '';
47
48
  if (cmdName !== 'upgrade') {
48
- await checkForUpdates('9.5.7');
49
+ await checkForUpdates('9.5.9');
49
50
  }
50
- // Auth Guard: enforce authentication for all commands except login, signup, upgrade, help, dashboard, auth, status, plan, mcp, switch, accounts, support
51
- const EXEMPT_COMMANDS = ['login', 'signin', 'signup', 'register', 'upgrade', 'help', 'dashboard', 'web-ui', 'gui', 'auth', 'status', 'quota', 'usage', 'credits', 'plan', 'pricing', 'subscribe', 'mcp', 'switch', 'accounts', 'account', 'support', 'ticket', 'helpdesk'];
51
+ // Auth Guard: enforce authentication for all commands except login, signup, upgrade, help, dashboard, auth, status, plan, mcp, switch, accounts, support, replay
52
+ const EXEMPT_COMMANDS = ['login', 'signin', 'signup', 'register', 'upgrade', 'help', 'dashboard', 'web-ui', 'gui', 'auth', 'status', 'quota', 'usage', 'credits', 'plan', 'pricing', 'subscribe', 'mcp', 'switch', 'accounts', 'account', 'support', 'ticket', 'helpdesk', 'replay', 'trace'];
52
53
  if (!EXEMPT_COMMANDS.includes(cmdName)) {
53
54
  const authCfg = loadAuthConfig();
54
55
  const hasEnvApiKey = Boolean(process.env.OPENAI_API_KEY ||
@@ -266,7 +267,7 @@ program
266
267
  .command('upgrade')
267
268
  .description('Check for updates and auto-upgrade Scout to the latest version')
268
269
  .action(async () => {
269
- await checkForUpdates('9.5.7', true);
270
+ await checkForUpdates('9.5.9', true);
270
271
  outro(chalk.cyan('Upgrade check complete.'));
271
272
  });
272
273
  program
@@ -541,6 +542,16 @@ program
541
542
  await handlePrCommand(title, options);
542
543
  outro(chalk.cyan('PR workflow complete.'));
543
544
  });
545
+ // Production Hardening: Task Replay & Telemetry Engine
546
+ program
547
+ .command('replay [taskId]')
548
+ .alias('trace')
549
+ .description('Deterministic multi-step task replay, regression verification & execution trace export')
550
+ .option('-l, --list', 'List all available recorded task traces')
551
+ .option('-e, --export', 'Export task trace as JSON to stdout')
552
+ .action(async (taskId, options) => {
553
+ await handleReplay(taskId, options);
554
+ });
544
555
  try {
545
556
  await program.parseAsync(process.argv);
546
557
  }
@@ -37,7 +37,7 @@ export class MCPClient {
37
37
  },
38
38
  clientInfo: {
39
39
  name: 'scout',
40
- version: '9.5.7',
40
+ version: '9.5.9',
41
41
  },
42
42
  };
43
43
  const result = await this.transport.sendRequest('initialize', initParams, timeoutMs);
@@ -15,6 +15,7 @@ import { ApprovalManager } from '../engine/safety.js';
15
15
  import { AgentExecutionLoop } from '../engine/agentEngine.js';
16
16
  import { getMCPManager, MCPTelemetry } from '../mcp/index.js';
17
17
  import { loadSupportTickets, createSupportTicket, getSupportTicket, addTicketMessage, updateTicketStatus, collectSanitizedDiagnostics, getPresetFaqs, } from '../utils/support.js';
18
+ import { firebaseSignUp, FIREBASE_TENANT_ID, FIREBASE_API_KEY, FIREBASE_PROJECT_ID } from '../utils/firebaseAuth.js';
18
19
  let activeAgentLoop = null;
19
20
  const serverStateManager = new TaskStateManager(process.cwd());
20
21
  const DEFAULT_PORT = 9120;
@@ -1226,13 +1227,233 @@ export function startDashboardServer(port = DEFAULT_PORT) {
1226
1227
  });
1227
1228
  return;
1228
1229
  }
1230
+ // POST /api/prelaunch/register - Pre-launch VIP Waitlist & 1,000 Token Voucher
1231
+ if (pathname === '/api/prelaunch/register' && req.method === 'POST') {
1232
+ let body = '';
1233
+ req.on('data', chunk => body += chunk);
1234
+ req.on('end', async () => {
1235
+ try {
1236
+ const data = JSON.parse(body || '{}');
1237
+ if (!data.name || !data.email) {
1238
+ res.writeHead(400);
1239
+ res.end(JSON.stringify({ success: false, error: 'Name and email are required.' }));
1240
+ return;
1241
+ }
1242
+ const normalizedEmail = data.email.toLowerCase().trim();
1243
+ const ftDir = path.join(process.cwd(), '.ft');
1244
+ if (!fs.existsSync(ftDir)) {
1245
+ fs.mkdirSync(ftDir, { recursive: true });
1246
+ }
1247
+ const regFile = path.join(ftDir, 'prelaunch_registrations.json');
1248
+ let registrations = [];
1249
+ if (fs.existsSync(regFile)) {
1250
+ try {
1251
+ registrations = JSON.parse(fs.readFileSync(regFile, 'utf-8'));
1252
+ }
1253
+ catch { }
1254
+ }
1255
+ const existing = registrations.find((r) => r.email && r.email.toLowerCase().trim() === normalizedEmail);
1256
+ if (existing) {
1257
+ res.writeHead(200);
1258
+ res.end(JSON.stringify({
1259
+ success: true,
1260
+ alreadyRegistered: true,
1261
+ message: 'Email is already registered. Returning existing VIP pass.',
1262
+ name: existing.name,
1263
+ email: existing.email,
1264
+ role: existing.role || 'creator',
1265
+ voucherCode: existing.voucherCode,
1266
+ tenantId: existing.tenantId || FIREBASE_TENANT_ID,
1267
+ tenantUid: existing.tenantUid || 'Cloud Verified',
1268
+ baseTokens: existing.baseTokens || 1000,
1269
+ bonusTokens: existing.bonusTokens || 0,
1270
+ tokensGranted: existing.tokensGranted || (1000 + (existing.bonusTokens || 0)),
1271
+ referralCount: existing.referralCount || 0,
1272
+ waitlistRank: existing.waitlistRank || 428,
1273
+ registeredAt: existing.registeredAt,
1274
+ }));
1275
+ return;
1276
+ }
1277
+ const cleanName = data.name.replace(/[^a-zA-Z0-9]/g, '').slice(0, 4).toUpperCase() || 'VIP';
1278
+ const randomSuffix = Math.random().toString(36).substring(2, 6).toUpperCase();
1279
+ const voucherCode = data.voucherCode || `ENGLERT-${cleanName}-${randomSuffix}`;
1280
+ const waitlistRank = 428 + registrations.length + 1;
1281
+ // 1. Direct Cloud Provisioning in Scout Identity Platform Tenant (ft-scout-auth-gc2v5)
1282
+ let tenantUid = null;
1283
+ try {
1284
+ const authResult = await firebaseSignUp(data.name, normalizedEmail, `ScoutVIP@${voucherCode}!2026`);
1285
+ tenantUid = authResult?.user?.id || null;
1286
+ }
1287
+ catch (authErr) {
1288
+ if (authErr?.message?.includes('already exists') || authErr?.message?.includes('EMAIL_EXISTS')) {
1289
+ // User already exists in the tenant
1290
+ }
1291
+ }
1292
+ // 2. Handle Referrer Bonus (+500 ENGLERT Tokens for the referrer)
1293
+ let referrerAwarded = false;
1294
+ let referredByCode = null;
1295
+ let awardedReferrer = null;
1296
+ if (data.refCode) {
1297
+ const cleanRef = data.refCode.toString().trim().toUpperCase();
1298
+ const referrer = registrations.find((r) => r.voucherCode && r.voucherCode.toUpperCase() === cleanRef);
1299
+ if (referrer && referrer.email.toLowerCase() !== normalizedEmail) {
1300
+ referrer.referralCount = (referrer.referralCount || 0) + 1;
1301
+ referrer.bonusTokens = (referrer.bonusTokens || 0) + 500;
1302
+ referrer.tokensGranted = (referrer.tokensGranted || 1000) + 500;
1303
+ referrer.lastReferralAt = new Date().toISOString();
1304
+ referrerAwarded = true;
1305
+ referredByCode = referrer.voucherCode;
1306
+ awardedReferrer = referrer;
1307
+ }
1308
+ }
1309
+ const newEntry = {
1310
+ name: data.name,
1311
+ email: normalizedEmail,
1312
+ role: data.role || 'creator',
1313
+ refCode: data.refCode || null,
1314
+ referredBy: referredByCode,
1315
+ voucherCode,
1316
+ tenantId: FIREBASE_TENANT_ID,
1317
+ tenantUid,
1318
+ waitlistRank,
1319
+ tokensGranted: 1000,
1320
+ bonusTokens: 0,
1321
+ referralCount: 0,
1322
+ registeredAt: new Date().toISOString(),
1323
+ cloudTenantVerified: true,
1324
+ };
1325
+ // 3. Direct write to Cloud Firestore collection 'prelaunch_registrations'
1326
+ try {
1327
+ const safeDocId = `doc_${normalizedEmail.replace(/[^a-zA-Z0-9]/g, '_')}`;
1328
+ const firestoreUrl = `https://firestore.googleapis.com/v1/projects/${FIREBASE_PROJECT_ID}/databases/(default)/documents/prelaunch_registrations/${safeDocId}?key=${FIREBASE_API_KEY}`;
1329
+ await fetch(firestoreUrl, {
1330
+ method: 'PATCH',
1331
+ headers: { 'Content-Type': 'application/json' },
1332
+ body: JSON.stringify({
1333
+ fields: {
1334
+ name: { stringValue: data.name },
1335
+ email: { stringValue: normalizedEmail },
1336
+ role: { stringValue: data.role || 'creator' },
1337
+ voucherCode: { stringValue: voucherCode },
1338
+ tenantId: { stringValue: FIREBASE_TENANT_ID },
1339
+ tenantUid: { stringValue: tenantUid || '' },
1340
+ baseTokens: { integerValue: '1000' },
1341
+ bonusTokens: { integerValue: '0' },
1342
+ tokensGranted: { integerValue: '1000' },
1343
+ referralCount: { integerValue: '0' },
1344
+ refCode: { stringValue: data.refCode || '' },
1345
+ registeredAt: { stringValue: newEntry.registeredAt },
1346
+ cloudSynced: { booleanValue: true }
1347
+ }
1348
+ })
1349
+ });
1350
+ }
1351
+ catch { }
1352
+ // 4. Update Referrer in Cloud Firestore if awarded
1353
+ if (referrerAwarded && awardedReferrer) {
1354
+ try {
1355
+ const refDocId = `doc_${awardedReferrer.email.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()}`;
1356
+ const refFirestoreUrl = `https://firestore.googleapis.com/v1/projects/${FIREBASE_PROJECT_ID}/databases/(default)/documents/prelaunch_registrations/${refDocId}?key=${FIREBASE_API_KEY}`;
1357
+ await fetch(refFirestoreUrl, {
1358
+ method: 'PATCH',
1359
+ headers: { 'Content-Type': 'application/json' },
1360
+ body: JSON.stringify({
1361
+ fields: {
1362
+ name: { stringValue: awardedReferrer.name },
1363
+ email: { stringValue: awardedReferrer.email },
1364
+ voucherCode: { stringValue: awardedReferrer.voucherCode },
1365
+ tokensGranted: { integerValue: String(awardedReferrer.tokensGranted) },
1366
+ bonusTokens: { integerValue: String(awardedReferrer.bonusTokens) },
1367
+ referralCount: { integerValue: String(awardedReferrer.referralCount) },
1368
+ lastReferralAt: { stringValue: awardedReferrer.lastReferralAt }
1369
+ }
1370
+ })
1371
+ });
1372
+ }
1373
+ catch { }
1374
+ }
1375
+ // 5. Update local cache
1376
+ registrations.push(newEntry);
1377
+ fs.writeFileSync(regFile, JSON.stringify(registrations, null, 2), 'utf-8');
1378
+ res.writeHead(201);
1379
+ res.end(JSON.stringify({
1380
+ success: true,
1381
+ voucherCode,
1382
+ tenantId: FIREBASE_TENANT_ID,
1383
+ tenantUid,
1384
+ tokensGranted: 1000,
1385
+ bonusTokens: 0,
1386
+ referralCount: 0,
1387
+ referrerAwarded,
1388
+ waitlistRank,
1389
+ totalRegistrations: waitlistRank,
1390
+ }));
1391
+ }
1392
+ catch (err) {
1393
+ res.writeHead(400);
1394
+ res.end(JSON.stringify({ success: false, error: err.message || 'Failed to process registration' }));
1395
+ }
1396
+ });
1397
+ return;
1398
+ }
1399
+ // GET /api/prelaunch/status - Live user token balance & referral count
1400
+ if (pathname === '/api/prelaunch/status' && req.method === 'GET') {
1401
+ const code = parsedUrl.searchParams.get('code') || '';
1402
+ const email = parsedUrl.searchParams.get('email') || '';
1403
+ const regFile = path.join(process.cwd(), '.ft', 'prelaunch_registrations.json');
1404
+ let registrations = [];
1405
+ if (fs.existsSync(regFile)) {
1406
+ try {
1407
+ registrations = JSON.parse(fs.readFileSync(regFile, 'utf-8'));
1408
+ }
1409
+ catch { }
1410
+ }
1411
+ const user = registrations.find((r) => (code && r.voucherCode && r.voucherCode.toUpperCase() === code.trim().toUpperCase()) ||
1412
+ (email && r.email && r.email.toLowerCase() === email.trim().toLowerCase()));
1413
+ if (!user) {
1414
+ res.writeHead(404);
1415
+ res.end(JSON.stringify({ success: false, error: 'Registration not found' }));
1416
+ return;
1417
+ }
1418
+ res.writeHead(200);
1419
+ res.end(JSON.stringify({
1420
+ success: true,
1421
+ name: user.name,
1422
+ voucherCode: user.voucherCode,
1423
+ waitlistRank: user.waitlistRank,
1424
+ baseTokens: 1000,
1425
+ bonusTokens: user.bonusTokens || 0,
1426
+ totalTokens: user.tokensGranted || (1000 + (user.bonusTokens || 0)),
1427
+ referralCount: user.referralCount || 0,
1428
+ registeredAt: user.registeredAt,
1429
+ }));
1430
+ return;
1431
+ }
1432
+ // GET /api/prelaunch/stats - Public Pre-launch counter
1433
+ if (pathname === '/api/prelaunch/stats' && req.method === 'GET') {
1434
+ const regFile = path.join(process.cwd(), '.ft', 'prelaunch_registrations.json');
1435
+ let count = 0;
1436
+ if (fs.existsSync(regFile)) {
1437
+ try {
1438
+ const list = JSON.parse(fs.readFileSync(regFile, 'utf-8'));
1439
+ count = Array.isArray(list) ? list.length : 0;
1440
+ }
1441
+ catch { }
1442
+ }
1443
+ res.writeHead(200);
1444
+ res.end(JSON.stringify({ success: true, count: 428 + count }));
1445
+ return;
1446
+ }
1229
1447
  res.writeHead(404);
1230
1448
  res.end(JSON.stringify({ error: 'API route not found' }));
1231
1449
  return;
1232
1450
  }
1233
1451
  // Static File Server & Friendly URL Rewrites
1234
1452
  let filePath;
1235
- if (pathname === '/plans' || pathname === '/plans/') {
1453
+ if (pathname === '/register' || pathname === '/register/' || pathname === '/prelaunch' || pathname === '/prelaunch/' || pathname === '/waitlist' || pathname === '/waitlist/') {
1454
+ filePath = path.join(webDir, 'register.html');
1455
+ }
1456
+ else if (pathname === '/plans' || pathname === '/plans/') {
1236
1457
  filePath = path.join(webDir, 'paid_plans.html');
1237
1458
  }
1238
1459
  else if (pathname === '/auth' || pathname === '/auth/') {
@@ -1,5 +1,5 @@
1
1
  import chalk from 'chalk';
2
- export function renderBranding(version = '9.5.7') {
2
+ export function renderBranding(version = '9.5.9') {
3
3
  const logo = chalk.cyan.bold(' ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—') + ' ' + chalk.cyan.bold('ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•— ā–ˆā–ˆā•—ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•—') + '\n' +
4
4
  chalk.cyan.bold(' ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•') + ' ' + chalk.cyan.bold('ā–ˆā–ˆā•”ā•ā•ā•ā•ā• ā–ˆā–ˆā•”ā•ā•ā•ā•ā•ā–ˆā–ˆā•”ā•ā•ā•ā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ā•šā•ā•ā–ˆā–ˆā•”ā•ā•ā•') + '\n' +
5
5
  chalk.cyan.bold(' ā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ') + ' ' + chalk.cyan.bold(' ā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā–ˆā•— ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ā–ˆā–ˆā•‘ ') + '\n' +
@@ -31,6 +31,15 @@ export interface FtConfig {
31
31
  allowConfidential: boolean;
32
32
  maxFilesScanned?: number;
33
33
  }
34
+ /**
35
+ * Ensures the root .ft directory has the hidden attribute on Windows,
36
+ * so it stays hidden in Windows Explorer.
37
+ */
38
+ export declare function hideFtDir(workspaceDir?: string): void;
39
+ /**
40
+ * Ensures .ft/ is in the workspace's .gitignore so it is never committed to git.
41
+ */
42
+ export declare function ensureFtGitIgnored(workspaceDir?: string): void;
34
43
  export declare function saveScanReport(report: any[]): void;
35
44
  export declare function loadScanReport(): any[];
36
45
  export declare function getDirectoryFiles(dir: string, baseDir?: string, maxFiles?: number): string[];
@@ -1,10 +1,48 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { execSync } from 'child_process';
3
4
  const FT_DIR = path.join(process.cwd(), '.ft', 'scout');
4
5
  const CONTEXT_FILE = path.join(FT_DIR, 'context.json');
5
6
  const HISTORY_FILE = path.join(FT_DIR, 'history.json');
6
7
  const CONFIG_FILE = path.join(FT_DIR, 'config.json');
7
- function ensureFtDir() {
8
+ /**
9
+ * Ensures the root .ft directory has the hidden attribute on Windows,
10
+ * so it stays hidden in Windows Explorer.
11
+ */
12
+ export function hideFtDir(workspaceDir = process.cwd()) {
13
+ const ftPath = path.join(workspaceDir, '.ft');
14
+ if (fs.existsSync(ftPath) && process.platform === 'win32') {
15
+ try {
16
+ execSync(`attrib +h "${ftPath}"`, { windowsHide: true, stdio: 'ignore' });
17
+ }
18
+ catch { }
19
+ }
20
+ }
21
+ /**
22
+ * Ensures .ft/ is in the workspace's .gitignore so it is never committed to git.
23
+ */
24
+ export function ensureFtGitIgnored(workspaceDir = process.cwd()) {
25
+ const gitignorePath = path.join(workspaceDir, '.gitignore');
26
+ try {
27
+ if (fs.existsSync(gitignorePath)) {
28
+ const content = fs.readFileSync(gitignorePath, 'utf-8');
29
+ const lines = content.split(/\r?\n/).map(l => l.trim());
30
+ const hasFt = lines.some(l => l === '.ft' || l === '.ft/' || l === '/.ft/' || l === '**/.ft' || l === '**/.ft/');
31
+ if (!hasFt) {
32
+ const ending = content.endsWith('\n') ? '' : '\n';
33
+ fs.appendFileSync(gitignorePath, `${ending}.ft/\n.ft\n`, 'utf-8');
34
+ }
35
+ }
36
+ }
37
+ catch { }
38
+ }
39
+ function ensureFtDir(workspaceDir = process.cwd()) {
40
+ const rootFt = path.join(workspaceDir, '.ft');
41
+ if (!fs.existsSync(rootFt)) {
42
+ fs.mkdirSync(rootFt, { recursive: true });
43
+ }
44
+ hideFtDir(workspaceDir);
45
+ ensureFtGitIgnored(workspaceDir);
8
46
  if (!fs.existsSync(FT_DIR)) {
9
47
  fs.mkdirSync(FT_DIR, { recursive: true });
10
48
  }
@@ -105,7 +105,7 @@ export async function startQrPairingSession() {
105
105
  const pairingCode = `SCT-${rawNum}`;
106
106
  const sessionId = `sct_sess_${Date.now().toString(36)}_${crypto.randomBytes(3).toString('hex')}`;
107
107
  const hostName = os.hostname() || 'workstation.local';
108
- const version = '9.5.7';
108
+ const version = '9.5.9';
109
109
  let localIp = '127.0.0.1';
110
110
  try {
111
111
  const nets = os.networkInterfaces();
@@ -52,7 +52,7 @@ export function collectSanitizedDiagnostics() {
52
52
  catch { }
53
53
  }
54
54
  return {
55
- scoutVersion: '9.5.7',
55
+ scoutVersion: '9.5.9',
56
56
  nodeVersion: process.version,
57
57
  platform: process.platform,
58
58
  osRelease: os.release(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ft-scout",
3
- "version": "9.5.7",
3
+ "version": "9.5.9",
4
4
  "type": "module",
5
5
  "description": "FrontTerrain — The Onboarding Co-Pilot for New Codebases",
6
6
  "main": "bin/src/index.js",