### Local development setup commands Source: https://github.com/afar1/fieldtheory-cli/blob/main/CONTRIBUTING.md Run these commands to install dependencies, build the project, and execute the test suite. ```bash npm ci npm run build npm test ``` -------------------------------- ### GET Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/endpoints.md Downloads the DMG installer for the Mac app from the release asset URL. ```APIDOC ## GET ### Description Downloads the DMG installer for the Mac app from the release asset URL. ### Method GET ### Endpoint ### Response #### Success Response (200) Returns the DMG file content. #### Error Response - `Downloading Field Theory DMG failed: HTTP ` - `Downloading Field Theory DMG failed: empty response body` ``` -------------------------------- ### Programmatic Seed Management Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Example demonstrating how to build a seed strategy, query candidates, and save a seed programmatically. ```ts import { buildSeedStrategySpec } from 'fieldtheory/dist/seeds-strategies.js'; import { querySeedCandidates } from 'fieldtheory/dist/seeds-query.js'; import { saveSeedFromCandidates } from 'fieldtheory/dist/seeds-save.js'; const spec = buildSeedStrategySpec({ strategy: 'search', filters: { query: 'agents', days: 90, limit: 8 } }); const candidates = await querySeedCandidates(spec.filters); const seed = await saveSeedFromCandidates({ candidates, title: 'AI agents — last 90 days', notes: `strategy=${spec.strategy}`, strategy: spec.strategy, strategyParams: spec.strategyParams, }); console.log(seed.id); ``` -------------------------------- ### Quick start commands Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Sync bookmarks from a browser, search them, and explore data using the CLI commands. ```bash # 1. Sync your bookmarks (needs a supported browser logged into X) ft sync # 2. Search them ft search "distributed systems" # 3. Explore ft viz ft categories ft stats ``` -------------------------------- ### Install Field Theory skill Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Install the /fieldtheory skill to enable your agent to search bookmarks. ```bash ft skill install # Auto-detects Claude Code and Codex ``` -------------------------------- ### CLI Usage Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/cli.md Demonstrates how to initialize the CLI using buildCli, add a postAction hook, and parse command-line arguments. ```ts import { buildCli, engineOption } from 'fieldtheory/dist/cli.js'; const program = buildCli(); program.hook('postAction', async (_this, _action) => { // e.g. check for updates }); await program.parseAsync(['node', 'ft', 'search', 'distributed systems', '--limit', '10']); ``` -------------------------------- ### Install Field Theory CLI Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Install the CLI globally using npm. Requires Node.js 20+. ```bash npm install -g fieldtheory ``` -------------------------------- ### Using buildCli in an application Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/cli.md Example of importing and executing the CLI program using the commander Command instance. ```ts import { buildCli } from 'fieldtheory/dist/cli.js'; const program = buildCli(); program.hook('postAction', ...); await program.parseAsync(process.argv); ``` -------------------------------- ### Create and validate library and command documents Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Example demonstrating the creation of a library document, updating it with hash verification, and creating/validating a command document. ```ts import { createLibraryDocument, updateLibraryDocument } from 'fieldtheory/dist/library.js'; import { createCommandDocument, validateCommandDocument } from 'fieldtheory/dist/commands-files.js'; const doc = await createLibraryDocument('notes/example', { title: 'Example' }); await updateLibraryDocument('notes/example', { stdin: true, expectedSha256: doc.version.sha256 }); await createCommandDocument('daily-sync', { content: '# daily-sync\n\nUse this when ...\n\n## Steps\n\n1. ...\n\n## Guardrails\n\n- ...\n\n## Verification\n\n- ...\n' }); console.log(validateCommandDocument('daily-sync')); ``` -------------------------------- ### Seed Strategy Usage Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Example showing how to build a seed strategy spec, query seed candidates, and save a seed from candidates. ```APIDOC ## Seed Strategy Usage Example ### Description Example showing how to build a seed strategy spec, query seed candidates, and save a seed from candidates. ### Method Function ### Code ```ts import { buildSeedStrategySpec } from 'fieldtheory/dist/seeds-strategies.js'; import { querySeedCandidates } from 'fieldtheory/dist/seeds-query.js'; import { saveSeedFromCandidates } from 'fieldtheory/dist/seeds-save.js'; const spec = buildSeedStrategySpec({ strategy: 'search', filters: { query: 'agents', days: 90, limit: 8 } }); const candidates = await querySeedCandidates(spec.filters); const seed = await saveSeedFromCandidates({ candidates, title: 'AI agents — last 90 days', notes: `strategy=${spec.strategy}`, strategy: spec.strategy, strategyParams: spec.strategyParams, }); console.log(seed.id); ``` ``` -------------------------------- ### Bookmarks DB Usage Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-db.md Demonstrates how to initialize the index, perform a search, list bookmarks with specific filters, and retrieve database statistics using the bookmarks-db module. ```ts import { buildIndex, searchBookmarks, listBookmarks, getStats } from 'fieldtheory/dist/bookmarks-db.js'; await buildIndex(); const results = await searchBookmarks({ query: '"distributed systems"', limit: 10 }); const timeline = await listBookmarks({ category: 'tool', sort: 'desc', limit: 5 }); const stats = await getStats(); ``` -------------------------------- ### Configure nightly tasks on macOS Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Set up nightly tasks using LaunchAgent to search, add repositories, and install the nightly schedule. ```bash ft seeds search "agents" --days 90 --limit 8 --frame leverage-specificity --create ft repos add ~/dev/fieldtheory ft repos add ~/dev/fieldtheory-cli ft possible nightly install --time 02:00 --defaults --model opus --effort medium --nodes 5 ft possible nightly show ``` -------------------------------- ### Define SkillResult and InstallSkillOptions interfaces Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Interfaces for skill installation results and configuration options. ```ts export interface SkillResult { agent: string; path: string; action: 'installed' | 'updated' | 'up-to-date' | 'removed'; } export interface InstallSkillOptions { force?: boolean; } ``` -------------------------------- ### FieldTheory CLI Usage Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/app.md Demonstrates loading a Chrome session configuration, extracting CSRF cookies, and launching a target with environment variables. ```ts import { loadChromeSessionConfig } from 'fieldtheory/dist/config.js'; import { extractChromeXCookies } from 'fieldtheory/dist/chrome-cookies.js'; import { openFieldTheoryTarget, buildFieldTheoryOpenTarget } from 'fieldtheory/dist/app-open.js'; const cfg = loadChromeSessionConfig({ browserId: 'brave' }); const cookies = extractChromeXCookies(cfg.chromeUserDataDir, cfg.chromeProfileDirectory, cfg.browser); console.log(cookies.csrfToken); const target = buildFieldTheoryOpenTarget('notes/example.md', 'library'); const result = openFieldTheoryTarget(target, { env: { ...process.env, FT_APP_DEV_DIR: '/Users/you/dev/fieldtheory/mac-app' } }); if (!result.launched) { console.log('Print the URL instead:', target.url); // FT_APP_OPEN_COMMAND / --no-launch pattern } ``` -------------------------------- ### installSkill(options: InstallSkillOptions = {}): Promise Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Detects Claude Code and Codex environments and installs the skill to the appropriate location. If no environment is detected, falls back to the Claude Code path. Existing files prompt for user action unless force is set. ```APIDOC ## installSkill(options: InstallSkillOptions = {}): Promise ### Description Detects Claude Code and Codex environments and installs the skill to the appropriate location. If no environment is detected, falls back to the Claude Code path. Existing files prompt for user action unless force is set. ### Method installSkill(options: InstallSkillOptions = {}): Promise ### Parameters #### Options - **force** (boolean) - Optional - If true, overwrites existing files without prompting. ### Returns - **Promise** - A promise resolving to an array of SkillResult objects indicating the installation status for each detected agent. ### SkillResult Interface - **agent** (string) - The agent identifier (e.g., 'claude', 'codex'). - **path** (string) - The installation path. - **action** ('installed' | 'updated' | 'up-to-date' | 'removed') - The action performed. ``` -------------------------------- ### Usage example for Adjacent Librarian Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/adjacent-librarian.md Demonstrates importing core functions to write an artifact, read its content by ID, and retrieve store statistics. ```ts import { writeArtifact, readArtifact, getStoreStats } from 'fieldtheory/dist/adjacent/index.js'; const art = writeArtifact({ type: 'bookmark', source: 'field_theory', provenance: { createdAt: new Date().toISOString(), producer: 'user', inputIds: [] }, content: '# Seed\n\nSome saved tweet text', metadata: { title: 'Saved seed' }, }); console.log(readArtifact(art.id)?.content); console.log(getStoreStats()); ``` -------------------------------- ### Usage example for runPipeline with renderTwoByTwo Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/adjacent-pipeline.md Shows the full workflow: create a seed artifact with writeArtifact, resolve an engine, run the pipeline with runPipeline, and render the result with renderTwoByTwo. Wrap in try/catch to handle EngineInvocationError or Error; the consideration persists up to the last completed stage. ```TypeScript import { runPipeline, renderTwoByTwo } from 'fieldtheory/dist/adjacent/pipeline.js'; import { writeArtifact } from 'fieldtheory/dist/adjacent/librarian.js'; import { getFrame } from 'fieldtheory/dist/adjacent/frames.js'; import { resolveEngine } from 'fieldtheory/dist/engine.js'; const seed = writeArtifact({ type: 'bookmark', source: 'field_theory', provenance: { createdAt: new Date().toISOString(), producer: 'user', inputIds: [] }, content: 'A bookmark about real-time audio processing', metadata: {}, }); const engine = await resolveEngine({ override: 'claude' }); const result = await runPipeline({ seedArtifactIds: [seed.id], frame: getFrame('leverage-specificity')!, repo: '/Users/you/dev/my-repo', depth: 'quick', engine, onProgress: (stage, msg) => console.error(`[${stage}] ${msg}`), }); process.stdout.write(renderTwoByTwo(result.dots, result.consideration.frame)); ``` -------------------------------- ### Engine Invocation Usage Example Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/engine.md Demonstrates resolving an engine and invoking it asynchronously, with a try-catch block to handle EngineInvocationError. ```ts import { resolveEngine, invokeEngineAsync, EngineInvocationError } from 'fieldtheory/dist/engine.js'; const engine = await resolveEngine({ override: 'claude', model: 'opus', effort: 'medium' }); try { const out = await invokeEngineAsync(engine, 'Summarize this in one line.'); console.log(out); } catch (err) { if (err instanceof EngineInvocationError) { console.error(`reason=${err.reason} killed=${err.killed} code=${err.code}`); console.error(err.stderr); // redacted tail of child stderr } } ``` -------------------------------- ### installFieldTheoryApp(options) Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/app.md Downloads and installs the Field Theory Mac app from the latest GitHub release. Handles fetching, mounting, copying, and cleanup, with optional opening of the app. ```APIDOC ## installFieldTheoryApp(options) ### Description Downloads and installs the Field Theory Mac app from the latest GitHub release. Handles fetching, mounting, copying, and cleanup, with optional opening of the app. ### Method Function call ### Endpoint installFieldTheoryApp(options: FieldTheoryAppInstallOptions = {}): Promise ### Parameters #### Options - **fetch** (Fetcher) - Optional - Custom fetch implementation - **execFile** (ExecFileRunner) - Optional - Custom execFile runner - **installDir** (string) - Optional - Installation directory, defaults to /Applications - **open** (boolean) - Optional - Whether to open the app after install - **platform** (NodeJS.Platform) - Optional - Target platform, defaults to current - **releaseApiUrl** (string) - Optional - GitHub release API URL, defaults to https://api.github.com/repos/afar1/field-releases/releases/latest - **env** (NodeJS.ProcessEnv) - Optional - Environment variables, uses GITHUB_TOKEN or GH_TOKEN for GitHub auth - **onProgress** ((message: string) => void) - Optional - Progress callback ### Request Example { "installDir": "/Applications", "open": true, "releaseApiUrl": "https://api.github.com/repos/afar1/field-releases/releases/latest" } ### Response #### Success Response - **appPath** (string) - Path to the installed app - **assetName** (string) - Name of the downloaded DMG asset - **release** (string) - Release tag or name - **downloadUrl** (string) - URL of the downloaded asset #### Response Example { "appPath": "/Applications/Field Theory.app", "assetName": "FieldTheory-arm64.dmg", "release": "v1.0.0", "downloadUrl": "https://github.com/afar1/field-releases/releases/download/v1.0.0/FieldTheory-arm64.dmg" } ### Error Handling - Throws 'Fetching latest Field Theory release failed: HTTP ' on fetch failure - Throws 'Field Theory app install is only supported on macOS.' on non-darwin platforms - Throws 'Mounted Field Theory DMG did not contain an .app bundle.' if no .app bundle found - Throws on empty download body ``` -------------------------------- ### npm run commands for build, dev, test, and start Source: https://github.com/afar1/fieldtheory-cli/blob/main/CLAUDE.md Defines the standard npm scripts to compile TypeScript, run via tsx, run tests, and run the compiled CLI. ```bash npm run build # Compile TypeScript to dist/ npm run dev # Run via tsx directly npm run test # Run tests npm run start # Run compiled dist/cli.js ``` -------------------------------- ### runTwitterOAuthFlow(): Promise<{ tokenPath: string; scope?: string }> Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-sync.md Runs the complete OAuth flow: starts a local HTTP server, prints the authorize URL, exchanges the code for tokens, and saves them. Returns the token path and optional scope. ```APIDOC ## runTwitterOAuthFlow(): Promise<{ tokenPath: string; scope?: string }> ### Description Runs the complete OAuth flow: starts a local HTTP server, prints the authorize URL, exchanges the code for tokens, and saves them. Returns the token path and optional scope. ### Method Function ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **tokenPath** (string) - The path to the saved token file. - **scope** (string, optional) - The granted scope. #### Response Example { "tokenPath": "/path/to/dataDir/oauth-token.json", "scope": "tweet.read users.read bookmark.read offline.access" } ### Errors - Rejects with `OAuth error: ` - Rejects with `Invalid OAuth callback state/code` - Rejects with `Token exchange failed (HTTP ). Check your X API credentials.` ``` -------------------------------- ### detectBrowser(): BrowserDef Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/app.md Returns the first installed chromium-family browser, or 'chrome' if none are installed. ```APIDOC ## detectBrowser(): BrowserDef ### Description Detects and returns the first installed chromium-family browser, defaulting to 'chrome'. ### Returns - **BrowserDef** - The detected browser definition. ``` -------------------------------- ### runIdeasNightlyTick Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/ideas.md Runs a nightly tick for a given schedule ID. Reads the schedule, resolves the plan, and starts a background job. Appends log lines for tick started or failed. ```APIDOC ## runIdeasNightlyTick ### Description Runs a nightly tick for a given schedule ID. Reads the schedule, resolves the plan, and starts a background job. Appends log lines for tick started or failed. ### Signature runIdeasNightlyTick(id: string, deps: IdeasNightlyTickDeps = {}): IdeasJob ### Parameters - **id** (string) - Required - The schedule ID. - **deps** (IdeasNightlyTickDeps) - Optional - Dependencies for running the tick. ### Returns - **IdeasJob** - The started background job. ### Errors - Throws 'Nightly schedule not found: ' if the schedule does not exist. ``` -------------------------------- ### buildLaunchAgentPlist Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/ideas.md Builds the LaunchAgent plist XML content for a given schedule and invocation. Includes StartCalendarInterval, PATH environment, and stdout/stderr redirection to the schedule log. ```APIDOC ## buildLaunchAgentPlist ### Description Builds the LaunchAgent plist XML content for a given schedule and invocation. Includes StartCalendarInterval, PATH environment, and stdout/stderr redirection to the schedule log. ### Signature buildLaunchAgentPlist(input: { schedule; invocation; pathEnv? }): string ### Parameters - **input** (object) - Required - The input for building the plist. - **schedule** (IdeasNightlySchedule) - Required - The schedule object. - **invocation** (CliInvocation) - Required - The CLI invocation. - **pathEnv** (string) - Optional - The PATH environment variable. ### Returns - **string** - The plist XML content. ``` -------------------------------- ### uninstallSkill(): SkillResult[] Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Removes installed skill files for each detected agent, returning the removal results. ```APIDOC ## uninstallSkill(): SkillResult[] ### Description Removes installed skill files for each detected agent, returning the removal results. ### Method uninstallSkill(): SkillResult[] ### Returns - **SkillResult[]** - An array of SkillResult objects with action 'removed' for each detected agent. ``` -------------------------------- ### Importing PromptCancelledError Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/errors.md Shows the import statement for PromptCancelledError from the prompt module. The catching example is not shown on this page. ```TypeScript import { promptText, PromptCancelledError } from 'fieldtheory/dist/prompt.js'; ``` -------------------------------- ### stepPickModelProfile Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Prompts the user to choose an engine and model profile. It is an async step in the wizard. ```APIDOC ## stepPickModelProfile ### Description Prompts the user to choose an engine and model profile. It is an async step in the wizard. ### Method Function ### Signature `stepPickModelProfile(): Promise` ### Parameters None ### Returns Promise - Resolves when the step completes. ### Usage Example ```ts import { stepPickModelProfile } from 'fieldtheory/dist/possible-wizard.js'; await stepPickModelProfile(); ``` ``` -------------------------------- ### IdeasJob Interfaces and Options Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/ideas.md Defines the status, planning parameters, and job metadata structures, along with options for starting background jobs. ```ts export type IdeasJobStatus = 'queued' | 'running' | 'succeeded' | 'failed'; export interface IdeasJobPlan { seedArtifactIds?: string[]; seedId?: string; repos: string[]; frameId: string; depth: 'quick' | 'standard' | 'deep'; engine?: string; model?: string; effort?: string; nodeTarget?: number; steering?: string; } export interface IdeasJob { id: string; status: IdeasJobStatus; createdAt: string; updatedAt: string; cwd: string; pid?: number; plan: IdeasJobPlan; jobPath: string; logPath: string; runIds?: string[]; batchId?: string; dotCount?: number; error?: string; } export interface StartIdeasJobOptions { cwd?: string; env?: NodeJS.ProcessEnv; spawnImpl?: typeof spawn; } ``` -------------------------------- ### BookmarkFolder, BookmarkCacheMeta, XOAuthTokenSet, and BookmarkBackfillState interfaces Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/types.md Interfaces for folder management, cache metadata, OAuth tokens, and backfill state tracking. ```ts export interface BookmarkFolder { id: string; name: string; } export interface BookmarkCacheMeta { provider: 'twitter'; schemaVersion: number; lastFullSyncAt?: string; lastIncrementalSyncAt?: string; totalBookmarks: number; } export interface XOAuthTokenSet { access_token: string; refresh_token?: string; expires_in?: number; scope?: string; token_type?: string; obtained_at: string; } export interface BookmarkBackfillState { provider: 'twitter'; lastRunAt?: string; totalRuns: number; totalAdded: number; lastAdded: number; lastSeenIds: string[]; stopReason?: string; /** Saved pagination cursor for resuming an interrupted sync. */ lastCursor?: string; } ``` -------------------------------- ### buildCli() Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/cli.md Creates and returns the root commander Command named ft. It runs a one-time ideas-data migration and prints migration notices to stderr. The returned Command is used to parse command-line arguments. ```APIDOC ## buildCli() ### Description Creates and returns the root commander Command named ft. As a side effect, it runs the one-time ideas-data migration and prints migration notices to stderr. The returned Command object is normally used to parse command-line arguments. ### Method Function call ### Endpoint buildCli() ### Parameters None ### Request Example ```ts import { buildCli } from 'fieldtheory/dist/cli.js'; const program = buildCli(); program.hook('postAction', ...); await program.parseAsync(process.argv); ``` ### Response #### Success Response Returns a commander Command instance. #### Response Example ```ts const program = buildCli(); ``` ``` -------------------------------- ### Configure Proxy and Retrieve Agent Context Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/misc.md Initializes the HTTP proxy from environment variables and retrieves the agent context after a user confirmation prompt. ```ts import { configureHttpProxyFromEnv } from 'fieldtheory/dist/http-proxy.js'; import { promptText } from 'fieldtheory/dist/prompt.js'; import { getAgentContext } from 'fieldtheory/dist/agent-context.js'; configureHttpProxyFromEnv(); // at process start const answer = await promptText('Continue? (y/n) '); if (answer.kind === 'answer' && answer.value === 'y') { console.log(JSON.stringify(getAgentContext(process.cwd(), 5), null, 2)); } ``` -------------------------------- ### GET https://api.github.com/repos/afar1/field-releases/releases/latest Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/endpoints.md Fetches the latest Field Theory Mac app release from GitHub. Requires accept header and User-Agent, optional bearer token. ```APIDOC ## GET https://api.github.com/repos/afar1/field-releases/releases/latest ### Description Fetches the latest Field Theory Mac app release from GitHub. ### Method GET ### Endpoint https://api.github.com/repos/afar1/field-releases/releases/latest ### Headers - **Accept** (string) - Required - `application/vnd.github+json` - **User-Agent** (string) - Required - `fieldtheory-cli` - **Authorization** (string) - Optional - Bearer token from `GITHUB_TOKEN` or `GH_TOKEN`. ### Response #### Success Response (200) Returns release information including asset download URLs. #### Error Response - `Fetching latest Field Theory release failed: HTTP ` - `Downloading Field Theory DMG failed: HTTP ` - `Downloading Field Theory DMG failed: empty response body` ``` -------------------------------- ### buildSurveyPrompt Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/adjacent-prompts.md Builds a prompt for the Survey stage. Takes a SurveyInput containing a seed brief, repo tree, recent files, optional file excerpts, and a depth budget. Returns a string prompt. ```APIDOC ## buildSurveyPrompt ### Description Builds a prompt for the Survey stage. Takes a SurveyInput containing a seed brief, repo tree, recent files, optional file excerpts, and a depth budget. Returns a string prompt. ### Function Signature ```ts export function buildSurveyPrompt(input: SurveyInput): string ``` ### Parameters - **input** (SurveyInput) - Required - The input containing seed brief, repo tree, recent files, file excerpts, and budget. ### SurveyInput ```ts export interface SurveyInput { seedBrief: SeedBriefParsed; repoTree: string; recentFiles: string[]; fileExcerpts?: Array<{ path: string; text: string }>; budget: DepthBudget; } ``` ### Behavior - File tree is sanitized to 3000 chars. - Recent files capped at 20. - Excerpts capped at 8 (900 chars each). ### Output Contract Returns a string prompt that expects a JSON array of objects with the following fields: - `path` (string) - `description` (string) - `relevance` (string) - `workKind` (string) - one of: `new feature`, `refactor`, `integration`, `experiment`, `research` - 5-8 surfaces expected. ### SurfaceEntry ```ts export interface SurfaceEntry { path: string; description: string; relevance: string; workKind: string; } ``` ``` -------------------------------- ### stepPickRepos Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Prompts the user to select repositories from the registry and paths. It is an async step in the wizard. ```APIDOC ## stepPickRepos ### Description Prompts the user to select repositories from the registry and paths. It is an async step in the wizard. ### Method Function ### Signature `stepPickRepos(): Promise` ### Parameters None ### Returns Promise - Resolves when the step completes. ### Usage Example ```ts import { stepPickRepos } from 'fieldtheory/dist/possible-wizard.js'; await stepPickRepos(); ``` ``` -------------------------------- ### GET Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/endpoints.md Local OAuth callback server endpoint. Returns 200 with a success message when state matches and a code is present, 400 on error, and 404 for other paths. ```APIDOC ## GET ### Description Local OAuth callback server endpoint. Handles the OAuth callback from X. ### Method GET ### Endpoint (default `/callback`) ### Parameters #### Query Parameters - **state** (string) - Required - Must match the expected state. - **code** (string) - Required - Authorization code. - **error** (string) - Optional - Error code if OAuth failed. ### Response #### Success Response (200) Returns `ft auth complete. You can close this tab.` #### Error Response (400) Returns `OAuth error: ` if `error` param present, or `Invalid OAuth callback` otherwise. #### Error Response (404) Returns 404 for any other path. ``` -------------------------------- ### GET https://x.com/i/oauth2/authorize Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/endpoints.md PKCE authorize URL built by buildTwitterOAuthUrl. Used to initiate the OAuth flow for X (Twitter) with response_type=code, scope=tweet.read users.read bookmark.read offline.access, and code_challenge_method=S256. ```APIDOC ## GET https://x.com/i/oauth2/authorize ### Description PKCE authorize URL built by buildTwitterOAuthUrl. Used to initiate the OAuth flow for X (Twitter). ### Method GET ### Endpoint https://x.com/i/oauth2/authorize ### Parameters #### Query Parameters - **response_type** (string) - Required - Must be `code` - **scope** (string) - Required - `tweet.read users.read bookmark.read offline.access` - **code_challenge_method** (string) - Required - `S256` ### Response #### Success Response (200) Redirects to the callback URL with a `code` parameter. #### Error Response (400) Redirects to the callback URL with an `error` parameter. ``` -------------------------------- ### SyncOptions Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-sync.md Configuration options for the GraphQL bookmark sync operation. Allows controlling incremental sync, pagination, delays, browser profile selection, and progress callbacks. ```APIDOC ## SyncOptions ### Description Configuration interface for the GraphQL bookmark sync operation. ### Properties - **incremental** (boolean) - Optional - Default true. Stop once we reach the newest already-stored bookmark. - **maxPages** (number) - Optional - Max pages to fetch (20 bookmarks per page). Default: unlimited - **targetAdds** (number) - Optional - Stop once this many *new* bookmarks have been added. Default: unlimited - **delayMs** (number) - Optional - Delay between page requests in ms. Default: 600 - **maxMinutes** (number) - Optional - Max runtime in minutes. Default: 30 - **stalePageLimit** (number) - Optional - Consecutive pages with 0 new bookmarks before stopping. Default: 3 - **staleWhenNoNewRecords** (boolean) - Optional - Count old pages as stale when they add no new local records. - **pageSize** (number) - Optional - Bookmarks per page (1-100). Default: 20 - **browser** (string) - Optional - Browser id (e.g. 'chrome', 'firefox', 'brave'). - **chromeUserDataDir** (string) - Optional - Chrome-family user-data-dir override. - **chromeProfileDirectory** (string) - Optional - Chrome-family profile directory name (e.g. "Default"). - **firefoxProfileDir** (string) - Optional - Firefox profile directory override. - **csrfToken** (string) - Optional - Direct csrf token override; skips all cookie extraction. - **cookieHeader** (string) - Optional - Direct cookie header override; skips all cookie extraction. - **onProgress** (function) - Optional - Progress callback receiving SyncProgress status. - **resumeCursor** (string) - Optional - Resume from a saved cursor instead of starting from the newest bookmark. - **checkpointEvery** (number) - Optional - Flush to disk every N pages. Default: 25 - **signal** (AbortSignal) - Optional - Stop at the next safe loop boundary, then persist final state. ### Example ```ts const options: SyncOptions = { incremental: true, maxPages: 10, delayMs: 600, browser: 'chrome', onProgress: (status) => console.log(status) }; ``` ``` -------------------------------- ### buildNavigationWikiLink(target, alias?) Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/misc.md Builds a wiki link for the given target with an optional alias. ```APIDOC ## buildNavigationWikiLink(target, alias?) ### Description Builds a wiki link for the given target with an optional alias. ### Parameters - **target** (string) - Required - The target of the navigation document. - **alias** (string) - Optional - The alias for the link. ### Returns - **string** - The wiki link. ``` -------------------------------- ### GET http://:/health?token= Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/endpoints.md Browser helper health check endpoint. Used as a pre-flight probe before building the panel URL. Non-OK response results in an error. ```APIDOC ## GET http://:/health?token= ### Description Browser helper health check endpoint. Used as a pre-flight probe before building the panel URL. ### Method GET ### Endpoint http://:/health ### Parameters #### Query Parameters - **token** (string) - Required - Authentication token. ### Response #### Success Response (200) Indicates the browser helper is healthy. #### Error Response (non-200) Results in `Field Theory browser helper is not responding.` error. ``` -------------------------------- ### skillWithFrontmatter(): string Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Returns the full skill file content including YAML frontmatter with name and description fields. ```APIDOC ## skillWithFrontmatter(): string ### Description Returns the full skill file content including YAML frontmatter with name and description fields. ### Method skillWithFrontmatter() ### Returns - **string** - The complete skill file content with YAML frontmatter. ``` -------------------------------- ### browserHelperStatePath(): string Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/paths.md Returns the path to the browser-helper state file, honoring the FT_BROWSER_HELPER_STATE_PATH environment override, otherwise defaulting to ~/.fieldtheory/browser-helper.json. ```APIDOC ## browserHelperStatePath(): string ### Description Returns the path to the browser-helper state file. Honors the FT_BROWSER_HELPER_STATE_PATH environment override; otherwise defaults to ~/.fieldtheory/browser-helper.json. ### Returns - **string** - The resolved browser-helper state file path. ``` -------------------------------- ### enableBookmarks(): Promise Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-sync.md Enables bookmarks by running a GraphQL sync and building the index. Returns a result object with sync and indexing details. ```APIDOC ## enableBookmarks(): Promise ### Description Enables bookmarks by running a GraphQL sync and building the index. Returns a result object with sync and indexing details. ### Method Function ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **synced** (boolean) - Whether the sync completed. - **bookmarkCount** (number) - Number of bookmarks synced. - **indexedCount** (number) - Number of bookmarks indexed. - **cachePath** (string) - Path to the cache file. - **messageLines** (array of strings) - Informational messages. #### Response Example { "synced": true, "bookmarkCount": 100, "indexedCount": 95, "cachePath": "/path/to/cache", "messageLines": ["Sync completed", "Index built"] } ### Errors - None documented. ``` -------------------------------- ### detectAvailableEngines(): string[] Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/engine.md Returns the subset of available engines from the preference order ['claude', 'codex'] whose binaries are on PATH. ```APIDOC ## detectAvailableEngines(): string[] ### Description Returns the subset of `['claude', 'codex']` (preference order) whose binaries are on PATH. ### Returns - **string[]** - Array of engine names that are available on PATH, in preference order. ``` -------------------------------- ### loadNightlyLaunchAgent Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/ideas.md Loads the LaunchAgent for a schedule using launchctl bootout and bootstrap. Throws an error if the plist has not been written. ```APIDOC ## loadNightlyLaunchAgent ### Description Loads the LaunchAgent for a schedule using launchctl bootout and bootstrap. Throws an error if the plist has not been written. ### Signature loadNightlyLaunchAgent(schedule): { schedule; result: LaunchctlResult } ### Parameters - **schedule** (IdeasNightlySchedule) - Required - The schedule object. ### Returns - **object** - An object containing the schedule and the launchctl result. - **schedule** (IdeasNightlySchedule) - The schedule object. - **result** (LaunchctlResult) - The result of the launchctl command. ### Errors - Throws 'No LaunchAgent plist has been written for this schedule.' when launchAgent is missing. ``` -------------------------------- ### SyncOptions Interface Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-sync.md Defines the configuration parameters for the bookmark synchronization process, including browser settings, rate limiting, and incremental sync controls. ```ts export interface SyncOptions { /** Default true. Stop once we reach the newest already-stored bookmark. */ incremental?: boolean; /** Max pages to fetch (20 bookmarks per page). Default: unlimited */ maxPages?: number; /** Stop once this many *new* bookmarks have been added. Default: unlimited */ targetAdds?: number; /** Delay between page requests in ms. Default: 600 */ delayMs?: number; /** Max runtime in minutes. Default: 30 */ maxMinutes?: number; /** Consecutive pages with 0 new bookmarks before stopping. Default: 3 */ stalePageLimit?: number; /** Count old pages as stale when they add no new local records. */ staleWhenNoNewRecords?: boolean; /** Bookmarks per page (1–100). Default: 20 */ pageSize?: number; /** Browser id (e.g. 'chrome', 'firefox', 'brave'). */ browser?: string; /** Chrome-family user-data-dir override. */ chromeUserDataDir?: string; /** Chrome-family profile directory name (e.g. "Default"). */ chromeProfileDirectory?: string; /** Firefox profile directory override. */ firefoxProfileDir?: string; /** Direct csrf token override; skips all cookie extraction. */ csrfToken?: string; /** Direct cookie header override; skips all cookie extraction. */ cookieHeader?: string; /** Progress callback. */ onProgress?: (status: SyncProgress) => void; /** Resume from a saved cursor instead of starting from the newest bookmark. */ resumeCursor?: string; /** Flush to disk every N pages. Default: 25 */ checkpointEvery?: number; /** Stop at the next safe loop boundary, then persist final state. */ signal?: AbortSignal; } ``` -------------------------------- ### sampleByDomain Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-db.md Returns a random sample of bookmarks for a given domain. ```APIDOC ## sampleByDomain ### Description Retrieves a random sample of bookmarks from the specified domain. ### Signature sampleByDomain(domain: string, limit?: number, existingDb?: Database): Promise ### Parameters - **domain** (string) - Required - The domain to sample. - **limit** (number) - Optional - Maximum number of samples. - **existingDb** (Database) - Optional - An existing database connection. ### Returns Promise resolving to an array of CategorySample objects. ``` -------------------------------- ### Sync with cron Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Configure cron jobs to sync bookmarks or sync and classify them automatically. ```bash # Sync every morning at 7am 0 7 * * * ft sync # Sync and classify every morning 0 7 * * * ft sync --classify ``` -------------------------------- ### createCommandDocument Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Creates a new command document with a given name and input. Defaults to a template with sections for name, usage, steps, guardrails, and verification. Throws an error for invalid command names. ```APIDOC ## createCommandDocument(name: string, input: CommandWriteInput) ### Description Creates a new command document. If no content is provided, a default template is used. ### Method Function ### Signature createCommandDocument(name: string, input: CommandWriteInput): Promise ### Parameters #### Path Parameters - **name** (string) - Required - The name of the command document. #### Request Body - **stdin** (boolean) - Optional - Whether to read content from stdin. - **file** (string) - Optional - Path to a file containing content. - **content** (string) - Optional - Direct content for the document. ### Return Value - **Promise** - A promise resolving to the created command document. ### Errors - Throws `Invalid command name: ` if the name is invalid. ### Response Example { "path": "commands/example.md", "relPath": "example.md", "name": "example", "updatedAt": "2023-01-01T00:00:00Z", "size": 123, "content": "# example\n\nUse this when ...", "version": {} } ``` -------------------------------- ### RepoRun, DotEntry, and IdeasBatchSummary Interfaces Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/ideas.md Data structures for tracking individual repository runs, specific dot entries, and comprehensive batch summaries. ```ts export interface RepoRun { repo: string; runId: string; } export interface DotEntry { runId: string; repo: string; dotArtifactId: string; dot: Dot; } export interface IdeasBatchSummary { id: string; createdAt: string; seedId?: string; seedArtifactIds: string[]; frameId: string; frameName: string; depth: 'quick' | 'standard' | 'deep'; model: string; engine?: string; engineModel?: string; engineEffort?: string; nodeTarget?: number; steering?: string; /** Single source of truth for the repo→run pairing. */ repoRuns: RepoRun[]; totalDotCount: number; topDots: DotEntry[]; } ``` -------------------------------- ### ensureDataDir(): string Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/paths.md Creates the data directory with mode 0o700 if it does not exist, and returns the path. ```APIDOC ## ensureDataDir(): string ### Description Creates the data directory (dataDir()) with mode 0o700 if it does not exist, and returns the path. ### Returns - **string** - The data directory path. ``` -------------------------------- ### showCommandDocument Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/library.md Shows a single command document by target path. Returns a CommandDocument with content and version. ```APIDOC ## showCommandDocument(target: string) ### Description Retrieves a command document by its target path. ### Method Function ### Signature showCommandDocument(target: string): Promise ### Parameters #### Path Parameters - **target** (string) - Required - The path to the command document. ### Return Value - **Promise** - A promise resolving to the command document. ### Response Example { "path": "commands/example.md", "relPath": "example.md", "name": "example", "updatedAt": "2023-01-01T00:00:00Z", "size": 123, "content": "# example\n\nUse this when ...", "version": {} } ``` -------------------------------- ### runPossibleWizard Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Runs the full interactive wizard sequence for the 'ft possible' command. It prompts the user through all steps and invokes runIdeas with the assembled options. ```APIDOC ## runPossibleWizard ### Description Runs the full interactive wizard sequence for the 'ft possible' command. It prompts the user through all steps and invokes runIdeas with the assembled options. ### Method Function ### Signature `runPossibleWizard(): Promise` ### Parameters None ### Returns Promise - Resolves when the wizard completes. ### Usage Example ```ts import { runPossibleWizard } from 'fieldtheory/dist/possible-wizard.js'; await runPossibleWizard(); ``` ``` -------------------------------- ### openFieldTheoryTarget(target, options: FieldTheoryLaunchOptions = {}): FieldTheoryLaunchResult Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/app.md Launches the FieldTheory app for a given target. Uses environment-configured command, dev directory, or macOS bundle identifier with fallback precedence. ```APIDOC ## Function: openFieldTheoryTarget ### Description Launches the FieldTheory app for a given target. The launcher precedence is: FT_APP_OPEN_COMMAND , then FT_APP_DEV_DIR electron binary (override FT_APP_DEV_ELECTRON) with [devDir, url], then macOS open -b (bundle id from FT_APP_BUNDLE_ID or default com.fieldtheory.app). On non-darwin platforms, returns unsupported. ### Signature openFieldTheoryTarget(target: FieldTheoryOpenTarget, options: FieldTheoryLaunchOptions = {}): FieldTheoryLaunchResult ### Parameters - **target** (FieldTheoryOpenTarget) - Required - The target to launch. - **options** (FieldTheoryLaunchOptions) - Optional - Launch options including env, platform, and spawn runner. ### Returns - **FieldTheoryLaunchResult** - An object with launched (boolean) and method ('bundle' | 'dev-dir' | 'command' | 'unsupported'). ### Errors - Throws when the launcher exits non-zero or the bundle open fails, with a cause and remediation hints. ``` -------------------------------- ### Synchronize bookmarks and retrieve status Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/bookmarks-sync.md Demonstrates how to initiate a bookmark sync for a specific browser and retrieve the resulting status view. Cookie extraction failures will throw an Error, while network issues may surface via undici fetch or RateLimitError. ```ts import { syncBookmarksGraphQL } from 'fieldtheory/dist/graphql-bookmarks.js'; import { getBookmarkStatusView } from 'fieldtheory/dist/bookmarks-service.js'; const result = await syncBookmarksGraphQL({ browser: 'chrome', maxMinutes: 20, onProgress: (p) => console.error(`page ${p.page}: +${p.newAdded}`), }); console.log(formattedResult(result)); const view = await getBookmarkStatusView(); console.log(view.bookmarkCount, view.lastUpdated); ``` -------------------------------- ### stepConfirm Source: https://github.com/afar1/fieldtheory-cli/blob/main/_autodocs/api-reference/seeds.md Prompts the user to confirm the assembled plan before proceeding. It is an async step in the wizard. ```APIDOC ## stepConfirm ### Description Prompts the user to confirm the assembled plan before proceeding. It is an async step in the wizard. ### Method Function ### Signature `stepConfirm(): Promise` ### Parameters None ### Returns Promise - Resolves when the step completes. ### Usage Example ```ts import { stepConfirm } from 'fieldtheory/dist/possible-wizard.js'; await stepConfirm(); ``` ``` -------------------------------- ### Configure local Field Theory app development Source: https://github.com/afar1/fieldtheory-cli/blob/main/README.md Point the CLI to a local development checkout of the Mac app by setting the FT_APP_DEV_DIR environment variable before running library commands. ```bash export FT_APP_DEV_DIR=/Users/you/dev/fieldtheory/mac-app ft library open notes/example.md ```