@cleocode/core 2026.4.99 → 2026.4.100
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/dist/gc/daemon.js +481 -0
- package/dist/gc/daemon.js.map +7 -0
- package/dist/gc/index.js +669 -0
- package/dist/gc/index.js.map +7 -0
- package/dist/gc/runner.js +360 -0
- package/dist/gc/runner.js.map +7 -0
- package/dist/gc/state.js +49 -0
- package/dist/gc/state.js.map +7 -0
- package/dist/gc/transcript.js +209 -0
- package/dist/gc/transcript.js.map +7 -0
- package/dist/memory/brain-backfill.js +14643 -0
- package/dist/memory/brain-backfill.js.map +7 -0
- package/dist/memory/precompact-flush.js +47725 -0
- package/dist/memory/precompact-flush.js.map +7 -0
- package/dist/sentient/daemon.js +1100 -0
- package/dist/sentient/daemon.js.map +7 -0
- package/dist/sentient/index.js +1162 -0
- package/dist/sentient/index.js.map +7 -0
- package/dist/sentient/propose-tick.js +549 -0
- package/dist/sentient/propose-tick.js.map +7 -0
- package/dist/sentient/state.js +85 -0
- package/dist/sentient/state.js.map +7 -0
- package/dist/sentient/tick.js +396 -0
- package/dist/sentient/tick.js.map +7 -0
- package/dist/system/platform-paths.js +36 -0
- package/dist/system/platform-paths.js.map +7 -0
- package/package.json +8 -8
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/sentient/ingesters/brain-ingester.ts", "../../src/sentient/ingesters/nexus-ingester.ts", "../../src/sentient/ingesters/test-ingester.ts", "../../src/sentient/proposal-rate-limiter.ts", "../../src/sentient/state.ts", "../../src/sentient/propose-tick.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * BRAIN Ingester \u2014 Tier-2 proposal candidate source.\n *\n * Queries brain.db for recurring-pain observations (citation_count >= 3,\n * last 7 days, quality_score >= 0.5) and returns ranked ProposalCandidate[].\n *\n * Design principles:\n * - NO LLM calls. All data comes from structured SQL queries.\n * - Title is template-generated: `[T2-BRAIN] Recurring issue: {title}`.\n * This is the prompt-injection defence from T1008 \u00A73.6.\n * - Failures are swallowed: returns empty array + logs warning.\n * Brain.db absence must never crash the propose tick.\n *\n * @task T1008\n * @see ADR-054 \u2014 Sentient Loop Tier-2\n */\n\nimport type { DatabaseSync } from 'node:sqlite';\nimport type { ProposalCandidate } from '@cleocode/contracts';\n\n// ---------------------------------------------------------------------------\n// Brain observation row (raw SQL result)\n// ---------------------------------------------------------------------------\n\ninterface BrainObservationRow {\n id: string;\n title: string | null;\n text: string;\n citation_count: number;\n quality_score: number;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Maximum candidates returned from a single brain ingester pass. */\nexport const BRAIN_INGESTER_LIMIT = 10;\n\n/** Minimum citation count for a brain entry to be considered. */\nexport const BRAIN_MIN_CITATION_COUNT = 3;\n\n/** Minimum quality score for a brain entry to be considered. */\nexport const BRAIN_MIN_QUALITY_SCORE = 0.5;\n\n/** Lookback window in days for brain observations. */\nexport const BRAIN_LOOKBACK_DAYS = 7;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute candidate weight from citation_count and quality_score.\n * Formula: `(citation_count / 10) * quality_score` capped at 1.0.\n */\nexport function computeBrainWeight(citationCount: number, qualityScore: number): number {\n return Math.min((citationCount / 10) * qualityScore, 1.0);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run the BRAIN ingester against the provided DatabaseSync handle.\n *\n * Returns at most {@link BRAIN_INGESTER_LIMIT} candidates, sorted by weight\n * descending. Returns an empty array if the database has no matching entries\n * or if any error occurs (errors are swallowed to never crash the tick).\n *\n * @param nativeDb - Open DatabaseSync handle to brain.db. May be null if\n * brain.db has not been initialised; this is treated as zero candidates.\n * @returns Ranked ProposalCandidate array (may be empty).\n */\nexport function runBrainIngester(nativeDb: DatabaseSync | null): ProposalCandidate[] {\n if (!nativeDb) {\n return [];\n }\n\n try {\n const stmt = nativeDb.prepare(`\n SELECT id, title, text, citation_count, quality_score\n FROM brain_observations\n WHERE type IN ('bugfix', 'decision')\n AND citation_count >= :minCitations\n AND created_at >= datetime('now', :lookback)\n AND quality_score >= :minQuality\n ORDER BY citation_count DESC, quality_score DESC\n LIMIT :limit\n `);\n\n const rows = stmt.all({\n minCitations: BRAIN_MIN_CITATION_COUNT,\n lookback: `-${BRAIN_LOOKBACK_DAYS} days`,\n minQuality: BRAIN_MIN_QUALITY_SCORE,\n limit: BRAIN_INGESTER_LIMIT,\n }) as unknown as BrainObservationRow[];\n\n const candidates: ProposalCandidate[] = rows.map((row) => {\n const label = row.title ?? row.text.slice(0, 80);\n return {\n source: 'brain' as const,\n sourceId: row.id,\n title: `[T2-BRAIN] Recurring issue: ${label}`,\n rationale: `Brain entry ${row.id} cited ${row.citation_count} times (quality ${row.quality_score.toFixed(2)}) in the last ${BRAIN_LOOKBACK_DAYS} days`,\n weight: computeBrainWeight(row.citation_count, row.quality_score),\n };\n });\n\n // Sort descending by weight (DB ORDER BY handles primary sort, but\n // weight formula may produce different ordering than raw column order).\n candidates.sort((a, b) => b.weight - a.weight);\n\n return candidates;\n } catch (err) {\n // Best-effort: log warning but never throw from an ingester.\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[sentient/brain-ingester] WARNING: ${message}\\n`);\n return [];\n }\n}\n", "/**\n * Nexus Ingester \u2014 Tier-2 proposal candidate source.\n *\n * Queries nexus.db for structural anomalies and returns ranked\n * ProposalCandidate[]. Two query patterns:\n *\n * A. Orphaned callees: functions that have many callers but make no calls\n * themselves (zero-import, high-in-degree). Suggests dead-end sinks\n * that may be candidates for abstraction or documentation.\n *\n * B. Over-coupled nodes: symbols with total degree (in + out edges) > 20,\n * suggesting high coupling that should be refactored.\n *\n * Design principles:\n * - NO LLM calls. All data comes from structured SQL queries.\n * - Title is template-generated: `[T2-NEXUS] ...`. Prompt-injection defence.\n * - Failures are swallowed: returns empty array + logs warning.\n * Nexus.db absence must never crash the propose tick.\n *\n * @task T1008\n * @see ADR-054 \u2014 Sentient Loop Tier-2\n */\n\nimport type { DatabaseSync } from 'node:sqlite';\nimport type { ProposalCandidate } from '@cleocode/contracts';\n\n// ---------------------------------------------------------------------------\n// Raw row types\n// ---------------------------------------------------------------------------\n\ninterface OrphanCalleeRow {\n id: string;\n name: string;\n file_path: string;\n caller_count: number;\n}\n\ninterface HighDegreeRow {\n id: string;\n name: string;\n file_path: string;\n degree: number;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Base weight for all nexus candidates (structural signals, lower priority than brain). */\nexport const NEXUS_BASE_WEIGHT = 0.3;\n\n/** Minimum caller count for orphaned-callee detection. */\nexport const NEXUS_MIN_CALLER_COUNT = 5;\n\n/** Minimum total degree for over-coupling detection. */\nexport const NEXUS_MIN_DEGREE = 20;\n\n/** Maximum results per query. */\nexport const NEXUS_QUERY_LIMIT = 5;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute a deduplication key that is stable across query A and query B.\n * Both queries reference the same nexus node table, so using the node id\n * directly as sourceId is sufficient.\n */\nfunction toFingerprint(nodeId: string): string {\n return nodeId;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run the Nexus ingester against the provided DatabaseSync handle.\n *\n * Returns candidates from both orphaned-callee (Query A) and high-degree\n * (Query B) detection, merged without duplication. Returns an empty array\n * if the database has no matching entries or if any error occurs.\n *\n * @param nativeDb - Open DatabaseSync handle to nexus.db. May be null if\n * nexus.db has not been initialised; this is treated as zero candidates.\n * @returns Ranked ProposalCandidate array (may be empty).\n */\nexport function runNexusIngester(nativeDb: DatabaseSync | null): ProposalCandidate[] {\n if (!nativeDb) {\n return [];\n }\n\n const seenIds = new Set<string>();\n const candidates: ProposalCandidate[] = [];\n\n try {\n // Query A: orphaned callees (many callers, zero outbound calls).\n const stmtA = nativeDb.prepare(`\n SELECT n.id, n.name, n.file_path, COUNT(r.id) as caller_count\n FROM nexus_nodes n\n JOIN nexus_relations r ON r.target_id = n.id AND r.kind = 'calls'\n WHERE NOT EXISTS (\n SELECT 1 FROM nexus_relations r2\n WHERE r2.source_id = n.id AND r2.kind = 'calls'\n )\n AND n.kind = 'function'\n GROUP BY n.id\n HAVING caller_count > :minCallers\n ORDER BY caller_count DESC\n LIMIT :limit\n `);\n\n const rowsA = stmtA.all({\n minCallers: NEXUS_MIN_CALLER_COUNT,\n limit: NEXUS_QUERY_LIMIT,\n }) as unknown as OrphanCalleeRow[];\n\n for (const row of rowsA) {\n const fp = toFingerprint(row.id);\n if (seenIds.has(fp)) continue;\n seenIds.add(fp);\n candidates.push({\n source: 'nexus' as const,\n sourceId: row.id,\n title: `[T2-NEXUS] Over-coupled symbol: ${row.name} (${row.caller_count} callers)`,\n rationale: `Function ${row.name} in ${row.file_path} has ${row.caller_count} callers but makes no outbound calls \u2014 review for abstraction opportunity`,\n weight: NEXUS_BASE_WEIGHT,\n });\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[sentient/nexus-ingester] WARNING query A: ${message}\\n`);\n }\n\n try {\n // Query B: high-degree nodes (over-coupling).\n const stmtB = nativeDb.prepare(`\n SELECT n.id, n.name, n.file_path, COUNT(r.id) as degree\n FROM nexus_nodes n\n JOIN nexus_relations r ON r.source_id = n.id OR r.target_id = n.id\n GROUP BY n.id\n HAVING degree > :minDegree\n ORDER BY degree DESC\n LIMIT :limit\n `);\n\n const rowsB = stmtB.all({\n minDegree: NEXUS_MIN_DEGREE,\n limit: NEXUS_QUERY_LIMIT,\n }) as unknown as HighDegreeRow[];\n\n for (const row of rowsB) {\n const fp = toFingerprint(row.id);\n if (seenIds.has(fp)) continue;\n seenIds.add(fp);\n candidates.push({\n source: 'nexus' as const,\n sourceId: row.id,\n title: `[T2-NEXUS] Over-coupled symbol: ${row.name} (${row.degree} edges)`,\n rationale: `Symbol ${row.name} in ${row.file_path} has ${row.degree} total edges \u2014 review for over-coupling`,\n weight: NEXUS_BASE_WEIGHT,\n });\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[sentient/nexus-ingester] WARNING query B: ${message}\\n`);\n }\n\n return candidates;\n}\n", "/**\n * Test Ingester \u2014 Tier-2 proposal candidate source.\n *\n * Reads two data sources:\n *\n * Source A \u2014 `.cleo/audit/gates.jsonl`: CLEO evidence gate failure records.\n * Each line is a JSONL record. Lines where `failCount > 0` produce a\n * proposal suggesting a flaky-test guard be added for the failing task.\n *\n * Source B \u2014 `.cleo/coverage-summary.json`: vitest coverage JSON summary.\n * Written by `vitest --coverage --reporter json-summary`. Lines where\n * `lines.pct < 80` produce a proposal suggesting coverage improvement.\n * If the file is absent, Source B returns zero candidates (no error).\n *\n * Design principles:\n * - NO LLM calls. All data comes from structured file reads.\n * - Title is template-generated. Prompt-injection defence (T1008 \u00A73.6).\n * - Failures are swallowed: returns empty array + logs warning.\n *\n * @task T1008\n * @see ADR-054 \u2014 Sentient Loop Tier-2\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { ProposalCandidate } from '@cleocode/contracts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A single line from gates.jsonl. */\ninterface GateRecord {\n taskId?: string;\n gate?: string;\n failCount?: number;\n [key: string]: unknown;\n}\n\n/** Coverage summary entry for a single file. */\ninterface CoverageEntry {\n lines?: { pct?: number };\n statements?: { pct?: number };\n functions?: { pct?: number };\n branches?: { pct?: number };\n}\n\n/** Shape of the JSON coverage summary file. */\ntype CoverageSummary = Record<string, CoverageEntry>;\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Relative path from project root to gates.jsonl. */\nexport const GATES_JSONL_PATH = '.cleo/audit/gates.jsonl' as const;\n\n/** Relative path from project root to the coverage summary. */\nexport const COVERAGE_SUMMARY_PATH = '.cleo/coverage-summary.json' as const;\n\n/** Coverage line percentage below which a proposal is emitted. */\nexport const MIN_LINE_COVERAGE_PCT = 80;\n\n/** Base weight for all test ingester candidates. */\nexport const TEST_BASE_WEIGHT = 0.5;\n\n// ---------------------------------------------------------------------------\n// Source A: gates.jsonl\n// ---------------------------------------------------------------------------\n\n/**\n * Parse gates.jsonl and return one candidate per task that has any gate\n * with `failCount > 0`.\n *\n * @param projectRoot - Absolute path to the project root.\n * @returns Proposal candidates (may be empty).\n */\nfunction runGatesIngester(projectRoot: string): ProposalCandidate[] {\n const gatesPath = join(projectRoot, GATES_JSONL_PATH);\n\n let raw: string;\n try {\n raw = readFileSync(gatesPath, 'utf-8');\n } catch {\n // File absent or unreadable \u2014 not an error.\n return [];\n }\n\n const candidates: ProposalCandidate[] = [];\n const seenKeys = new Set<string>();\n\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let record: GateRecord;\n try {\n record = JSON.parse(trimmed) as GateRecord;\n } catch {\n // Skip malformed lines.\n continue;\n }\n\n const taskId = record.taskId;\n const gate = record.gate ?? 'unknown';\n const failCount = record.failCount ?? 0;\n\n if (typeof taskId !== 'string' || failCount <= 0) continue;\n\n const key = `${taskId}.${gate}`;\n if (seenKeys.has(key)) continue;\n seenKeys.add(key);\n\n candidates.push({\n source: 'test' as const,\n sourceId: key,\n title: `[T2-TEST] Fix flaky gate: ${taskId}.${gate}`,\n rationale: `Gate '${gate}' on task ${taskId} has failed ${failCount} time(s)`,\n weight: TEST_BASE_WEIGHT,\n });\n }\n\n return candidates;\n}\n\n// ---------------------------------------------------------------------------\n// Source B: coverage-summary.json\n// ---------------------------------------------------------------------------\n\n/**\n * Read the vitest coverage summary and return one candidate per file with\n * line coverage below {@link MIN_LINE_COVERAGE_PCT}.\n *\n * @param projectRoot - Absolute path to the project root.\n * @returns Proposal candidates (may be empty; empty if file absent).\n */\nfunction runCoverageIngester(projectRoot: string): ProposalCandidate[] {\n const coveragePath = join(projectRoot, COVERAGE_SUMMARY_PATH);\n\n let summary: CoverageSummary;\n try {\n const raw = readFileSync(coveragePath, 'utf-8');\n summary = JSON.parse(raw) as CoverageSummary;\n } catch {\n // File absent or malformed \u2014 not an error, return zero candidates.\n return [];\n }\n\n const candidates: ProposalCandidate[] = [];\n\n for (const [filePath, entry] of Object.entries(summary)) {\n // Skip the 'total' synthetic key if present.\n if (filePath === 'total') continue;\n\n const pct = entry?.lines?.pct;\n if (typeof pct !== 'number' || pct >= MIN_LINE_COVERAGE_PCT) continue;\n\n candidates.push({\n source: 'test' as const,\n sourceId: filePath,\n title: `[T2-TEST] Increase coverage: ${filePath} (${pct}% lines)`,\n rationale: `File ${filePath} has ${pct}% line coverage (target: ${MIN_LINE_COVERAGE_PCT}%)`,\n weight: TEST_BASE_WEIGHT,\n });\n }\n\n return candidates;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run the test ingester against both data sources.\n *\n * Merges Source A (gates.jsonl) and Source B (coverage-summary.json) without\n * duplication. Returns an empty array if both sources yield nothing or if\n * errors occur (errors are swallowed).\n *\n * @param projectRoot - Absolute path to the project root.\n * @returns Combined ProposalCandidate array (may be empty).\n */\nexport function runTestIngester(projectRoot: string): ProposalCandidate[] {\n try {\n const gatesCandidates = runGatesIngester(projectRoot);\n const coverageCandidates = runCoverageIngester(projectRoot);\n\n // Merge, deduplicate by sourceId.\n const seenSourceIds = new Set<string>();\n const merged: ProposalCandidate[] = [];\n\n for (const candidate of [...gatesCandidates, ...coverageCandidates]) {\n if (seenSourceIds.has(candidate.sourceId)) continue;\n seenSourceIds.add(candidate.sourceId);\n merged.push(candidate);\n }\n\n return merged;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[sentient/test-ingester] WARNING: ${message}\\n`);\n return [];\n }\n}\n", "/**\n * Proposal Rate Limiter \u2014 Transactional DB-enforced daily cap.\n *\n * Enforces a maximum of N proposals per day per source tag, using a\n * BEGIN IMMEDIATE transaction with COUNT + conditional INSERT pattern.\n *\n * Design rationale (T1008 \u00A73.2):\n * - In-process counters do not survive daemon restart, and two daemon\n * instances could both allow N/day if enforcement is not in the DB.\n * - The `sentient.lock` advisory lock (daemon.ts) prevents two daemons\n * from running concurrently, but the transactional count check provides\n * belt-and-suspenders protection against TOCTOU races.\n * - SQLite partial unique indexes cannot enforce count > 1, so the\n * BEGIN IMMEDIATE + COUNT + INSERT pattern is used instead.\n *\n * The \"day\" boundary is determined by SQLite's `date('now')` (UTC).\n * Proposals counted include ALL non-terminal statuses (proposed, pending,\n * active, done) \u2014 an accepted proposal still consumes a daily slot.\n *\n * @task T1008\n * @see ADR-054 \u2014 Sentient Loop Tier-2\n */\n\nimport type { DatabaseSync, SQLInputValue } from 'node:sqlite';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * The meta proposedBy tag written to `tasks.metadata_json` by the Tier-2\n * proposer. This tag is the query key for rate-limit counting.\n */\nexport const SENTIENT_TIER2_TAG = 'sentient-tier2' as const;\n\n/**\n * Default maximum number of Tier-2 proposals per UTC day.\n * Can be overridden by callers.\n */\nexport const DEFAULT_DAILY_PROPOSAL_LIMIT = 3;\n\n/**\n * SQL error code string returned when BEGIN IMMEDIATE fails because another\n * write transaction is in progress.\n */\nconst SQLITE_BUSY_CODE = 'SQLITE_BUSY';\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Count the number of Tier-2 proposals created today (UTC).\n *\n * Counts tasks where:\n * - `labels_json` contains `'sentient-tier2'` (the Tier-2 marker label)\n * - `date(created_at) = date('now')`\n * - `status IN ('proposed', 'pending', 'active', 'done')` \u2014 terminal\n * states that were proposed today still count toward the daily cap so\n * that accepted proposals don't free a slot for another proposal.\n *\n * The `LIKE` pattern is intentional: labels_json is a JSON array stored as\n * text, and `'sentient-tier2'` is always a complete JSON string value within\n * that array, making substring matching safe here.\n *\n * @param nativeDb - Open DatabaseSync handle to tasks.db.\n * @returns Number of proposals created today. Returns 0 if DB is null.\n */\nexport function countTodayProposals(nativeDb: DatabaseSync | null): number {\n if (!nativeDb) return 0;\n\n const stmt = nativeDb.prepare(`\n SELECT COUNT(*) as cnt\n FROM tasks\n WHERE labels_json LIKE :labelPattern\n AND date(created_at) = date('now')\n AND status IN ('proposed', 'pending', 'active', 'done')\n `);\n\n const row = stmt.get({ labelPattern: `%${SENTIENT_TIER2_TAG}%` }) as { cnt: number } | undefined;\n return row?.cnt ?? 0;\n}\n\n/**\n * Check whether the daily rate limit has been reached.\n *\n * @param nativeDb - Open DatabaseSync handle to tasks.db.\n * @param limit - Daily cap (defaults to {@link DEFAULT_DAILY_PROPOSAL_LIMIT}).\n * @returns `true` if the limit is reached or exceeded; `false` if capacity remains.\n */\nexport function isRateLimitExceeded(\n nativeDb: DatabaseSync | null,\n limit = DEFAULT_DAILY_PROPOSAL_LIMIT,\n): boolean {\n return countTodayProposals(nativeDb) >= limit;\n}\n\n// ---------------------------------------------------------------------------\n// Transactional INSERT guard\n// ---------------------------------------------------------------------------\n\n/** Result of a transactional insert attempt. */\nexport interface TransactionalInsertResult {\n /** Whether the INSERT was committed. */\n inserted: boolean;\n /**\n * The count read at the start of the transaction. Used for diagnostics\n * and tests \u2014 lets callers verify the guard saw the expected count.\n */\n countBeforeInsert: number;\n /**\n * If `inserted = false` and this is set, the limit was the reason.\n */\n reason?: 'rate-limit' | 'busy';\n}\n\n/**\n * Attempt to insert a pre-built task row inside a BEGIN IMMEDIATE transaction\n * with a count check.\n *\n * Steps:\n * 1. BEGIN IMMEDIATE (exclusive write lock on tasks.db)\n * 2. COUNT proposals created today\n * 3. If count >= limit: ROLLBACK, return `{ inserted: false, reason: 'rate-limit' }`\n * 4. Otherwise: INSERT the row, COMMIT, return `{ inserted: true }`\n *\n * On SQLITE_BUSY: ROLLBACK + return `{ inserted: false, reason: 'busy' }`.\n *\n * @param nativeDb - Open DatabaseSync handle to tasks.db.\n * @param insertSql - Parameterized INSERT SQL string.\n * @param insertParams - Named parameters for the INSERT statement.\n * @param limit - Daily cap.\n * @returns Insert result.\n */\nexport function transactionalInsertProposal(\n nativeDb: DatabaseSync,\n insertSql: string,\n insertParams: Record<string, SQLInputValue>,\n limit = DEFAULT_DAILY_PROPOSAL_LIMIT,\n): TransactionalInsertResult {\n try {\n nativeDb.exec('BEGIN IMMEDIATE');\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(SQLITE_BUSY_CODE)) {\n return { inserted: false, countBeforeInsert: 0, reason: 'busy' };\n }\n throw err;\n }\n\n try {\n const countBeforeInsert = countTodayProposals(nativeDb);\n\n if (countBeforeInsert >= limit) {\n nativeDb.exec('ROLLBACK');\n return { inserted: false, countBeforeInsert, reason: 'rate-limit' };\n }\n\n const stmt = nativeDb.prepare(insertSql);\n stmt.run(insertParams);\n\n nativeDb.exec('COMMIT');\n return { inserted: true, countBeforeInsert };\n } catch (err) {\n try {\n nativeDb.exec('ROLLBACK');\n } catch {\n // ignore rollback failure\n }\n throw err;\n }\n}\n", "/**\n * Sentient Loop State \u2014 Persistent state for the Tier-1 autonomous daemon.\n *\n * Stored in `.cleo/sentient-state.json` (plain JSON, not SQLite) to avoid\n * SQLite WAL conflicts between the long-running daemon process and the\n * main CLEO CLI process. Human-readable for debugging.\n *\n * The file is gitignored (see .gitignore \u00A7.cleo/ section) and survives\n * restarts. Only `killSwitch`, `pid`, and `stats` fields are load-bearing\n * across process boundaries.\n *\n * @see ADR-054 \u2014 Sentient Loop Tier-1 (autonomous task execution)\n * @task T946\n */\n\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { Tier2Stats } from '@cleocode/contracts';\n\n/** Schema version for sentient-state.json. Bump on breaking field changes. */\nexport const SENTIENT_STATE_SCHEMA_VERSION = '1.0' as const;\n\n/**\n * Per-task failure/backoff tracking for stuck detection.\n * Keyed by task id in {@link SentientState.stuckTasks}.\n */\nexport interface StuckTaskRecord {\n /** Number of consecutive failed spawn attempts for this task. */\n attempts: number;\n /** ISO-8601 timestamp of the most recent failure. */\n lastFailureAt: string;\n /** Unix epoch ms when the next retry becomes eligible. */\n nextRetryAt: number;\n /** Last captured failure reason (truncated to 500 chars). */\n lastReason: string;\n}\n\n/**\n * Rolling counters persisted across daemon restarts.\n */\nexport interface SentientStats {\n /** Total tasks picked by the loop since creation. */\n tasksPicked: number;\n /** Total tasks that completed successfully. */\n tasksCompleted: number;\n /** Total tasks whose spawn exited non-zero. */\n tasksFailed: number;\n /** Total ticks executed (including no-op ticks). */\n ticksExecuted: number;\n /** Total ticks aborted early because kill switch was active. */\n ticksKilled: number;\n}\n\n/**\n * Persistent sentient daemon state.\n *\n * Design principles:\n * - `killSwitch` is the single load-bearing kill signal \u2014 the daemon re-checks\n * it between every step of a tick, not just at tick start (Round 2 audit).\n * - `stuckTasks` keys are task ids; values encode backoff + failure counts.\n * - `stuckTimestamps` is a rolling 1-hour window used for the self-pause rule\n * (5 stucks in 1 hour \u2192 killSwitch=true).\n * - `stats` fields are monotonic counters that only ever increase.\n */\nexport interface SentientState {\n /** JSON schema version for forward-compatibility checks. */\n schemaVersion: typeof SENTIENT_STATE_SCHEMA_VERSION;\n /** PID of the currently running daemon process. null = daemon not running. */\n pid: number | null;\n /** ISO-8601 timestamp when the daemon was last started. */\n startedAt: string | null;\n /** ISO-8601 timestamp of the last completed tick (any outcome). */\n lastTickAt: string | null;\n /**\n * Kill-switch flag. When true, the daemon re-checks at every step of a tick\n * and exits cleanly without picking or spawning a task.\n */\n killSwitch: boolean;\n /** Reason supplied when killSwitch was last set (diagnostic only). */\n killSwitchReason: string | null;\n /** Rolling counters; see {@link SentientStats}. */\n stats: SentientStats;\n /** Per-task backoff + failure metadata for retry/stuck detection. */\n stuckTasks: Record<string, StuckTaskRecord>;\n /**\n * Unix-epoch-ms timestamps of `stuck` events within the last hour.\n * When length \u2265 5 the daemon self-pauses (killSwitch=true).\n */\n stuckTimestamps: number[];\n /**\n * Currently-active task id (set while a spawn is in-flight, cleared afterward).\n * Enables `status` to show the in-progress task during a long-running tick.\n */\n activeTaskId: string | null;\n /**\n * Tier-2 proposal queue enabled flag.\n *\n * Default: `false` \u2014 Tier 2 is OFF by default to prevent surprise proposal\n * floods on first daemon start. Owner enables via `cleo sentient propose enable`\n * (patches this flag). See ADR-054 \u00A7Tier-2.\n *\n * @task T1008\n */\n tier2Enabled: boolean;\n /**\n * Rolling counters for Tier-2 proposal activity.\n *\n * @task T1008\n */\n tier2Stats: Tier2Stats;\n}\n\n/** Default (empty) sentient state for fresh initialisation. */\nexport const DEFAULT_SENTIENT_STATE: SentientState = {\n schemaVersion: SENTIENT_STATE_SCHEMA_VERSION,\n pid: null,\n startedAt: null,\n lastTickAt: null,\n killSwitch: false,\n killSwitchReason: null,\n stats: {\n tasksPicked: 0,\n tasksCompleted: 0,\n tasksFailed: 0,\n ticksExecuted: 0,\n ticksKilled: 0,\n },\n stuckTasks: {},\n stuckTimestamps: [],\n activeTaskId: null,\n tier2Enabled: false,\n tier2Stats: {\n proposalsGenerated: 0,\n proposalsAccepted: 0,\n proposalsRejected: 0,\n },\n};\n\n/**\n * Read the sentient state from disk.\n *\n * Returns the default state if the file does not exist or is malformed.\n * Never throws \u2014 absence is not an error.\n *\n * @param statePath - Absolute path to sentient-state.json\n */\nexport async function readSentientState(statePath: string): Promise<SentientState> {\n try {\n const raw = await readFile(statePath, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<SentientState>;\n return {\n ...DEFAULT_SENTIENT_STATE,\n ...parsed,\n stats: { ...DEFAULT_SENTIENT_STATE.stats, ...(parsed.stats ?? {}) },\n stuckTasks: parsed.stuckTasks ?? {},\n stuckTimestamps: parsed.stuckTimestamps ?? [],\n tier2Enabled: parsed.tier2Enabled ?? false,\n tier2Stats: { ...DEFAULT_SENTIENT_STATE.tier2Stats, ...(parsed.tier2Stats ?? {}) },\n };\n } catch {\n return { ...DEFAULT_SENTIENT_STATE };\n }\n}\n\n/**\n * Write the sentient state to disk atomically via tmp-then-rename.\n *\n * Atomic write prevents partial reads if the daemon crashes mid-write.\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param state - State to persist\n */\nexport async function writeSentientState(statePath: string, state: SentientState): Promise<void> {\n const dir = dirname(statePath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.sentient-state-${process.pid}.tmp`);\n const json = JSON.stringify(state, null, 2);\n\n await writeFile(tmpPath, json, 'utf-8');\n await rename(tmpPath, statePath);\n}\n\n/**\n * Patch a subset of fields in the sentient state file.\n *\n * Reads current state, merges patch, writes back. Nested `stats` merges\n * with existing stats (never clobbered wholesale).\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param patch - Partial state to merge over the existing state\n * @returns The merged state that was written to disk.\n */\nexport async function patchSentientState(\n statePath: string,\n patch: Partial<SentientState>,\n): Promise<SentientState> {\n const current = await readSentientState(statePath);\n const updated: SentientState = {\n ...current,\n ...patch,\n stats: { ...current.stats, ...(patch.stats ?? {}) },\n };\n await writeSentientState(statePath, updated);\n return updated;\n}\n\n/**\n * Increment stats counters atomically.\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param delta - Partial stats to add to current counters\n */\nexport async function incrementStats(\n statePath: string,\n delta: Partial<SentientStats>,\n): Promise<SentientState> {\n const current = await readSentientState(statePath);\n const nextStats: SentientStats = {\n tasksPicked: current.stats.tasksPicked + (delta.tasksPicked ?? 0),\n tasksCompleted: current.stats.tasksCompleted + (delta.tasksCompleted ?? 0),\n tasksFailed: current.stats.tasksFailed + (delta.tasksFailed ?? 0),\n ticksExecuted: current.stats.ticksExecuted + (delta.ticksExecuted ?? 0),\n ticksKilled: current.stats.ticksKilled + (delta.ticksKilled ?? 0),\n };\n const updated: SentientState = { ...current, stats: nextStats };\n await writeSentientState(statePath, updated);\n return updated;\n}\n", "/**\n * Sentient Loop Propose Tick \u2014 Single-pass Tier-2 proposal generator.\n *\n * Runs inside the daemon cron (every 2 hours) or standalone via\n * `cleo sentient propose run`. Orchestrates the three ingesters,\n * deduplicates candidates by fingerprint, applies the DB-enforced\n * rate limit, and writes accepted candidates as tasks with\n * `status='proposed'` and labels including `'sentient-tier2'`.\n *\n * Scoped IN:\n * - Ingest from brain.db, nexus.db, and .cleo/audit/gates.jsonl\n * - Transactional rate-limit check (BEGIN IMMEDIATE + COUNT + INSERT)\n * - Kill-switch re-check at each checkpoint (Round 2 audit \u00A79)\n * - tier2Enabled guard (default false \u2014 owner opt-in)\n *\n * Scoped OUT:\n * - LLM calls (NONE \u2014 all proposal titles are structured templates)\n * - Tier-3 sandbox/merge (blocked on T992+T993+T995)\n *\n * Title format enforcement:\n * All proposal titles MUST match `/^\\[T2-(BRAIN|NEXUS|TEST)\\]/`.\n * This is the prompt-injection defence from T1008 \u00A73.6 \u2014 no freeform\n * LLM text can enter the task title column from the Tier-2 proposer.\n *\n * @task T1008\n * @see ADR-054 \u2014 Sentient Loop Tier-2\n */\n\nimport type { ProposalCandidate } from '@cleocode/contracts';\nimport { runBrainIngester } from './ingesters/brain-ingester.js';\nimport { runNexusIngester } from './ingesters/nexus-ingester.js';\nimport { runTestIngester } from './ingesters/test-ingester.js';\nimport {\n countTodayProposals,\n DEFAULT_DAILY_PROPOSAL_LIMIT,\n transactionalInsertProposal,\n} from './proposal-rate-limiter.js';\nimport { patchSentientState, readSentientState } from './state.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Regex that ALL proposal titles MUST match.\n * Enforces structured-template-only output (no freeform LLM text).\n */\nexport const PROPOSAL_TITLE_PATTERN = /^\\[T2-(BRAIN|NEXUS|TEST)\\]/;\n\n/**\n * Label applied to every Tier-2 proposal task.\n * Used by the rate limiter to identify proposals.\n */\nexport const TIER2_LABEL = 'sentient-tier2';\n\n// ---------------------------------------------------------------------------\n// Outcome types\n// ---------------------------------------------------------------------------\n\n/** Discriminant for the propose-tick outcome. */\nexport type ProposalTickOutcomeKind =\n | 'killed' // killSwitch active\n | 'disabled' // tier2Enabled = false\n | 'rate-limited' // daily cap already reached\n | 'no-candidates' // all ingesters returned empty\n | 'wrote' // at least one proposal was written\n | 'error'; // unexpected error\n\n/** Structured outcome of a single propose-tick pass. */\nexport interface ProposeTickOutcome {\n /** Discriminant describing how the tick ended. */\n kind: ProposalTickOutcomeKind;\n /** Number of proposals written in this pass. */\n written: number;\n /** Current daily proposal count at the end of the pass. */\n count: number;\n /** Human-readable detail (one line). */\n detail: string;\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for {@link runProposeTick}. */\nexport interface ProposeTickOptions {\n /** Absolute path to the project root (contains `.cleo/`). */\n projectRoot: string;\n /** Absolute path to sentient-state.json. */\n statePath: string;\n /**\n * Override for the brain DB handle. Injected by tests to avoid\n * opening a real brain.db. When omitted the real getBrainNativeDb() is used.\n */\n brainDb?: import('node:sqlite').DatabaseSync | null;\n /**\n * Override for the nexus DB handle. Injected by tests.\n * When omitted the real getNexusNativeDb() is used.\n */\n nexusDb?: import('node:sqlite').DatabaseSync | null;\n /**\n * Override for the tasks DB handle (used by rate limiter + INSERT).\n * Injected by tests. When omitted the real getNativeTasksDb() is used.\n */\n tasksDb?: import('node:sqlite').DatabaseSync | null;\n /**\n * Override the task ID allocator. Injected by tests.\n * When omitted the real allocateNextTaskId() is used.\n */\n allocateTaskId?: () => Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute a deduplication fingerprint for a candidate.\n * Two candidates with the same source + sourceId are considered identical.\n */\nfunction fingerprint(candidate: ProposalCandidate): string {\n return `${candidate.source}:${candidate.sourceId}`;\n}\n\n/**\n * Check whether the kill switch is currently active.\n */\nasync function killSwitchActive(statePath: string): Promise<boolean> {\n const state = await readSentientState(statePath);\n return state.killSwitch === true;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Run a single Tier-2 propose pass.\n *\n * Steps:\n * 1. Check killSwitch \u2192 abort if true\n * 2. Check tier2Enabled \u2192 abort if false\n * 3. Run all three ingesters in parallel\n * 4. Check killSwitch again (post-ingest checkpoint)\n * 5. Merge + deduplicate candidates by fingerprint\n * 6. Validate title format (must match PROPOSAL_TITLE_PATTERN)\n * 7. Score + take top-N candidates (N = limit - countTodayProposals)\n * 8. Check killSwitch again (pre-write checkpoint)\n * 9. For each candidate: transactional INSERT into tasks.db\n * 10. Update tier2Stats in state\n *\n * @param options - Propose tick options (see {@link ProposeTickOptions})\n * @returns Structured outcome describing how the pass ended.\n */\nexport async function runProposeTick(options: ProposeTickOptions): Promise<ProposeTickOutcome> {\n const { projectRoot, statePath } = options;\n\n // Checkpoint 1: killSwitch before any work\n if (await killSwitchActive(statePath)) {\n return { kind: 'killed', written: 0, count: 0, detail: 'killSwitch active before ingest' };\n }\n\n // Check tier2Enabled guard\n const state = await readSentientState(statePath);\n if (!state.tier2Enabled) {\n return {\n kind: 'disabled',\n written: 0,\n count: 0,\n detail: 'tier2Enabled=false; enable via cleo sentient propose enable',\n };\n }\n\n // Resolve DB handles\n let brainDb: import('node:sqlite').DatabaseSync | null;\n let nexusDb: import('node:sqlite').DatabaseSync | null;\n let tasksNativeDb: import('node:sqlite').DatabaseSync | null;\n\n if (options.brainDb !== undefined) {\n brainDb = options.brainDb;\n } else {\n // Ensure brain.db is initialized before calling getBrainNativeDb\n try {\n const { getBrainDb, getBrainNativeDb } = await import('@cleocode/core/internal');\n await getBrainDb(projectRoot);\n brainDb = getBrainNativeDb();\n } catch {\n brainDb = null;\n }\n }\n\n if (options.nexusDb !== undefined) {\n nexusDb = options.nexusDb;\n } else {\n try {\n const { getNexusNativeDb } = await import('@cleocode/core/internal');\n nexusDb = getNexusNativeDb();\n } catch {\n nexusDb = null;\n }\n }\n\n if (options.tasksDb !== undefined) {\n tasksNativeDb = options.tasksDb;\n } else {\n const { getNativeDb, getDb } = await import('@cleocode/core/internal');\n // Ensure tasks.db is initialized\n await getDb(projectRoot);\n tasksNativeDb = getNativeDb();\n }\n\n // Run all three ingesters in parallel\n const [brainCandidates, nexusCandidates, testCandidates] = await Promise.all([\n Promise.resolve(runBrainIngester(brainDb)),\n Promise.resolve(runNexusIngester(nexusDb)),\n Promise.resolve(runTestIngester(projectRoot)),\n ]);\n\n // Checkpoint 2: killSwitch after ingest\n if (await killSwitchActive(statePath)) {\n return {\n kind: 'killed',\n written: 0,\n count: 0,\n detail: 'killSwitch active after ingest phase',\n };\n }\n\n // Merge + deduplicate by fingerprint\n const seenFingerprints = new Set<string>();\n const merged: ProposalCandidate[] = [];\n\n for (const candidate of [...brainCandidates, ...nexusCandidates, ...testCandidates]) {\n // Validate title format \u2014 reject candidates with non-template titles\n if (!PROPOSAL_TITLE_PATTERN.test(candidate.title)) {\n process.stderr.write(\n `[sentient/propose-tick] Rejected candidate with invalid title format: \"${candidate.title}\"\\n`,\n );\n continue;\n }\n\n const fp = fingerprint(candidate);\n if (seenFingerprints.has(fp)) continue;\n seenFingerprints.add(fp);\n merged.push(candidate);\n }\n\n if (merged.length === 0) {\n return { kind: 'no-candidates', written: 0, count: 0, detail: 'no candidates from ingesters' };\n }\n\n // Sort by weight descending\n merged.sort((a, b) => b.weight - a.weight);\n\n // Determine how many slots remain today\n const currentCount = tasksNativeDb ? countTodayProposals(tasksNativeDb) : 0;\n const slotsRemaining = Math.max(0, DEFAULT_DAILY_PROPOSAL_LIMIT - currentCount);\n\n if (slotsRemaining === 0) {\n return {\n kind: 'rate-limited',\n written: 0,\n count: currentCount,\n detail: `daily limit reached (${currentCount}/${DEFAULT_DAILY_PROPOSAL_LIMIT})`,\n };\n }\n\n // Take top-N candidates\n const toWrite = merged.slice(0, slotsRemaining);\n\n // Checkpoint 3: killSwitch before DB writes\n if (await killSwitchActive(statePath)) {\n return {\n kind: 'killed',\n written: 0,\n count: currentCount,\n detail: 'killSwitch active before write phase',\n };\n }\n\n // Write proposals\n let written = 0;\n\n for (const candidate of toWrite) {\n // Allocate task ID\n let taskId: string;\n if (options.allocateTaskId) {\n taskId = await options.allocateTaskId();\n } else {\n const { allocateNextTaskId } = await import('@cleocode/core/internal');\n taskId = await allocateNextTaskId(projectRoot);\n }\n\n const now = new Date().toISOString();\n const labels = JSON.stringify([TIER2_LABEL, `source:${candidate.source}`]);\n\n if (!tasksNativeDb) {\n process.stderr.write('[sentient/propose-tick] tasks DB not available; skipping write\\n');\n break;\n }\n\n // Use the SQL INSERT path (with metadata_json-equivalent stored in notes_json\n // as a structured first element) and labels to mark the proposal.\n // The rate limiter identifies proposals by: labels_json LIKE '%sentient-tier2%'\n // This avoids needing a new column on the tasks table.\n const notesJson = JSON.stringify([\n JSON.stringify({\n kind: 'proposal-meta',\n proposedBy: 'sentient-tier2',\n source: candidate.source,\n sourceId: candidate.sourceId,\n weight: candidate.weight,\n proposedAt: now,\n }),\n ]);\n\n const insertSql = `\n INSERT INTO tasks (\n id, title, description, status, priority,\n labels_json, notes_json,\n created_at, updated_at,\n role, scope\n ) VALUES (\n :id, :title, :description, :status, :priority,\n :labelsJson, :notesJson,\n :createdAt, :updatedAt,\n :role, :scope\n )\n `;\n\n const insertParams = {\n id: taskId,\n title: candidate.title,\n description: candidate.rationale,\n status: 'proposed',\n priority: 'medium',\n labelsJson: labels,\n notesJson,\n createdAt: now,\n updatedAt: now,\n role: 'work',\n scope: 'feature',\n };\n\n try {\n const result = transactionalInsertProposal(\n tasksNativeDb,\n insertSql,\n insertParams,\n DEFAULT_DAILY_PROPOSAL_LIMIT,\n );\n\n if (result.inserted) {\n written++;\n } else if (result.reason === 'rate-limit') {\n // Rate limit hit mid-loop \u2014 stop writing.\n break;\n }\n // If 'busy', skip this one and continue.\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[sentient/propose-tick] INSERT failed for ${taskId}: ${message}\\n`);\n }\n }\n\n // Update tier2Stats\n if (written > 0) {\n const latestState = await readSentientState(statePath);\n await patchSentientState(statePath, {\n tier2Stats: {\n ...latestState.tier2Stats,\n proposalsGenerated: latestState.tier2Stats.proposalsGenerated + written,\n },\n });\n }\n\n const finalCount = tasksNativeDb ? countTodayProposals(tasksNativeDb) : currentCount + written;\n\n if (written === 0) {\n return {\n kind: 'no-candidates',\n written: 0,\n count: finalCount,\n detail: 'candidates available but none written (rate limit or DB unavailable)',\n };\n }\n\n return {\n kind: 'wrote',\n written,\n count: finalCount,\n detail: `wrote ${written} proposal(s) (${finalCount}/${DEFAULT_DAILY_PROPOSAL_LIMIT} today)`,\n };\n}\n\n/**\n * Safe wrapper for {@link runProposeTick} \u2014 swallows unexpected exceptions.\n * Used by the daemon cron handler.\n *\n * @param options - Propose tick options\n * @returns The propose tick outcome, or an error outcome if the tick threw.\n */\nexport async function safeRunProposeTick(options: ProposeTickOptions): Promise<ProposeTickOutcome> {\n try {\n return await runProposeTick(options);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n kind: 'error',\n written: 0,\n count: 0,\n detail: `propose tick threw: ${message}`,\n };\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAqCO,IAAM,uBAAuB;AAG7B,IAAM,2BAA2B;AAGjC,IAAM,0BAA0B;AAGhC,IAAM,sBAAsB;AAU5B,SAAS,mBAAmB,eAAuB,cAA8B;AACtF,SAAO,KAAK,IAAK,gBAAgB,KAAM,cAAc,CAAG;AAC1D;AAiBO,SAAS,iBAAiB,UAAoD;AACnF,MAAI,CAAC,UAAU;AACb,WAAO,CAAC;AAAA,EACV;AAEA,MAAI;AACF,UAAM,OAAO,SAAS,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAS7B;AAED,UAAM,OAAO,KAAK,IAAI;AAAA,MACpB,cAAc;AAAA,MACd,UAAU,IAAI,mBAAmB;AAAA,MACjC,YAAY;AAAA,MACZ,OAAO;AAAA,IACT,CAAC;AAED,UAAM,aAAkC,KAAK,IAAI,CAAC,QAAQ;AACxD,YAAM,QAAQ,IAAI,SAAS,IAAI,KAAK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AA,EACH;AAEA,QAAM,aAAa,gBAAgB,oBAAoB,aAAa,IAAI,eAAe;AAEvF,MAAI,YAAY,GAAG;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,MACT,OAAO;AAAA,MACP,QAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,OAAO;AAAA,IACP,QAAQ,SAAS,OAAO,iBAAiB,UAAU,IAAI,4BAA4B;AAAA,EACrF;AACF;AASA,eAAsB,mBAAmB,SAA0D;AACjG,MAAI;AACF,WAAO,MAAM,eAAe,OAAO;AAAA,EACrC,SAAS,KAAK;AACZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,MACT,OAAO;AAAA,MACP,QAAQ,uBAAuB,OAAO;AAAA,IACxC;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["join"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// packages/core/src/sentient/state.ts
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
var SENTIENT_STATE_SCHEMA_VERSION = "1.0";
|
|
5
|
+
var DEFAULT_SENTIENT_STATE = {
|
|
6
|
+
schemaVersion: SENTIENT_STATE_SCHEMA_VERSION,
|
|
7
|
+
pid: null,
|
|
8
|
+
startedAt: null,
|
|
9
|
+
lastTickAt: null,
|
|
10
|
+
killSwitch: false,
|
|
11
|
+
killSwitchReason: null,
|
|
12
|
+
stats: {
|
|
13
|
+
tasksPicked: 0,
|
|
14
|
+
tasksCompleted: 0,
|
|
15
|
+
tasksFailed: 0,
|
|
16
|
+
ticksExecuted: 0,
|
|
17
|
+
ticksKilled: 0
|
|
18
|
+
},
|
|
19
|
+
stuckTasks: {},
|
|
20
|
+
stuckTimestamps: [],
|
|
21
|
+
activeTaskId: null,
|
|
22
|
+
tier2Enabled: false,
|
|
23
|
+
tier2Stats: {
|
|
24
|
+
proposalsGenerated: 0,
|
|
25
|
+
proposalsAccepted: 0,
|
|
26
|
+
proposalsRejected: 0
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
async function readSentientState(statePath) {
|
|
30
|
+
try {
|
|
31
|
+
const raw = await readFile(statePath, "utf-8");
|
|
32
|
+
const parsed = JSON.parse(raw);
|
|
33
|
+
return {
|
|
34
|
+
...DEFAULT_SENTIENT_STATE,
|
|
35
|
+
...parsed,
|
|
36
|
+
stats: { ...DEFAULT_SENTIENT_STATE.stats, ...parsed.stats ?? {} },
|
|
37
|
+
stuckTasks: parsed.stuckTasks ?? {},
|
|
38
|
+
stuckTimestamps: parsed.stuckTimestamps ?? [],
|
|
39
|
+
tier2Enabled: parsed.tier2Enabled ?? false,
|
|
40
|
+
tier2Stats: { ...DEFAULT_SENTIENT_STATE.tier2Stats, ...parsed.tier2Stats ?? {} }
|
|
41
|
+
};
|
|
42
|
+
} catch {
|
|
43
|
+
return { ...DEFAULT_SENTIENT_STATE };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function writeSentientState(statePath, state) {
|
|
47
|
+
const dir = dirname(statePath);
|
|
48
|
+
await mkdir(dir, { recursive: true });
|
|
49
|
+
const tmpPath = join(dir, `.sentient-state-${process.pid}.tmp`);
|
|
50
|
+
const json = JSON.stringify(state, null, 2);
|
|
51
|
+
await writeFile(tmpPath, json, "utf-8");
|
|
52
|
+
await rename(tmpPath, statePath);
|
|
53
|
+
}
|
|
54
|
+
async function patchSentientState(statePath, patch) {
|
|
55
|
+
const current = await readSentientState(statePath);
|
|
56
|
+
const updated = {
|
|
57
|
+
...current,
|
|
58
|
+
...patch,
|
|
59
|
+
stats: { ...current.stats, ...patch.stats ?? {} }
|
|
60
|
+
};
|
|
61
|
+
await writeSentientState(statePath, updated);
|
|
62
|
+
return updated;
|
|
63
|
+
}
|
|
64
|
+
async function incrementStats(statePath, delta) {
|
|
65
|
+
const current = await readSentientState(statePath);
|
|
66
|
+
const nextStats = {
|
|
67
|
+
tasksPicked: current.stats.tasksPicked + (delta.tasksPicked ?? 0),
|
|
68
|
+
tasksCompleted: current.stats.tasksCompleted + (delta.tasksCompleted ?? 0),
|
|
69
|
+
tasksFailed: current.stats.tasksFailed + (delta.tasksFailed ?? 0),
|
|
70
|
+
ticksExecuted: current.stats.ticksExecuted + (delta.ticksExecuted ?? 0),
|
|
71
|
+
ticksKilled: current.stats.ticksKilled + (delta.ticksKilled ?? 0)
|
|
72
|
+
};
|
|
73
|
+
const updated = { ...current, stats: nextStats };
|
|
74
|
+
await writeSentientState(statePath, updated);
|
|
75
|
+
return updated;
|
|
76
|
+
}
|
|
77
|
+
export {
|
|
78
|
+
DEFAULT_SENTIENT_STATE,
|
|
79
|
+
SENTIENT_STATE_SCHEMA_VERSION,
|
|
80
|
+
incrementStats,
|
|
81
|
+
patchSentientState,
|
|
82
|
+
readSentientState,
|
|
83
|
+
writeSentientState
|
|
84
|
+
};
|
|
85
|
+
//# sourceMappingURL=state.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/sentient/state.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Sentient Loop State \u2014 Persistent state for the Tier-1 autonomous daemon.\n *\n * Stored in `.cleo/sentient-state.json` (plain JSON, not SQLite) to avoid\n * SQLite WAL conflicts between the long-running daemon process and the\n * main CLEO CLI process. Human-readable for debugging.\n *\n * The file is gitignored (see .gitignore \u00A7.cleo/ section) and survives\n * restarts. Only `killSwitch`, `pid`, and `stats` fields are load-bearing\n * across process boundaries.\n *\n * @see ADR-054 \u2014 Sentient Loop Tier-1 (autonomous task execution)\n * @task T946\n */\n\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport type { Tier2Stats } from '@cleocode/contracts';\n\n/** Schema version for sentient-state.json. Bump on breaking field changes. */\nexport const SENTIENT_STATE_SCHEMA_VERSION = '1.0' as const;\n\n/**\n * Per-task failure/backoff tracking for stuck detection.\n * Keyed by task id in {@link SentientState.stuckTasks}.\n */\nexport interface StuckTaskRecord {\n /** Number of consecutive failed spawn attempts for this task. */\n attempts: number;\n /** ISO-8601 timestamp of the most recent failure. */\n lastFailureAt: string;\n /** Unix epoch ms when the next retry becomes eligible. */\n nextRetryAt: number;\n /** Last captured failure reason (truncated to 500 chars). */\n lastReason: string;\n}\n\n/**\n * Rolling counters persisted across daemon restarts.\n */\nexport interface SentientStats {\n /** Total tasks picked by the loop since creation. */\n tasksPicked: number;\n /** Total tasks that completed successfully. */\n tasksCompleted: number;\n /** Total tasks whose spawn exited non-zero. */\n tasksFailed: number;\n /** Total ticks executed (including no-op ticks). */\n ticksExecuted: number;\n /** Total ticks aborted early because kill switch was active. */\n ticksKilled: number;\n}\n\n/**\n * Persistent sentient daemon state.\n *\n * Design principles:\n * - `killSwitch` is the single load-bearing kill signal \u2014 the daemon re-checks\n * it between every step of a tick, not just at tick start (Round 2 audit).\n * - `stuckTasks` keys are task ids; values encode backoff + failure counts.\n * - `stuckTimestamps` is a rolling 1-hour window used for the self-pause rule\n * (5 stucks in 1 hour \u2192 killSwitch=true).\n * - `stats` fields are monotonic counters that only ever increase.\n */\nexport interface SentientState {\n /** JSON schema version for forward-compatibility checks. */\n schemaVersion: typeof SENTIENT_STATE_SCHEMA_VERSION;\n /** PID of the currently running daemon process. null = daemon not running. */\n pid: number | null;\n /** ISO-8601 timestamp when the daemon was last started. */\n startedAt: string | null;\n /** ISO-8601 timestamp of the last completed tick (any outcome). */\n lastTickAt: string | null;\n /**\n * Kill-switch flag. When true, the daemon re-checks at every step of a tick\n * and exits cleanly without picking or spawning a task.\n */\n killSwitch: boolean;\n /** Reason supplied when killSwitch was last set (diagnostic only). */\n killSwitchReason: string | null;\n /** Rolling counters; see {@link SentientStats}. */\n stats: SentientStats;\n /** Per-task backoff + failure metadata for retry/stuck detection. */\n stuckTasks: Record<string, StuckTaskRecord>;\n /**\n * Unix-epoch-ms timestamps of `stuck` events within the last hour.\n * When length \u2265 5 the daemon self-pauses (killSwitch=true).\n */\n stuckTimestamps: number[];\n /**\n * Currently-active task id (set while a spawn is in-flight, cleared afterward).\n * Enables `status` to show the in-progress task during a long-running tick.\n */\n activeTaskId: string | null;\n /**\n * Tier-2 proposal queue enabled flag.\n *\n * Default: `false` \u2014 Tier 2 is OFF by default to prevent surprise proposal\n * floods on first daemon start. Owner enables via `cleo sentient propose enable`\n * (patches this flag). See ADR-054 \u00A7Tier-2.\n *\n * @task T1008\n */\n tier2Enabled: boolean;\n /**\n * Rolling counters for Tier-2 proposal activity.\n *\n * @task T1008\n */\n tier2Stats: Tier2Stats;\n}\n\n/** Default (empty) sentient state for fresh initialisation. */\nexport const DEFAULT_SENTIENT_STATE: SentientState = {\n schemaVersion: SENTIENT_STATE_SCHEMA_VERSION,\n pid: null,\n startedAt: null,\n lastTickAt: null,\n killSwitch: false,\n killSwitchReason: null,\n stats: {\n tasksPicked: 0,\n tasksCompleted: 0,\n tasksFailed: 0,\n ticksExecuted: 0,\n ticksKilled: 0,\n },\n stuckTasks: {},\n stuckTimestamps: [],\n activeTaskId: null,\n tier2Enabled: false,\n tier2Stats: {\n proposalsGenerated: 0,\n proposalsAccepted: 0,\n proposalsRejected: 0,\n },\n};\n\n/**\n * Read the sentient state from disk.\n *\n * Returns the default state if the file does not exist or is malformed.\n * Never throws \u2014 absence is not an error.\n *\n * @param statePath - Absolute path to sentient-state.json\n */\nexport async function readSentientState(statePath: string): Promise<SentientState> {\n try {\n const raw = await readFile(statePath, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<SentientState>;\n return {\n ...DEFAULT_SENTIENT_STATE,\n ...parsed,\n stats: { ...DEFAULT_SENTIENT_STATE.stats, ...(parsed.stats ?? {}) },\n stuckTasks: parsed.stuckTasks ?? {},\n stuckTimestamps: parsed.stuckTimestamps ?? [],\n tier2Enabled: parsed.tier2Enabled ?? false,\n tier2Stats: { ...DEFAULT_SENTIENT_STATE.tier2Stats, ...(parsed.tier2Stats ?? {}) },\n };\n } catch {\n return { ...DEFAULT_SENTIENT_STATE };\n }\n}\n\n/**\n * Write the sentient state to disk atomically via tmp-then-rename.\n *\n * Atomic write prevents partial reads if the daemon crashes mid-write.\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param state - State to persist\n */\nexport async function writeSentientState(statePath: string, state: SentientState): Promise<void> {\n const dir = dirname(statePath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.sentient-state-${process.pid}.tmp`);\n const json = JSON.stringify(state, null, 2);\n\n await writeFile(tmpPath, json, 'utf-8');\n await rename(tmpPath, statePath);\n}\n\n/**\n * Patch a subset of fields in the sentient state file.\n *\n * Reads current state, merges patch, writes back. Nested `stats` merges\n * with existing stats (never clobbered wholesale).\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param patch - Partial state to merge over the existing state\n * @returns The merged state that was written to disk.\n */\nexport async function patchSentientState(\n statePath: string,\n patch: Partial<SentientState>,\n): Promise<SentientState> {\n const current = await readSentientState(statePath);\n const updated: SentientState = {\n ...current,\n ...patch,\n stats: { ...current.stats, ...(patch.stats ?? {}) },\n };\n await writeSentientState(statePath, updated);\n return updated;\n}\n\n/**\n * Increment stats counters atomically.\n *\n * @param statePath - Absolute path to sentient-state.json\n * @param delta - Partial stats to add to current counters\n */\nexport async function incrementStats(\n statePath: string,\n delta: Partial<SentientStats>,\n): Promise<SentientState> {\n const current = await readSentientState(statePath);\n const nextStats: SentientStats = {\n tasksPicked: current.stats.tasksPicked + (delta.tasksPicked ?? 0),\n tasksCompleted: current.stats.tasksCompleted + (delta.tasksCompleted ?? 0),\n tasksFailed: current.stats.tasksFailed + (delta.tasksFailed ?? 0),\n ticksExecuted: current.stats.ticksExecuted + (delta.ticksExecuted ?? 0),\n ticksKilled: current.stats.ticksKilled + (delta.ticksKilled ?? 0),\n };\n const updated: SentientState = { ...current, stats: nextStats };\n await writeSentientState(statePath, updated);\n return updated;\n}\n"],
|
|
5
|
+
"mappings": ";AAeA,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,SAAS,SAAS,YAAY;AAIvB,IAAM,gCAAgC;AA6FtC,IAAM,yBAAwC;AAAA,EACnD,eAAe;AAAA,EACf,KAAK;AAAA,EACL,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,OAAO;AAAA,IACL,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,aAAa;AAAA,EACf;AAAA,EACA,YAAY,CAAC;AAAA,EACb,iBAAiB,CAAC;AAAA,EAClB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,YAAY;AAAA,IACV,oBAAoB;AAAA,IACpB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,EACrB;AACF;AAUA,eAAsB,kBAAkB,WAA2C;AACjF,MAAI;AACF,UAAM,MAAM,MAAM,SAAS,WAAW,OAAO;AAC7C,UAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,WAAO;AAAA,MACL,GAAG;AAAA,MACH,GAAG;AAAA,MACH,OAAO,EAAE,GAAG,uBAAuB,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,MAClE,YAAY,OAAO,cAAc,CAAC;AAAA,MAClC,iBAAiB,OAAO,mBAAmB,CAAC;AAAA,MAC5C,cAAc,OAAO,gBAAgB;AAAA,MACrC,YAAY,EAAE,GAAG,uBAAuB,YAAY,GAAI,OAAO,cAAc,CAAC,EAAG;AAAA,IACnF;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,GAAG,uBAAuB;AAAA,EACrC;AACF;AAUA,eAAsB,mBAAmB,WAAmB,OAAqC;AAC/F,QAAM,MAAM,QAAQ,SAAS;AAC7B,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AAEpC,QAAM,UAAU,KAAK,KAAK,mBAAmB,QAAQ,GAAG,MAAM;AAC9D,QAAM,OAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AAE1C,QAAM,UAAU,SAAS,MAAM,OAAO;AACtC,QAAM,OAAO,SAAS,SAAS;AACjC;AAYA,eAAsB,mBACpB,WACA,OACwB;AACxB,QAAM,UAAU,MAAM,kBAAkB,SAAS;AACjD,QAAM,UAAyB;AAAA,IAC7B,GAAG;AAAA,IACH,GAAG;AAAA,IACH,OAAO,EAAE,GAAG,QAAQ,OAAO,GAAI,MAAM,SAAS,CAAC,EAAG;AAAA,EACpD;AACA,QAAM,mBAAmB,WAAW,OAAO;AAC3C,SAAO;AACT;AAQA,eAAsB,eACpB,WACA,OACwB;AACxB,QAAM,UAAU,MAAM,kBAAkB,SAAS;AACjD,QAAM,YAA2B;AAAA,IAC/B,aAAa,QAAQ,MAAM,eAAe,MAAM,eAAe;AAAA,IAC/D,gBAAgB,QAAQ,MAAM,kBAAkB,MAAM,kBAAkB;AAAA,IACxE,aAAa,QAAQ,MAAM,eAAe,MAAM,eAAe;AAAA,IAC/D,eAAe,QAAQ,MAAM,iBAAiB,MAAM,iBAAiB;AAAA,IACrE,aAAa,QAAQ,MAAM,eAAe,MAAM,eAAe;AAAA,EACjE;AACA,QAAM,UAAyB,EAAE,GAAG,SAAS,OAAO,UAAU;AAC9D,QAAM,mBAAmB,WAAW,OAAO;AAC3C,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// packages/core/src/sentient/tick.ts
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
// packages/core/src/sentient/state.ts
|
|
5
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
var SENTIENT_STATE_SCHEMA_VERSION = "1.0";
|
|
8
|
+
var DEFAULT_SENTIENT_STATE = {
|
|
9
|
+
schemaVersion: SENTIENT_STATE_SCHEMA_VERSION,
|
|
10
|
+
pid: null,
|
|
11
|
+
startedAt: null,
|
|
12
|
+
lastTickAt: null,
|
|
13
|
+
killSwitch: false,
|
|
14
|
+
killSwitchReason: null,
|
|
15
|
+
stats: {
|
|
16
|
+
tasksPicked: 0,
|
|
17
|
+
tasksCompleted: 0,
|
|
18
|
+
tasksFailed: 0,
|
|
19
|
+
ticksExecuted: 0,
|
|
20
|
+
ticksKilled: 0
|
|
21
|
+
},
|
|
22
|
+
stuckTasks: {},
|
|
23
|
+
stuckTimestamps: [],
|
|
24
|
+
activeTaskId: null,
|
|
25
|
+
tier2Enabled: false,
|
|
26
|
+
tier2Stats: {
|
|
27
|
+
proposalsGenerated: 0,
|
|
28
|
+
proposalsAccepted: 0,
|
|
29
|
+
proposalsRejected: 0
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
async function readSentientState(statePath) {
|
|
33
|
+
try {
|
|
34
|
+
const raw = await readFile(statePath, "utf-8");
|
|
35
|
+
const parsed = JSON.parse(raw);
|
|
36
|
+
return {
|
|
37
|
+
...DEFAULT_SENTIENT_STATE,
|
|
38
|
+
...parsed,
|
|
39
|
+
stats: { ...DEFAULT_SENTIENT_STATE.stats, ...parsed.stats ?? {} },
|
|
40
|
+
stuckTasks: parsed.stuckTasks ?? {},
|
|
41
|
+
stuckTimestamps: parsed.stuckTimestamps ?? [],
|
|
42
|
+
tier2Enabled: parsed.tier2Enabled ?? false,
|
|
43
|
+
tier2Stats: { ...DEFAULT_SENTIENT_STATE.tier2Stats, ...parsed.tier2Stats ?? {} }
|
|
44
|
+
};
|
|
45
|
+
} catch {
|
|
46
|
+
return { ...DEFAULT_SENTIENT_STATE };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function writeSentientState(statePath, state) {
|
|
50
|
+
const dir = dirname(statePath);
|
|
51
|
+
await mkdir(dir, { recursive: true });
|
|
52
|
+
const tmpPath = join(dir, `.sentient-state-${process.pid}.tmp`);
|
|
53
|
+
const json = JSON.stringify(state, null, 2);
|
|
54
|
+
await writeFile(tmpPath, json, "utf-8");
|
|
55
|
+
await rename(tmpPath, statePath);
|
|
56
|
+
}
|
|
57
|
+
async function patchSentientState(statePath, patch) {
|
|
58
|
+
const current = await readSentientState(statePath);
|
|
59
|
+
const updated = {
|
|
60
|
+
...current,
|
|
61
|
+
...patch,
|
|
62
|
+
stats: { ...current.stats, ...patch.stats ?? {} }
|
|
63
|
+
};
|
|
64
|
+
await writeSentientState(statePath, updated);
|
|
65
|
+
return updated;
|
|
66
|
+
}
|
|
67
|
+
async function incrementStats(statePath, delta) {
|
|
68
|
+
const current = await readSentientState(statePath);
|
|
69
|
+
const nextStats = {
|
|
70
|
+
tasksPicked: current.stats.tasksPicked + (delta.tasksPicked ?? 0),
|
|
71
|
+
tasksCompleted: current.stats.tasksCompleted + (delta.tasksCompleted ?? 0),
|
|
72
|
+
tasksFailed: current.stats.tasksFailed + (delta.tasksFailed ?? 0),
|
|
73
|
+
ticksExecuted: current.stats.ticksExecuted + (delta.ticksExecuted ?? 0),
|
|
74
|
+
ticksKilled: current.stats.ticksKilled + (delta.ticksKilled ?? 0)
|
|
75
|
+
};
|
|
76
|
+
const updated = { ...current, stats: nextStats };
|
|
77
|
+
await writeSentientState(statePath, updated);
|
|
78
|
+
return updated;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// packages/core/src/sentient/tick.ts
|
|
82
|
+
var DREAM_VOLUME_THRESHOLD_DEFAULT = 50;
|
|
83
|
+
var DREAM_IDLE_TICKS_DEFAULT = 5;
|
|
84
|
+
var DEFAULT_ADAPTER = "claude-code";
|
|
85
|
+
var RETRY_BACKOFF_MS = [3e4, 3e5, 18e5];
|
|
86
|
+
var MAX_TASK_ATTEMPTS = RETRY_BACKOFF_MS.length;
|
|
87
|
+
var SELF_PAUSE_STUCK_THRESHOLD = 5;
|
|
88
|
+
var SELF_PAUSE_WINDOW_MS = 60 * 60 * 1e3;
|
|
89
|
+
var SELF_PAUSE_REASON = "self-pause: 5 stuck tasks in 1 hour";
|
|
90
|
+
var SPAWN_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
91
|
+
async function killSwitchActive(statePath) {
|
|
92
|
+
const state = await readSentientState(statePath);
|
|
93
|
+
return state.killSwitch === true;
|
|
94
|
+
}
|
|
95
|
+
function pruneStuckWindow(timestamps, now) {
|
|
96
|
+
const cutoff = now - SELF_PAUSE_WINDOW_MS;
|
|
97
|
+
return timestamps.filter((t) => t >= cutoff);
|
|
98
|
+
}
|
|
99
|
+
async function defaultPickTask(projectRoot) {
|
|
100
|
+
const { Cleo } = await import("@cleocode/core/sdk");
|
|
101
|
+
const { getReadyTasks } = await import("@cleocode/core/tasks");
|
|
102
|
+
const cleo = await Cleo.init(projectRoot);
|
|
103
|
+
const pending = await cleo.tasks.find({ status: "pending", limit: 500 });
|
|
104
|
+
const candidates = Array.isArray(pending?.data?.tasks) ? pending.data.tasks : [];
|
|
105
|
+
if (candidates.length === 0) return null;
|
|
106
|
+
const ready = getReadyTasks(candidates);
|
|
107
|
+
if (ready.length === 0) return null;
|
|
108
|
+
ready.sort((a, b) => a.id.localeCompare(b.id));
|
|
109
|
+
return ready[0];
|
|
110
|
+
}
|
|
111
|
+
function defaultSpawn(taskId, adapter, projectRoot) {
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
const args = ["orchestrate", "spawn", taskId, "--adapter", adapter];
|
|
114
|
+
const child = spawn("cleo", args, {
|
|
115
|
+
cwd: projectRoot,
|
|
116
|
+
env: { ...process.env, CLEO_SENTIENT_SPAWN: "1" },
|
|
117
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
118
|
+
});
|
|
119
|
+
let stdout = "";
|
|
120
|
+
let stderr = "";
|
|
121
|
+
child.stdout?.on("data", (chunk) => {
|
|
122
|
+
stdout += chunk.toString("utf-8");
|
|
123
|
+
});
|
|
124
|
+
child.stderr?.on("data", (chunk) => {
|
|
125
|
+
stderr += chunk.toString("utf-8");
|
|
126
|
+
});
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
child.kill("SIGTERM");
|
|
129
|
+
}, SPAWN_TIMEOUT_MS);
|
|
130
|
+
child.on("error", (err) => {
|
|
131
|
+
clearTimeout(timer);
|
|
132
|
+
resolve({
|
|
133
|
+
exitCode: 1,
|
|
134
|
+
stdout,
|
|
135
|
+
stderr: stderr + `
|
|
136
|
+
[sentient] spawn error: ${err.message}`
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
child.on("exit", (code) => {
|
|
140
|
+
clearTimeout(timer);
|
|
141
|
+
resolve({
|
|
142
|
+
exitCode: code ?? 1,
|
|
143
|
+
stdout: stdout.slice(-4e3),
|
|
144
|
+
stderr: stderr.slice(-4e3)
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
async function writeSuccessReceipt(projectRoot, taskId, exitCode) {
|
|
150
|
+
try {
|
|
151
|
+
const { Cleo } = await import("@cleocode/core/sdk");
|
|
152
|
+
const cleo = await Cleo.init(projectRoot);
|
|
153
|
+
await cleo.memory.observe({
|
|
154
|
+
text: `sentient-tier1: task ${taskId} completed successfully (exit=${exitCode})`,
|
|
155
|
+
title: `sentient-receipt: ${taskId}`
|
|
156
|
+
});
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
var consecutiveIdleTicks = 0;
|
|
161
|
+
async function maybeTriggerDream(projectRoot, opts, pickedTask) {
|
|
162
|
+
const volumeThreshold = opts.dreamVolumeThreshold ?? DREAM_VOLUME_THRESHOLD_DEFAULT;
|
|
163
|
+
const idleTicksThreshold = opts.dreamIdleTicks ?? DREAM_IDLE_TICKS_DEFAULT;
|
|
164
|
+
if (volumeThreshold <= 0 && idleTicksThreshold <= 0) return;
|
|
165
|
+
if (pickedTask) {
|
|
166
|
+
consecutiveIdleTicks = 0;
|
|
167
|
+
} else {
|
|
168
|
+
consecutiveIdleTicks += 1;
|
|
169
|
+
}
|
|
170
|
+
const dreamer = opts.checkAndDream ?? (async (root, dreamerOpts) => {
|
|
171
|
+
const { checkAndDream } = await import("@cleocode/core/internal");
|
|
172
|
+
return checkAndDream(root, dreamerOpts);
|
|
173
|
+
});
|
|
174
|
+
try {
|
|
175
|
+
await dreamer(projectRoot, {
|
|
176
|
+
volumeThreshold: volumeThreshold > 0 ? volumeThreshold : void 0,
|
|
177
|
+
inline: false
|
|
178
|
+
}).catch((err) => {
|
|
179
|
+
console.warn("[sentient/tick] dream trigger error:", err);
|
|
180
|
+
});
|
|
181
|
+
} catch (err) {
|
|
182
|
+
console.warn("[sentient/tick] dream trigger threw:", err);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async function writeFailureReceipt(projectRoot, taskId, attempt, exitCode, reason) {
|
|
186
|
+
try {
|
|
187
|
+
const { Cleo } = await import("@cleocode/core/sdk");
|
|
188
|
+
const cleo = await Cleo.init(projectRoot);
|
|
189
|
+
await cleo.memory.observe({
|
|
190
|
+
text: `sentient-tier1: task ${taskId} failed (attempt=${attempt}/${MAX_TASK_ATTEMPTS}, exit=${exitCode}). reason=${reason.slice(0, 500)}`,
|
|
191
|
+
title: `sentient-failure: ${taskId}`
|
|
192
|
+
});
|
|
193
|
+
} catch {
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function runTick(options) {
|
|
197
|
+
const { projectRoot, statePath } = options;
|
|
198
|
+
const adapter = options.adapter ?? DEFAULT_ADAPTER;
|
|
199
|
+
const now = Date.now();
|
|
200
|
+
if (await killSwitchActive(statePath)) {
|
|
201
|
+
await incrementStats(statePath, { ticksKilled: 1 });
|
|
202
|
+
await patchSentientState(statePath, { lastTickAt: new Date(now).toISOString() });
|
|
203
|
+
return { kind: "killed", taskId: null, detail: "killSwitch active before pick" };
|
|
204
|
+
}
|
|
205
|
+
const picker = options.pickTask ?? defaultPickTask;
|
|
206
|
+
let task;
|
|
207
|
+
try {
|
|
208
|
+
task = await picker(projectRoot);
|
|
209
|
+
} catch (err) {
|
|
210
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
211
|
+
await incrementStats(statePath, { ticksExecuted: 1 });
|
|
212
|
+
await patchSentientState(statePath, { lastTickAt: new Date(now).toISOString() });
|
|
213
|
+
return { kind: "error", taskId: null, detail: `picker threw: ${message}` };
|
|
214
|
+
}
|
|
215
|
+
if (task === null) {
|
|
216
|
+
await incrementStats(statePath, { ticksExecuted: 1 });
|
|
217
|
+
await patchSentientState(statePath, { lastTickAt: new Date(now).toISOString() });
|
|
218
|
+
return { kind: "no-task", taskId: null, detail: "no unblocked tasks available" };
|
|
219
|
+
}
|
|
220
|
+
const preSpawnState = await readSentientState(statePath);
|
|
221
|
+
const existingStuck = preSpawnState.stuckTasks[task.id];
|
|
222
|
+
if (existingStuck && existingStuck.nextRetryAt > now) {
|
|
223
|
+
await incrementStats(statePath, { ticksExecuted: 1 });
|
|
224
|
+
await patchSentientState(statePath, { lastTickAt: new Date(now).toISOString() });
|
|
225
|
+
return {
|
|
226
|
+
kind: "backoff",
|
|
227
|
+
taskId: task.id,
|
|
228
|
+
detail: `task ${task.id} in backoff until ${new Date(existingStuck.nextRetryAt).toISOString()}`
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
if (await killSwitchActive(statePath)) {
|
|
232
|
+
await incrementStats(statePath, { ticksKilled: 1 });
|
|
233
|
+
await patchSentientState(statePath, { lastTickAt: new Date(now).toISOString() });
|
|
234
|
+
return { kind: "killed", taskId: task.id, detail: "killSwitch active before spawn" };
|
|
235
|
+
}
|
|
236
|
+
await incrementStats(statePath, { tasksPicked: 1 });
|
|
237
|
+
await patchSentientState(statePath, { activeTaskId: task.id });
|
|
238
|
+
let spawnResult;
|
|
239
|
+
if (options.dryRun === true) {
|
|
240
|
+
spawnResult = {
|
|
241
|
+
exitCode: 0,
|
|
242
|
+
stdout: "[dry-run] spawn skipped",
|
|
243
|
+
stderr: ""
|
|
244
|
+
};
|
|
245
|
+
} else {
|
|
246
|
+
try {
|
|
247
|
+
const spawner = options.spawn ?? ((tid, adp) => defaultSpawn(tid, adp, projectRoot));
|
|
248
|
+
spawnResult = await spawner(task.id, adapter);
|
|
249
|
+
} catch (err) {
|
|
250
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
251
|
+
spawnResult = { exitCode: 1, stdout: "", stderr: `spawn threw: ${message}` };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (await killSwitchActive(statePath)) {
|
|
255
|
+
await incrementStats(statePath, { ticksKilled: 1 });
|
|
256
|
+
await patchSentientState(statePath, {
|
|
257
|
+
lastTickAt: new Date(Date.now()).toISOString(),
|
|
258
|
+
activeTaskId: null
|
|
259
|
+
});
|
|
260
|
+
return {
|
|
261
|
+
kind: "killed",
|
|
262
|
+
taskId: task.id,
|
|
263
|
+
detail: "killSwitch active after spawn; result not recorded"
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (spawnResult.exitCode === 0) {
|
|
267
|
+
await writeSuccessReceipt(projectRoot, task.id, spawnResult.exitCode);
|
|
268
|
+
const post2 = await readSentientState(statePath);
|
|
269
|
+
const { [task.id]: _removed, ...rest } = post2.stuckTasks;
|
|
270
|
+
void _removed;
|
|
271
|
+
await patchSentientState(statePath, {
|
|
272
|
+
stuckTasks: rest,
|
|
273
|
+
activeTaskId: null,
|
|
274
|
+
lastTickAt: new Date(Date.now()).toISOString()
|
|
275
|
+
});
|
|
276
|
+
await incrementStats(statePath, { tasksCompleted: 1, ticksExecuted: 1 });
|
|
277
|
+
return {
|
|
278
|
+
kind: "success",
|
|
279
|
+
taskId: task.id,
|
|
280
|
+
detail: `task ${task.id} completed (exit=0)`
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const currentAttempts = existingStuck?.attempts ?? 0;
|
|
284
|
+
const nextAttempts = currentAttempts + 1;
|
|
285
|
+
const failureReason = spawnResult.stderr.slice(-500) || `exit=${spawnResult.exitCode}`;
|
|
286
|
+
await writeFailureReceipt(
|
|
287
|
+
projectRoot,
|
|
288
|
+
task.id,
|
|
289
|
+
nextAttempts,
|
|
290
|
+
spawnResult.exitCode,
|
|
291
|
+
failureReason
|
|
292
|
+
);
|
|
293
|
+
await incrementStats(statePath, { tasksFailed: 1, ticksExecuted: 1 });
|
|
294
|
+
if (nextAttempts >= MAX_TASK_ATTEMPTS) {
|
|
295
|
+
const windowed = pruneStuckWindow(preSpawnState.stuckTimestamps, now);
|
|
296
|
+
windowed.push(now);
|
|
297
|
+
const stuckRecord2 = {
|
|
298
|
+
attempts: nextAttempts,
|
|
299
|
+
lastFailureAt: new Date(now).toISOString(),
|
|
300
|
+
nextRetryAt: Number.MAX_SAFE_INTEGER,
|
|
301
|
+
// owner-only release
|
|
302
|
+
lastReason: failureReason
|
|
303
|
+
};
|
|
304
|
+
const post2 = await readSentientState(statePath);
|
|
305
|
+
const updatedStuckTasks = {
|
|
306
|
+
...post2.stuckTasks,
|
|
307
|
+
[task.id]: stuckRecord2
|
|
308
|
+
};
|
|
309
|
+
const shouldSelfPause = windowed.length >= SELF_PAUSE_STUCK_THRESHOLD;
|
|
310
|
+
await patchSentientState(statePath, {
|
|
311
|
+
stuckTasks: updatedStuckTasks,
|
|
312
|
+
stuckTimestamps: windowed,
|
|
313
|
+
activeTaskId: null,
|
|
314
|
+
lastTickAt: new Date(now).toISOString(),
|
|
315
|
+
...shouldSelfPause ? { killSwitch: true, killSwitchReason: SELF_PAUSE_REASON } : {}
|
|
316
|
+
});
|
|
317
|
+
if (shouldSelfPause) {
|
|
318
|
+
return {
|
|
319
|
+
kind: "self-paused",
|
|
320
|
+
taskId: task.id,
|
|
321
|
+
detail: `task ${task.id} is stuck; self-pause fired (${windowed.length}/${SELF_PAUSE_STUCK_THRESHOLD} stucks in window)`
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
kind: "stuck",
|
|
326
|
+
taskId: task.id,
|
|
327
|
+
detail: `task ${task.id} stuck after ${nextAttempts} attempts; owner must re-enable via \`cleo sentient resume\``
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
const backoff = RETRY_BACKOFF_MS[nextAttempts - 1] ?? RETRY_BACKOFF_MS[RETRY_BACKOFF_MS.length - 1];
|
|
331
|
+
const stuckRecord = {
|
|
332
|
+
attempts: nextAttempts,
|
|
333
|
+
lastFailureAt: new Date(now).toISOString(),
|
|
334
|
+
nextRetryAt: now + backoff,
|
|
335
|
+
lastReason: failureReason
|
|
336
|
+
};
|
|
337
|
+
const post = await readSentientState(statePath);
|
|
338
|
+
await patchSentientState(statePath, {
|
|
339
|
+
stuckTasks: { ...post.stuckTasks, [task.id]: stuckRecord },
|
|
340
|
+
activeTaskId: null,
|
|
341
|
+
lastTickAt: new Date(now).toISOString()
|
|
342
|
+
});
|
|
343
|
+
return {
|
|
344
|
+
kind: "failure",
|
|
345
|
+
taskId: task.id,
|
|
346
|
+
detail: `task ${task.id} failed (attempt=${nextAttempts}/${MAX_TASK_ATTEMPTS}); retry scheduled at ${new Date(now + backoff).toISOString()}`
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async function safeRunTick(options) {
|
|
350
|
+
let outcome;
|
|
351
|
+
try {
|
|
352
|
+
outcome = await runTick(options);
|
|
353
|
+
} catch (err) {
|
|
354
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
355
|
+
try {
|
|
356
|
+
await incrementStats(options.statePath, { ticksExecuted: 1 });
|
|
357
|
+
} catch {
|
|
358
|
+
}
|
|
359
|
+
outcome = { kind: "error", taskId: null, detail: `tick threw: ${message}` };
|
|
360
|
+
}
|
|
361
|
+
const pickedTask = outcome.kind !== "no-task" && outcome.kind !== "killed" && outcome.kind !== "error" && outcome.taskId !== null;
|
|
362
|
+
await maybeTriggerDream(options.projectRoot, options, pickedTask).catch(() => {
|
|
363
|
+
});
|
|
364
|
+
return outcome;
|
|
365
|
+
}
|
|
366
|
+
function isFailureOutcome(outcome) {
|
|
367
|
+
return outcome.kind === "failure" || outcome.kind === "stuck" || outcome.kind === "self-paused";
|
|
368
|
+
}
|
|
369
|
+
async function getKillStatus(statePath) {
|
|
370
|
+
const state = await readSentientState(statePath);
|
|
371
|
+
return { killSwitch: state.killSwitch, killSwitchReason: state.killSwitchReason };
|
|
372
|
+
}
|
|
373
|
+
function _resetDreamTickState() {
|
|
374
|
+
consecutiveIdleTicks = 0;
|
|
375
|
+
}
|
|
376
|
+
function _getConsecutiveIdleTicks() {
|
|
377
|
+
return consecutiveIdleTicks;
|
|
378
|
+
}
|
|
379
|
+
export {
|
|
380
|
+
DEFAULT_ADAPTER,
|
|
381
|
+
DREAM_IDLE_TICKS_DEFAULT,
|
|
382
|
+
DREAM_VOLUME_THRESHOLD_DEFAULT,
|
|
383
|
+
MAX_TASK_ATTEMPTS,
|
|
384
|
+
RETRY_BACKOFF_MS,
|
|
385
|
+
SELF_PAUSE_REASON,
|
|
386
|
+
SELF_PAUSE_STUCK_THRESHOLD,
|
|
387
|
+
SELF_PAUSE_WINDOW_MS,
|
|
388
|
+
SPAWN_TIMEOUT_MS,
|
|
389
|
+
_getConsecutiveIdleTicks,
|
|
390
|
+
_resetDreamTickState,
|
|
391
|
+
getKillStatus,
|
|
392
|
+
isFailureOutcome,
|
|
393
|
+
runTick,
|
|
394
|
+
safeRunTick
|
|
395
|
+
};
|
|
396
|
+
//# sourceMappingURL=tick.js.map
|