@cleocode/core 2026.4.98 → 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.
Files changed (85) hide show
  1. package/dist/gc/daemon-entry.d.ts +15 -0
  2. package/dist/gc/daemon-entry.d.ts.map +1 -0
  3. package/dist/gc/daemon.d.ts +71 -0
  4. package/dist/gc/daemon.d.ts.map +1 -0
  5. package/dist/gc/daemon.js +481 -0
  6. package/dist/gc/daemon.js.map +7 -0
  7. package/dist/gc/index.d.ts +14 -0
  8. package/dist/gc/index.d.ts.map +1 -0
  9. package/dist/gc/index.js +669 -0
  10. package/dist/gc/index.js.map +7 -0
  11. package/dist/gc/runner.d.ts +132 -0
  12. package/dist/gc/runner.d.ts.map +1 -0
  13. package/dist/gc/runner.js +360 -0
  14. package/dist/gc/runner.js.map +7 -0
  15. package/dist/gc/state.d.ts +94 -0
  16. package/dist/gc/state.d.ts.map +1 -0
  17. package/dist/gc/state.js +49 -0
  18. package/dist/gc/state.js.map +7 -0
  19. package/dist/gc/transcript.d.ts +130 -0
  20. package/dist/gc/transcript.d.ts.map +1 -0
  21. package/dist/gc/transcript.js +209 -0
  22. package/dist/gc/transcript.js.map +7 -0
  23. package/dist/memory/brain-backfill.js +14643 -0
  24. package/dist/memory/brain-backfill.js.map +7 -0
  25. package/dist/memory/precompact-flush.js +47725 -0
  26. package/dist/memory/precompact-flush.js.map +7 -0
  27. package/dist/sentient/daemon-entry.d.ts +11 -0
  28. package/dist/sentient/daemon-entry.d.ts.map +1 -0
  29. package/dist/sentient/daemon.d.ts +160 -0
  30. package/dist/sentient/daemon.d.ts.map +1 -0
  31. package/dist/sentient/daemon.js +1100 -0
  32. package/dist/sentient/daemon.js.map +7 -0
  33. package/dist/sentient/index.d.ts +18 -0
  34. package/dist/sentient/index.d.ts.map +1 -0
  35. package/dist/sentient/index.js +1162 -0
  36. package/dist/sentient/index.js.map +7 -0
  37. package/dist/sentient/ingesters/brain-ingester.d.ts +44 -0
  38. package/dist/sentient/ingesters/brain-ingester.d.ts.map +1 -0
  39. package/dist/sentient/ingesters/nexus-ingester.d.ts +45 -0
  40. package/dist/sentient/ingesters/nexus-ingester.d.ts.map +1 -0
  41. package/dist/sentient/ingesters/test-ingester.d.ts +43 -0
  42. package/dist/sentient/ingesters/test-ingester.d.ts.map +1 -0
  43. package/dist/sentient/proposal-rate-limiter.d.ts +93 -0
  44. package/dist/sentient/proposal-rate-limiter.d.ts.map +1 -0
  45. package/dist/sentient/propose-tick.d.ts +105 -0
  46. package/dist/sentient/propose-tick.d.ts.map +1 -0
  47. package/dist/sentient/propose-tick.js +549 -0
  48. package/dist/sentient/propose-tick.js.map +7 -0
  49. package/dist/sentient/state.d.ts +143 -0
  50. package/dist/sentient/state.d.ts.map +1 -0
  51. package/dist/sentient/state.js +85 -0
  52. package/dist/sentient/state.js.map +7 -0
  53. package/dist/sentient/tick.d.ts +193 -0
  54. package/dist/sentient/tick.d.ts.map +1 -0
  55. package/dist/sentient/tick.js +396 -0
  56. package/dist/sentient/tick.js.map +7 -0
  57. package/dist/system/platform-paths.js +36 -0
  58. package/dist/system/platform-paths.js.map +7 -0
  59. package/package.json +76 -8
  60. package/src/gc/__tests__/runner.test.ts +367 -0
  61. package/src/gc/__tests__/state.test.ts +169 -0
  62. package/src/gc/__tests__/transcript.test.ts +371 -0
  63. package/src/gc/daemon-entry.ts +26 -0
  64. package/src/gc/daemon.ts +251 -0
  65. package/src/gc/index.ts +14 -0
  66. package/src/gc/runner.ts +378 -0
  67. package/src/gc/state.ts +140 -0
  68. package/src/gc/transcript.ts +380 -0
  69. package/src/sentient/__tests__/brain-ingester.test.ts +154 -0
  70. package/src/sentient/__tests__/daemon.test.ts +472 -0
  71. package/src/sentient/__tests__/dream-tick.test.ts +200 -0
  72. package/src/sentient/__tests__/nexus-ingester.test.ts +138 -0
  73. package/src/sentient/__tests__/proposal-rate-limiter.test.ts +247 -0
  74. package/src/sentient/__tests__/propose-tick.test.ts +296 -0
  75. package/src/sentient/__tests__/test-ingester.test.ts +104 -0
  76. package/src/sentient/daemon-entry.ts +20 -0
  77. package/src/sentient/daemon.ts +471 -0
  78. package/src/sentient/index.ts +18 -0
  79. package/src/sentient/ingesters/brain-ingester.ts +122 -0
  80. package/src/sentient/ingesters/nexus-ingester.ts +171 -0
  81. package/src/sentient/ingesters/test-ingester.ts +205 -0
  82. package/src/sentient/proposal-rate-limiter.ts +172 -0
  83. package/src/sentient/propose-tick.ts +415 -0
  84. package/src/sentient/state.ts +229 -0
  85. package/src/sentient/tick.ts +688 -0
@@ -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,MAAM,GAAG,EAAE;AAC/C,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,UAAU,IAAI;AAAA,QACd,OAAO,+BAA+B,KAAK;AAAA,QAC3C,WAAW,eAAe,IAAI,EAAE,UAAU,IAAI,cAAc,mBAAmB,IAAI,cAAc,QAAQ,CAAC,CAAC,iBAAiB,mBAAmB;AAAA,QAC/I,QAAQ,mBAAmB,IAAI,gBAAgB,IAAI,aAAa;AAAA,MAClE;AAAA,IACF,CAAC;AAID,eAAW,KAAK,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM;AAE7C,WAAO;AAAA,EACT,SAAS,KAAK;AAEZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAQ,OAAO,MAAM,sCAA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AAA,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,143 @@
1
+ /**
2
+ * Sentient Loop State — Persistent state for the Tier-1 autonomous daemon.
3
+ *
4
+ * Stored in `.cleo/sentient-state.json` (plain JSON, not SQLite) to avoid
5
+ * SQLite WAL conflicts between the long-running daemon process and the
6
+ * main CLEO CLI process. Human-readable for debugging.
7
+ *
8
+ * The file is gitignored (see .gitignore §.cleo/ section) and survives
9
+ * restarts. Only `killSwitch`, `pid`, and `stats` fields are load-bearing
10
+ * across process boundaries.
11
+ *
12
+ * @see ADR-054 — Sentient Loop Tier-1 (autonomous task execution)
13
+ * @task T946
14
+ */
15
+ import type { Tier2Stats } from '@cleocode/contracts';
16
+ /** Schema version for sentient-state.json. Bump on breaking field changes. */
17
+ export declare const SENTIENT_STATE_SCHEMA_VERSION: "1.0";
18
+ /**
19
+ * Per-task failure/backoff tracking for stuck detection.
20
+ * Keyed by task id in {@link SentientState.stuckTasks}.
21
+ */
22
+ export interface StuckTaskRecord {
23
+ /** Number of consecutive failed spawn attempts for this task. */
24
+ attempts: number;
25
+ /** ISO-8601 timestamp of the most recent failure. */
26
+ lastFailureAt: string;
27
+ /** Unix epoch ms when the next retry becomes eligible. */
28
+ nextRetryAt: number;
29
+ /** Last captured failure reason (truncated to 500 chars). */
30
+ lastReason: string;
31
+ }
32
+ /**
33
+ * Rolling counters persisted across daemon restarts.
34
+ */
35
+ export interface SentientStats {
36
+ /** Total tasks picked by the loop since creation. */
37
+ tasksPicked: number;
38
+ /** Total tasks that completed successfully. */
39
+ tasksCompleted: number;
40
+ /** Total tasks whose spawn exited non-zero. */
41
+ tasksFailed: number;
42
+ /** Total ticks executed (including no-op ticks). */
43
+ ticksExecuted: number;
44
+ /** Total ticks aborted early because kill switch was active. */
45
+ ticksKilled: number;
46
+ }
47
+ /**
48
+ * Persistent sentient daemon state.
49
+ *
50
+ * Design principles:
51
+ * - `killSwitch` is the single load-bearing kill signal — the daemon re-checks
52
+ * it between every step of a tick, not just at tick start (Round 2 audit).
53
+ * - `stuckTasks` keys are task ids; values encode backoff + failure counts.
54
+ * - `stuckTimestamps` is a rolling 1-hour window used for the self-pause rule
55
+ * (5 stucks in 1 hour → killSwitch=true).
56
+ * - `stats` fields are monotonic counters that only ever increase.
57
+ */
58
+ export interface SentientState {
59
+ /** JSON schema version for forward-compatibility checks. */
60
+ schemaVersion: typeof SENTIENT_STATE_SCHEMA_VERSION;
61
+ /** PID of the currently running daemon process. null = daemon not running. */
62
+ pid: number | null;
63
+ /** ISO-8601 timestamp when the daemon was last started. */
64
+ startedAt: string | null;
65
+ /** ISO-8601 timestamp of the last completed tick (any outcome). */
66
+ lastTickAt: string | null;
67
+ /**
68
+ * Kill-switch flag. When true, the daemon re-checks at every step of a tick
69
+ * and exits cleanly without picking or spawning a task.
70
+ */
71
+ killSwitch: boolean;
72
+ /** Reason supplied when killSwitch was last set (diagnostic only). */
73
+ killSwitchReason: string | null;
74
+ /** Rolling counters; see {@link SentientStats}. */
75
+ stats: SentientStats;
76
+ /** Per-task backoff + failure metadata for retry/stuck detection. */
77
+ stuckTasks: Record<string, StuckTaskRecord>;
78
+ /**
79
+ * Unix-epoch-ms timestamps of `stuck` events within the last hour.
80
+ * When length ≥ 5 the daemon self-pauses (killSwitch=true).
81
+ */
82
+ stuckTimestamps: number[];
83
+ /**
84
+ * Currently-active task id (set while a spawn is in-flight, cleared afterward).
85
+ * Enables `status` to show the in-progress task during a long-running tick.
86
+ */
87
+ activeTaskId: string | null;
88
+ /**
89
+ * Tier-2 proposal queue enabled flag.
90
+ *
91
+ * Default: `false` — Tier 2 is OFF by default to prevent surprise proposal
92
+ * floods on first daemon start. Owner enables via `cleo sentient propose enable`
93
+ * (patches this flag). See ADR-054 §Tier-2.
94
+ *
95
+ * @task T1008
96
+ */
97
+ tier2Enabled: boolean;
98
+ /**
99
+ * Rolling counters for Tier-2 proposal activity.
100
+ *
101
+ * @task T1008
102
+ */
103
+ tier2Stats: Tier2Stats;
104
+ }
105
+ /** Default (empty) sentient state for fresh initialisation. */
106
+ export declare const DEFAULT_SENTIENT_STATE: SentientState;
107
+ /**
108
+ * Read the sentient state from disk.
109
+ *
110
+ * Returns the default state if the file does not exist or is malformed.
111
+ * Never throws — absence is not an error.
112
+ *
113
+ * @param statePath - Absolute path to sentient-state.json
114
+ */
115
+ export declare function readSentientState(statePath: string): Promise<SentientState>;
116
+ /**
117
+ * Write the sentient state to disk atomically via tmp-then-rename.
118
+ *
119
+ * Atomic write prevents partial reads if the daemon crashes mid-write.
120
+ *
121
+ * @param statePath - Absolute path to sentient-state.json
122
+ * @param state - State to persist
123
+ */
124
+ export declare function writeSentientState(statePath: string, state: SentientState): Promise<void>;
125
+ /**
126
+ * Patch a subset of fields in the sentient state file.
127
+ *
128
+ * Reads current state, merges patch, writes back. Nested `stats` merges
129
+ * with existing stats (never clobbered wholesale).
130
+ *
131
+ * @param statePath - Absolute path to sentient-state.json
132
+ * @param patch - Partial state to merge over the existing state
133
+ * @returns The merged state that was written to disk.
134
+ */
135
+ export declare function patchSentientState(statePath: string, patch: Partial<SentientState>): Promise<SentientState>;
136
+ /**
137
+ * Increment stats counters atomically.
138
+ *
139
+ * @param statePath - Absolute path to sentient-state.json
140
+ * @param delta - Partial stats to add to current counters
141
+ */
142
+ export declare function incrementStats(statePath: string, delta: Partial<SentientStats>): Promise<SentientState>;
143
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/sentient/state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,8EAA8E;AAC9E,eAAO,MAAM,6BAA6B,EAAG,KAAc,CAAC;AAE5D;;;GAGG;AACH,MAAM,WA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EF;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAgBjF;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAS/F;AAED;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CACtC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,CAAC,aAAa,CAAC,GAC5B,OAAO,CAAC,aAAa,CAAC,CASxB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,OAAO,CAAC,aAAa,CAAC,GAC5B,OAAO,CAAC,aAAa,CAAC,CAYxB"}
@@ -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,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A,EACjE;AACA,QAAM,UAAyB,EAAE,GAAG,SAAS,OAAO,UAAU;AAC9D,QAAM,mBAAmB,WAAW,OAAO;AAC3C,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Sentient Loop Tick — Single-iteration tick runner for the Tier-1 daemon.
3
+ *
4
+ * A tick is one complete pass of:
5
+ * 1. Check killSwitch (abort if true)
6
+ * 2. Pick an unblocked task via @cleocode/core/sdk
7
+ * 3. Check killSwitch again (abort if true)
8
+ * 4. Spawn worker via `cleo orchestrate spawn <taskId> --adapter <adapter>`
9
+ * 5. Check killSwitch again before recording result
10
+ * 6. Record success (receipt + stats) or failure (retry/backoff)
11
+ *
12
+ * Each step re-reads the state file so that a killSwitch flipped mid-tick is
13
+ * honoured on the very next instruction (Round 2 audit §1: "mid-experiment
14
+ * kill limbo").
15
+ *
16
+ * Rate limit: driven by the cron schedule (`*\/5 * * * *` → ≤12 ticks/hour ≤
17
+ * 12 spawns/hour). No in-tick sleep is required — cron provides the cadence.
18
+ *
19
+ * Scoped OUT: Tier 2 (propose) and Tier 3 (sandbox auto-merge) per ADR-054.
20
+ *
21
+ * @task T946
22
+ * @see ADR-054 — Sentient Loop Tier-1
23
+ */
24
+ import type { Task } from '@cleocode/contracts';
25
+ import { type SentientState } from './state.js';
26
+ /**
27
+ * Number of new brain observations since the last consolidation that causes
28
+ * the tick loop to trigger a dream cycle (volume tier).
29
+ * Configurable via the injected `dreamVolumeThreshold` option.
30
+ */
31
+ export declare const DREAM_VOLUME_THRESHOLD_DEFAULT = 50;
32
+ /**
33
+ * Number of consecutive no-task ticks before the idle dream trigger fires.
34
+ * Represents "N idle ticks" — when no task has been picked for this many
35
+ * consecutive ticks, the system is considered sufficiently idle.
36
+ */
37
+ export declare const DREAM_IDLE_TICKS_DEFAULT = 5;
38
+ /** Default adapter used when spawning workers. */
39
+ export declare const DEFAULT_ADAPTER: "claude-code";
40
+ /**
41
+ * Backoff delays between successive retries for the same task (milliseconds).
42
+ * Index n = delay before attempt n+1. After exhaustion the task is `stuck`.
43
+ * 30 s → 5 min → 30 min, then the task is marked stuck.
44
+ */
45
+ export declare const RETRY_BACKOFF_MS: readonly number[];
46
+ /**
47
+ * Maximum spawn attempts per task before it is classified as `stuck`.
48
+ * Matches RETRY_BACKOFF_MS.length but surfaced as a named constant for
49
+ * readability in tests and status output.
50
+ */
51
+ export declare const MAX_TASK_ATTEMPTS: number;
52
+ /**
53
+ * Threshold for self-pause: if this many tasks become `stuck` within a
54
+ * rolling 1-hour window, the daemon flips killSwitch=true and exits.
55
+ */
56
+ export declare const SELF_PAUSE_STUCK_THRESHOLD = 5;
57
+ /** Rolling window (ms) used for stuck-rate calculation. */
58
+ export declare const SELF_PAUSE_WINDOW_MS: number;
59
+ /** Reason stored on the state file when self-pause fires. */
60
+ export declare const SELF_PAUSE_REASON = "self-pause: 5 stuck tasks in 1 hour";
61
+ /** Max wall-clock time for a single spawn before forceful kill (30 min). */
62
+ export declare const SPAWN_TIMEOUT_MS: number;
63
+ /** Discriminant for the tick outcome. */
64
+ export type TickOutcomeKind = 'killed' | 'no-task' | 'backoff' | 'success' | 'failure' | 'stuck' | 'self-paused' | 'error';
65
+ /** Structured outcome of a single tick. */
66
+ export interface TickOutcome {
67
+ /** Discriminant describing how the tick ended. */
68
+ kind: TickOutcomeKind;
69
+ /** Task id that was the subject of this tick (if any). */
70
+ taskId: string | null;
71
+ /** Human-readable detail (one line). */
72
+ detail: string;
73
+ }
74
+ /** Options for {@link runTick}. */
75
+ export interface TickOptions {
76
+ /** Absolute path to the project root (contains `.cleo/`). */
77
+ projectRoot: string;
78
+ /** Absolute path to sentient-state.json. */
79
+ statePath: string;
80
+ /**
81
+ * Adapter to pass to `cleo orchestrate spawn --adapter`. Defaults to
82
+ * {@link DEFAULT_ADAPTER}. Overridden in tests via options.spawn.
83
+ */
84
+ adapter?: string;
85
+ /**
86
+ * Dry-run mode: skip the actual `cleo orchestrate spawn` subprocess and
87
+ * treat the pick as a no-op (still records picked stat). Used by
88
+ * `cleo sentient tick --dry-run`.
89
+ */
90
+ dryRun?: boolean;
91
+ /**
92
+ * Override for the spawn function — lets tests inject a deterministic fake
93
+ * without forking real subprocesses. Must resolve to an exit code.
94
+ *
95
+ * When omitted, the default implementation spawns
96
+ * `cleo orchestrate spawn <taskId> --adapter <adapter>` and resolves with
97
+ * the child's exit code.
98
+ */
99
+ spawn?: (taskId: string, adapter: string) => Promise<SpawnResult>;
100
+ /**
101
+ * Override for the "pick next unblocked task" source. Lets tests return
102
+ * a deterministic task without constructing a SQLite fixture.
103
+ */
104
+ pickTask?: (projectRoot: string) => Promise<Task | null>;
105
+ /**
106
+ * New observation count since last consolidation that triggers the volume
107
+ * dream cycle. Defaults to {@link DREAM_VOLUME_THRESHOLD_DEFAULT}.
108
+ * Pass 0 to disable volume trigger. Injected by tests.
109
+ */
110
+ dreamVolumeThreshold?: number;
111
+ /**
112
+ * Number of consecutive no-task ticks before the idle dream trigger fires.
113
+ * Defaults to {@link DREAM_IDLE_TICKS_DEFAULT}.
114
+ * Pass 0 to disable idle trigger. Injected by tests.
115
+ */
116
+ dreamIdleTicks?: number;
117
+ /**
118
+ * Override for the dream trigger function — lets tests assert dream calls
119
+ * without touching the real brain.db stack.
120
+ * Signature mirrors `checkAndDream` from `@cleocode/core`.
121
+ */
122
+ checkAndDream?: (projectRoot: string, opts?: {
123
+ volumeThreshold?: number;
124
+ inline?: boolean;
125
+ }) => Promise<{
126
+ triggered: boolean;
127
+ tier: string | null;
128
+ skippedReason?: string;
129
+ }>;
130
+ }
131
+ /** Result of a spawn invocation. */
132
+ export interface SpawnResult {
133
+ /** Process exit code (0 = success). */
134
+ exitCode: number;
135
+ /** Captured stdout, truncated by the caller if needed. */
136
+ stdout: string;
137
+ /** Captured stderr, truncated by the caller if needed. */
138
+ stderr: string;
139
+ }
140
+ /**
141
+ * Run a single tick of the sentient loop.
142
+ *
143
+ * Every checkpoint re-reads state so that a killSwitch flipped mid-tick is
144
+ * honoured on the next instruction.
145
+ *
146
+ * @param options - Tick options (see {@link TickOptions})
147
+ * @returns Structured outcome describing how the tick ended.
148
+ */
149
+ export declare function runTick(options: TickOptions): Promise<TickOutcome>;
150
+ /**
151
+ * Convenience wrapper used by the daemon cron handler and the `cleo sentient
152
+ * tick` CLI command. Reads state, runs a tick, swallows any unexpected
153
+ * exception so the cron scheduler never sees a rejection.
154
+ *
155
+ * After the tick completes, evaluates volume + idle dream triggers via
156
+ * {@link maybeTriggerDream}. Dream errors are swallowed independently so
157
+ * they never affect the tick outcome.
158
+ *
159
+ * @param options - Tick options
160
+ * @returns The tick outcome (or an `error` outcome if the tick itself threw).
161
+ */
162
+ export declare function safeRunTick(options: TickOptions): Promise<TickOutcome>;
163
+ /**
164
+ * Type-narrowing helper used by tests and status rendering to identify tick
165
+ * outcomes that consumed a retry attempt.
166
+ */
167
+ export declare function isFailureOutcome(outcome: TickOutcome): outcome is TickOutcome & {
168
+ kind: 'failure' | 'stuck' | 'self-paused';
169
+ };
170
+ /**
171
+ * Returns a shallow view of the current state's kill status.
172
+ * Exposed for diagnostic/test consumers.
173
+ */
174
+ export declare function getKillStatus(statePath: string): Promise<Pick<SentientState, 'killSwitch' | 'killSwitchReason'>>;
175
+ /**
176
+ * Reset dream-cycle in-process state.
177
+ *
178
+ * Intended for test teardown only — clears `consecutiveIdleTicks` so that
179
+ * successive test cases start from a clean slate.
180
+ *
181
+ * @internal
182
+ */
183
+ export declare function _resetDreamTickState(): void;
184
+ /**
185
+ * Return the current consecutive-idle-tick counter value.
186
+ *
187
+ * Read-only accessor for test assertions. The counter is reset to 0 whenever
188
+ * a task is picked, and incremented on each no-task tick.
189
+ *
190
+ * @internal
191
+ */
192
+ export declare function _getConsecutiveIdleTicks(): number;
193
+ //# sourceMappingURL=tick.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tick.d.ts","sourceRoot":"","sources":["../../src/sentient/tick.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;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