diff --git a/changelog.d/changed-retire-inception-api.md b/changelog.d/changed-retire-inception-api.md new file mode 100644 index 0000000000..607826bd41 --- /dev/null +++ b/changelog.d/changed-retire-inception-api.md @@ -0,0 +1 @@ +- The inception API, its watcher and the brainstorm agent's inception mode are retired in favour of Inception (spek) sessions. For one release, all 14 `/api/inception/*` routes answer `410 Gone` with a JSON pointer to `/api/sessions` and the docs; nothing is read or changed. The inception engine and its scaffold generator, the brainstorm bead watcher, the inception-approval run admission path and the boot-time brainstorm resume are removed. The dashboard snapshot builder no longer fetches `/api/inception/state`. The `brainstorm` agent is ideation-only and stays on-demand and parked at boot. The `${INCEPTION_*}` template variables always render empty, so custom templates keep rendering. Knowledge facts from past inception runs are kept: nothing deletes them, and Hive still reconnects the `/data/inception-wiki` vault on boot. `/data/inception/` stays on disk. diff --git a/dashboard/build-snapshot.mjs b/dashboard/build-snapshot.mjs index 75f9dfda72..b1361b929b 100644 --- a/dashboard/build-snapshot.mjs +++ b/dashboard/build-snapshot.mjs @@ -79,7 +79,7 @@ async function fetchJson(endpoint, fallback = '{}') { async function main() { console.log(`Fetching data from ${dashboardUrl} (mode: ${snapshotMode})...`); - const [statusRaw, historyRaw, trendsRaw, timelineRaw, configRaw, versionRaw, nousStatusRaw, nousLedgerRaw, nousPrinciplesRaw, kbStatsRaw, kbFactsRaw, contributorsRaw, leaderboardRaw, auditRaw, inceptionRaw] = await Promise.all([ + const [statusRaw, historyRaw, trendsRaw, timelineRaw, configRaw, versionRaw, nousStatusRaw, nousLedgerRaw, nousPrinciplesRaw, kbStatsRaw, kbFactsRaw, contributorsRaw, leaderboardRaw, auditRaw] = await Promise.all([ fetchJson('/api/status'), fetchJson('/api/history', '[]'), fetchJson('/api/trends?range=week', '[]'), @@ -93,11 +93,11 @@ async function main() { fetchJson('/api/knowledge', '{"facts":[]}'), fetchJson('/api/contributors', '[]'), fetchJson('/api/leaderboard', '{"leaderboard":[]}'), - // Audit Log and Project Inception load from their own endpoints on the - // live dashboard (via _deferredInit, which the snapshot strips), so bake - // them here or they sit at "Loading…" forever in the read-only preview. + // The Audit Log loads from its own endpoint on the live dashboard (via + // _deferredInit, which the snapshot strips), so bake it here or it sits + // at "Loading…" forever in the read-only preview. (/api/inception/state + // was retired with the inception API and now answers 410.) fetchJson('/api/audit', '{"entries":[]}'), - fetchJson('/api/inception/state', '{}'), ]); // Validate status @@ -362,17 +362,6 @@ async function main() { } } catch (e) {} - // Project Inception — same story: /api/inception/state loads via - // _deferredInit. Bake the state and render the panel once (statically). - try { - var _snapInception = ${inceptionRaw}; - // Mirror loadInceptionState(): only an active inception has a state. - if (typeof _inceptionState !== 'undefined') { - _inceptionState = (_snapInception && _snapInception.active) ? _snapInception.state : null; - } - if (typeof renderInception === 'function') renderInception(); - } catch (e) {} - // Fix leaderboard link to use snapshot base path document.querySelectorAll('a[href="/leaderboard"]').forEach(function(a) { a.href = '${basePath}/leaderboard'; diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 27248d52c8..02362a1a0a 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -66,7 +66,7 @@ }, { "name": "Inception", - "description": "Greenfield project scaffolding and ideation workflow" + "description": "Retired inception API: every route answers 410 Gone and points to Inception (spek) sessions" }, { "name": "Knowledge", @@ -23196,22 +23196,33 @@ "tags": [ "Inception" ], - "summary": "Download the produced scaffold as a zip", - "description": "Produces the current inception scaffold and streams it as a zip file attachment (application/zip). No JSON body on success.", + "summary": "Retired: download the produced scaffold as a zip", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Zip archive of scaffold files", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { - "application/zip": { + "application/json": { "schema": { - "type": "string", - "format": "binary" + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" + } + } } } } - }, - "404": { - "description": "Inception engine not initialized, no scaffold, or no files to download" } } } @@ -23221,11 +23232,12 @@ "tags": [ "Inception" ], - "summary": "Check whether the inception wiki has files", - "description": "Reports whether the inception knowledge wiki currently has any files on disk.", + "summary": "Retired: check whether the inception wiki has files", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Has-files flag", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23234,8 +23246,14 @@ "ok": { "type": "boolean" }, - "has_files": { - "type": "boolean" + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } @@ -23250,11 +23268,12 @@ "tags": [ "Inception" ], - "summary": "List ideation facts", - "description": "Returns the facts gathered so far during ideation, preferring the knowledge store's ideation facts and falling back to the inception engine's in-memory gathered facts.", + "summary": "Retired: list ideation facts", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Ideation facts", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23263,20 +23282,19 @@ "ok": { "type": "boolean" }, - "facts": { - "type": "array", - "items": { - "type": "object" - }, - "description": "knowledge.Fact entries" + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "503": { - "description": "Knowledge API not initialized" } } } @@ -23286,11 +23304,12 @@ "tags": [ "Inception" ], - "summary": "Produce (or fetch) the project scaffold", - "description": "Produces the scaffold result from the current inception state (file list/content). Not owner-gated.", + "summary": "Retired: produce (or fetch) the project scaffold", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Scaffold result", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23299,20 +23318,19 @@ "ok": { "type": "boolean" }, - "scaffold": { - "type": "object", - "description": "Scaffold result including a Files list; shape not fully enumerated here — see inception.ProduceScaffold." + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "404": { - "description": "No scaffold available" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23322,11 +23340,12 @@ "tags": [ "Inception" ], - "summary": "Get current inception state", - "description": "Returns the current inception engine state (idea capture / question / structure phase, etc). State shape is dynamic (inception engine internal state struct).", + "summary": "Retired: get current inception state", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Inception state", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23335,21 +23354,19 @@ "ok": { "type": "boolean" }, - "state": { - "type": "object", - "nullable": true, - "description": "Inception engine state; null when no session is active." + "error": { + "type": "string" }, - "active": { - "type": "boolean" + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23359,29 +23376,12 @@ "tags": [ "Inception" ], - "summary": "Submit answers to inception questions", - "description": "Submits a map of question-id to answer text, advancing the inception session. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "answers": { - "type": "object", - "additionalProperties": { - "type": "string" - } - } - } - } - } - } - }, + "summary": "Retired: submit answers to inception questions", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Updated state", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23390,19 +23390,19 @@ "ok": { "type": "boolean" }, - "state": { - "type": "object" + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Invalid body or submission rejected by the engine" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23412,11 +23412,12 @@ "tags": [ "Inception" ], - "summary": "Approve inception and complete it", - "description": "Advances the inception session to complete and re-pauses the brainstorm agent (on-demand only afterward). Requires owner role.", + "summary": "Retired: approve inception and complete it", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Approved", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23424,17 +23425,20 @@ "properties": { "ok": { "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Could not advance to complete" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23444,30 +23448,12 @@ "tags": [ "Inception" ], - "summary": "Record ideation facts", - "description": "Records a batch of ideation facts against the knowledge base. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "facts": { - "type": "array", - "items": { - "type": "object" - }, - "description": "knowledge.IdeationFact entries" - } - } - } - } - } - }, + "summary": "Retired: record ideation facts", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Recorded", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23475,17 +23461,20 @@ "properties": { "ok": { "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Invalid body or record failure" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23495,46 +23484,33 @@ "tags": [ "Inception" ], - "summary": "Import a wiki zip into the inception wiki directory", - "description": "Accepts a multipart/form-data upload (field name 'file') of a zip archive (max 10 MiB) and extracts it into the inception wiki directory. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "properties": { - "file": { - "type": "string", - "format": "binary" - } - }, - "required": [ - "file" - ] - } - } - } - }, + "summary": "Retired: import a wiki zip into the inception wiki directory", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Import result", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" + } + } } } } - }, - "400": { - "description": "Missing file, unreadable upload, or invalid zip" - }, - "500": { - "description": "Failed to create wiki directory" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23544,30 +23520,12 @@ "tags": [ "Inception" ], - "summary": "Set inception clarifying questions", - "description": "Sets the list of clarifying questions for the active inception session. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "items": { - "type": "object" - }, - "description": "knowledge.Question entries" - } - } - } - } - } - }, + "summary": "Retired: set inception clarifying questions", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Set", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23575,17 +23533,20 @@ "properties": { "ok": { "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Invalid body or rejected by engine" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23595,11 +23556,12 @@ "tags": [ "Inception" ], - "summary": "Reset the inception session", - "description": "Resets the inception engine state, clears any open brainstorm/inception beads, and re-pauses the brainstorm agent. Requires owner role.", + "summary": "Retired: reset the inception session", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Reset", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23607,17 +23569,20 @@ "properties": { "ok": { "type": "boolean" + }, + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "500": { - "description": "Reset failed" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23627,29 +23592,12 @@ "tags": [ "Inception" ], - "summary": "Start a brownfield repo scan", - "description": "Starts inception in brownfield mode against an existing repo URL. Optional force=true resets any existing session first (pausing brainstorm and clearing its beads). Kicks the brainstorm agent. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "repo_url": { - "type": "string" - }, - "force": { - "type": "boolean" - } - } - } - } - } - }, + "summary": "Retired: start a brownfield repo scan", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Started", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23658,19 +23606,19 @@ "ok": { "type": "boolean" }, - "state": { - "type": "object" + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Invalid body or scan could not start" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23680,29 +23628,12 @@ "tags": [ "Inception" ], - "summary": "Start a greenfield inception session", - "description": "Starts a new inception session from a free-text idea. Optional force=true resets any existing session first (pausing brainstorm and clearing its beads). Kicks the brainstorm agent. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "idea": { - "type": "string" - }, - "force": { - "type": "boolean" - } - } - } - } - } - }, + "summary": "Retired: start a greenfield inception session", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Started", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23711,19 +23642,19 @@ "ok": { "type": "boolean" }, - "state": { - "type": "object" + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { + "type": "string" } } } } } - }, - "400": { - "description": "Invalid body or start failed" - }, - "503": { - "description": "Inception engine not initialized" } } } @@ -23733,30 +23664,12 @@ "tags": [ "Inception" ], - "summary": "Rename the inception wiki", - "description": "Renames the inception knowledge vault (max 80 characters) and persists the name in inception state. Requires owner role.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "name": { - "type": "string", - "maxLength": 80 - } - }, - "required": [ - "name" - ] - } - } - } - }, + "summary": "Retired: rename the inception wiki", + "description": "Retired with the inception API in favour of Inception (spek) sessions. Answers 410 Gone for one release, with a pointer to /api/sessions.", + "deprecated": true, "responses": { - "200": { - "description": "Renamed", + "410": { + "description": "Gone: the inception API was retired in favour of Inception (spek) sessions. Use /api/sessions.", "content": { "application/json": { "schema": { @@ -23765,22 +23678,19 @@ "ok": { "type": "boolean" }, - "name": { + "error": { + "type": "string" + }, + "replacement": { + "type": "string" + }, + "docs": { "type": "string" } } } } } - }, - "400": { - "description": "Missing/too-long name" - }, - "404": { - "description": "Inception wiki vault not found" - }, - "503": { - "description": "Knowledge or inception not initialized" } } } diff --git a/src/cmd/hive/boot.go b/src/cmd/hive/boot.go index c6c32e3ab9..86b80e6303 100644 --- a/src/cmd/hive/boot.go +++ b/src/cmd/hive/boot.go @@ -169,7 +169,6 @@ type boot struct { knowledgeAPI *knowledge.KnowledgeAPI beadSynth *knowledge.BeadSynthesizer nousState *dashboard.NousState - inceptionEngine *knowledge.InceptionEngine rotationMgr *rotation.Manager questionAutoclose atomic.Pointer[questionclose.Manager] wd *watchdog.Reconciler diff --git a/src/cmd/hive/boot_dashboard_api_deps.go b/src/cmd/hive/boot_dashboard_api_deps.go index b173ec14de..e1ab452ae9 100644 --- a/src/cmd/hive/boot_dashboard_api_deps.go +++ b/src/cmd/hive/boot_dashboard_api_deps.go @@ -11,9 +11,9 @@ import ( // bootDashboardAPIDeps are the long-lived effects bootDashboardAPI performs // (#7571, step 2): registering the API surface on the dashboard server, -// installing the Forge App inventory provider, and starting the three -// background loops (installation-ID discovery, App-banner self-heal, the -// brainstorm inception watcher). Everything else the phase does — wiring the +// installing the Forge App inventory provider, and starting the two +// background loops (installation-ID discovery and App-banner self-heal). +// Everything else the phase does — wiring the // dashboard.Dependencies closures, applying the classified App state, // installing the Re-check callback — is plain assignment against the real // *dashboard.Server, which a test constructs cheaply with dashboard.NewServer. @@ -30,8 +30,7 @@ type bootDashboardAPIDeps struct { startInstallDiscovery func(ctx context.Context, tryDiscover func()) // startSelfHeal runs heal every githubAppSelfHealInterval until ctx is // done. It does NOT run immediately: boot has just checked coverage. - startSelfHeal func(ctx context.Context, heal func()) - startInceptionWatcher func(ctx context.Context, w *dashboard.InceptionWatcher) + startSelfHeal func(ctx context.Context, heal func()) } // githubAppDiscoveryInterval paces the installation-ID discovery loop. It @@ -56,7 +55,6 @@ func defaultBootDashboardAPIDeps() bootDashboardAPIDeps { startSelfHeal: func(ctx context.Context, heal func()) { go runTickLoop(ctx, githubAppSelfHealInterval, false, heal) }, - startInceptionWatcher: func(ctx context.Context, w *dashboard.InceptionWatcher) { go w.Run(ctx) }, } } diff --git a/src/cmd/hive/boot_dashboard_api_deps_test.go b/src/cmd/hive/boot_dashboard_api_deps_test.go index bea7683d49..cbbc798067 100644 --- a/src/cmd/hive/boot_dashboard_api_deps_test.go +++ b/src/cmd/hive/boot_dashboard_api_deps_test.go @@ -30,8 +30,6 @@ type bootDashboardAPIFake struct { forgeFn func() dashboard.ForgeAppInventory discoverTick func() healTick func() - inception *dashboard.InceptionWatcher - inceptionRun int } func newBootDashboardAPIFake() *bootDashboardAPIFake { @@ -46,10 +44,6 @@ func newBootDashboardAPIFake() *bootDashboardAPIFake { setForgeAppInventory: func(_ *dashboard.Server, fn func() dashboard.ForgeAppInventory) { f.forgeFn = fn }, startInstallDiscovery: func(_ context.Context, tick func()) { f.discoverTick = tick }, startSelfHeal: func(_ context.Context, tick func()) { f.healTick = tick }, - startInceptionWatcher: func(_ context.Context, w *dashboard.InceptionWatcher) { - f.inception = w - f.inceptionRun++ - }, } return f } @@ -277,17 +271,6 @@ func TestBootDashboardAPIWith_ForgeInventoryResolvesTheActiveKey(t *testing.T) { } } -func TestBootDashboardAPIWith_InceptionWatcherNeedsTheBrainstormStore(t *testing.T) { - f := newBootDashboardAPIFake() - b := newBootDashboardAPIBoot(t, f, bootDashboardAPIConfig()) - - b.bootDashboardAPIWith(f.deps) - - if f.inceptionRun != 0 { - t.Fatal("inception watcher started without a brainstorm bead store to watch") - } -} - func TestRunTickLoop_FiresOnScheduleAndStopsOnCancel(t *testing.T) { const interval = 5 * time.Millisecond fired := make(chan struct{}, 16) diff --git a/src/cmd/hive/boot_knowledge_deps.go b/src/cmd/hive/boot_knowledge_deps.go index 11f2f5c960..85ac848aa2 100644 --- a/src/cmd/hive/boot_knowledge_deps.go +++ b/src/cmd/hive/boot_knowledge_deps.go @@ -6,8 +6,6 @@ import ( "os" "time" - "github.com/hivecommons/hive/crux" - "github.com/hivecommons/hive/pkg/campaignexport" "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/dashboard" @@ -23,16 +21,17 @@ const ( beadSynthVaultDefaultPath = "/data/vaults/bead-synth-wiki" // knowledgeGraphStorePath is the SQLite-backed knowledge graph on the PVC. knowledgeGraphStorePath = "/data/graph/knowledge.db" - // inceptionDataDir roots the inception engine's persisted state. + // inceptionDataDir roots what the retired inception engine left on the + // PVC: the inception-wiki vault, its state file and campaign archives. inceptionDataDir = "/data" ) // bootKnowledgeDeps are bootKnowledge's long-lived effects (#7571, step 2): // vault init/seed on disk, the background loops (git sync, bead synth, // promotion, graph store open + wiring, workspace cleanup), the nous state -// read, the inception engine (reads /data), and the brainstorm restart. The -// knowledge API, vault connects, bead synthesizer, and inception decision -// run for real; cfg paths point a test at temp dirs. +// read, the inception-wiki reconnect and the retired-campaigns export (both +// read /data). The knowledge API, vault connects and bead synthesizer run for +// real; cfg paths point a test at temp dirs. type bootKnowledgeDeps struct { initVaultRepo func(path string, logger *slog.Logger) error seedVaultContent func(vaultPath string, logger *slog.Logger) error @@ -43,11 +42,13 @@ type bootKnowledgeDeps struct { startWorkspaceCleanup func(ctx context.Context, logger *slog.Logger, audit *dashboard.AuditLog) ensureNousDirs func(logger *slog.Logger) loadNousState func(logger *slog.Logger) *dashboard.NousState - newInceptionEngine func(api *knowledge.KnowledgeAPI, logger *slog.Logger) *knowledge.InceptionEngine + // reconnectInceptionWiki keeps facts from past inception runs (the + // inception-wiki vault) served after the inception engine's retirement; + // nil skips it. + reconnectInceptionWiki func(api *knowledge.KnowledgeAPI, logger *slog.Logger) // exportRetiredCampaigns writes the one-time read-only export of retired // inception campaign archives and campaign Jam data; nil skips it. exportRetiredCampaigns func(cfg *config.Config, logger *slog.Logger) - restartBrainstorm func(ctx context.Context, mgr crux.Runtime, msg string) error // startConnectorSyncer runs the knowledge.connectors syncer (#11069); // nil leaves it built but not started. startConnectorSyncer func(ctx context.Context, s *connector.Syncer) @@ -80,15 +81,12 @@ func defaultBootKnowledgeDeps() bootKnowledgeDeps { } }, loadNousState: loadNousState, - newInceptionEngine: func(api *knowledge.KnowledgeAPI, logger *slog.Logger) *knowledge.InceptionEngine { - return knowledge.NewInceptionEngine(inceptionDataDir, api, logger) + reconnectInceptionWiki: func(api *knowledge.KnowledgeAPI, logger *slog.Logger) { + knowledge.ReconnectInceptionWiki(inceptionDataDir, api, logger) }, exportRetiredCampaigns: exportRetiredCampaigns, - restartBrainstorm: func(ctx context.Context, mgr crux.Runtime, msg string) error { - return mgr.RestartWithBootstrap(ctx, "brainstorm", msg) - }, - startConnectorSyncer: func(ctx context.Context, s *connector.Syncer) { go s.Run(ctx) }, - startPublishMirror: func(ctx context.Context, m *connector.Mirror) { go m.Start(ctx) }, + startConnectorSyncer: func(ctx context.Context, s *connector.Syncer) { go s.Run(ctx) }, + startPublishMirror: func(ctx context.Context, m *connector.Mirror) { go m.Start(ctx) }, } } diff --git a/src/cmd/hive/boot_knowledge_deps_test.go b/src/cmd/hive/boot_knowledge_deps_test.go index 73f9d589be..0192518577 100644 --- a/src/cmd/hive/boot_knowledge_deps_test.go +++ b/src/cmd/hive/boot_knowledge_deps_test.go @@ -2,14 +2,12 @@ package main import ( "context" - "encoding/json" "errors" "log/slog" "os" "path/filepath" "strings" "testing" - "time" "github.com/hivecommons/hive/crux/cruxtest" @@ -35,8 +33,7 @@ type bootKnowledgeFake struct { cleanupAudit *dashboard.AuditLog nousDirs int inceptionDir string - restarts []string - restartErr error + wikiReconnects int } func newBootKnowledgeFake(t *testing.T) *bootKnowledgeFake { @@ -64,12 +61,9 @@ func newBootKnowledgeFake(t *testing.T) *bootKnowledgeFake { startWorkspaceCleanup: func(_ context.Context, _ *slog.Logger, a *dashboard.AuditLog) { f.cleanupAudit = a }, ensureNousDirs: func(*slog.Logger) { f.nousDirs++ }, loadNousState: func(*slog.Logger) *dashboard.NousState { return &dashboard.NousState{Mode: "observe"} }, - newInceptionEngine: func(api *knowledge.KnowledgeAPI, logger *slog.Logger) *knowledge.InceptionEngine { - return knowledge.NewInceptionEngine(f.inceptionDir, api, logger) - }, - restartBrainstorm: func(_ context.Context, _ crux.Runtime, msg string) error { - f.restarts = append(f.restarts, msg) - return f.restartErr + reconnectInceptionWiki: func(api *knowledge.KnowledgeAPI, logger *slog.Logger) { + f.wikiReconnects++ + knowledge.ReconnectInceptionWiki(f.inceptionDir, api, logger) }, } return f @@ -99,19 +93,6 @@ func newBootKnowledgeBoot(t *testing.T, cfg *config.Config) *boot { return b } -func writeInceptionState(t *testing.T, dir string, phase knowledge.InceptionPhase, startedAt time.Time) { - t.Helper() - st := knowledge.InceptionState{Phase: phase, Mode: knowledge.InceptionGreenfield, IdeaText: "x", StartedAt: startedAt} - data, _ := json.Marshal(st) - path := filepath.Join(dir, "inception", "state.json") - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, data, 0o644); err != nil { - t.Fatal(err) - } -} - func TestBootKnowledgeWithMinimalConfigAutoEnablesFileAPI(t *testing.T) { cfg := bootKnowledgeConfig(t) b := newBootKnowledgeBoot(t, cfg) @@ -142,14 +123,11 @@ func TestBootKnowledgeWithMinimalConfigAutoEnablesFileAPI(t *testing.T) { if b.nousState == nil || b.nousState.SnapshotDir != nousSnapshotDir { t.Fatalf("nous state = %+v", b.nousState) } - if b.inceptionEngine == nil || b.sched.GetInception() != b.inceptionEngine { - t.Fatal("inception engine not wired into scheduler") + if f.wikiReconnects != 1 { + t.Fatalf("past inception facts must be reconnected once at boot, got %d", f.wikiReconnects) } if !b.agentMgr.IsPaused("brainstorm") { - t.Fatal("brainstorm must be paused on-demand when no inception is active") - } - if len(f.restarts) != 0 { - t.Fatalf("no inception means no restart: %v", f.restarts) + t.Fatal("brainstorm must be paused on-demand at boot") } } @@ -317,72 +295,3 @@ func TestBootKnowledgeWithGraphStoreWiring(t *testing.T) { } }) } - -func TestBootKnowledgeWithInceptionResume(t *testing.T) { - t.Run("active inception restarts brainstorm", func(t *testing.T) { - b := newBootKnowledgeBoot(t, bootKnowledgeConfig(t)) - var log strings.Builder - b.logger = slog.New(slog.NewTextHandler(&log, nil)) - f := newBootKnowledgeFake(t) - writeInceptionState(t, f.inceptionDir, knowledge.PhaseClarify, time.Now().Add(-time.Minute)) - - b.bootKnowledgeWith(f.deps) - - if len(f.restarts) != 1 { - t.Fatalf("restarts = %v", f.restarts) - } - if b.agentMgr.IsPaused("brainstorm") { - t.Fatal("brainstorm must not be paused while resuming an active inception") - } - if !strings.Contains(log.String(), "brainstorm resumed for active inception") { - t.Fatalf("log:\n%s", log.String()) - } - }) - t.Run("restart failure is a warning", func(t *testing.T) { - b := newBootKnowledgeBoot(t, bootKnowledgeConfig(t)) - var log strings.Builder - b.logger = slog.New(slog.NewTextHandler(&log, nil)) - f := newBootKnowledgeFake(t) - f.restartErr = errors.New("no runtime") - writeInceptionState(t, f.inceptionDir, knowledge.PhaseClarify, time.Now().Add(-time.Minute)) - - b.bootKnowledgeWith(f.deps) - - if !strings.Contains(log.String(), "failed to resume brainstorm for active inception") { - t.Fatalf("log:\n%s", log.String()) - } - }) - t.Run("stale inception is reset and brainstorm paused", func(t *testing.T) { - b := newBootKnowledgeBoot(t, bootKnowledgeConfig(t)) - var log strings.Builder - b.logger = slog.New(slog.NewTextHandler(&log, nil)) - f := newBootKnowledgeFake(t) - writeInceptionState(t, f.inceptionDir, knowledge.PhaseClarify, time.Now().Add(-time.Hour)) - - b.bootKnowledgeWith(f.deps) - - if len(f.restarts) != 0 { - t.Fatalf("stale inception must not restart: %v", f.restarts) - } - if st := b.inceptionEngine.GetState(); st != nil { - t.Fatalf("inception not reset: %+v", st) - } - if !b.agentMgr.IsPaused("brainstorm") { - t.Fatal("brainstorm must be paused after a stale reset") - } - if !strings.Contains(log.String(), "skipping stale inception resume") { - t.Fatalf("log:\n%s", log.String()) - } - }) - t.Run("completed inception pauses brainstorm", func(t *testing.T) { - b := newBootKnowledgeBoot(t, bootKnowledgeConfig(t)) - f := newBootKnowledgeFake(t) - writeInceptionState(t, f.inceptionDir, knowledge.PhaseComplete, time.Now()) - - b.bootKnowledgeWith(f.deps) - - if len(f.restarts) != 0 || !b.agentMgr.IsPaused("brainstorm") { - t.Fatalf("restarts=%v paused=%v", f.restarts, b.agentMgr.IsPaused("brainstorm")) - } - }) -} diff --git a/src/cmd/hive/main.go b/src/cmd/hive/main.go index 2038c61289..71ab7af0e0 100644 --- a/src/cmd/hive/main.go +++ b/src/cmd/hive/main.go @@ -1159,7 +1159,6 @@ func (b *boot) wireBootClosures() { GHTokenScopes: b.ghAuth.TokenScopes, Tokens: b.tokenCollector, Knowledge: b.knowledgeAPI, - Inception: b.inceptionEngine, Nous: b.nousState, Scheduler: b.sched, KnowledgePrimer: knowledgePrimerControl{b: b}, @@ -3346,39 +3345,17 @@ func (b *boot) bootKnowledgeWith(deps bootKnowledgeDeps) { b.nousState = deps.loadNousState(b.logger) b.nousState.SnapshotDir = nousSnapshotDir - b.inceptionEngine = deps.newInceptionEngine(b.knowledgeAPI, b.logger) - b.sched.SetInception(b.inceptionEngine) - - // Brainstorm is on-demand only. Only restart with bootstrap during - // capture phase — structure/scaffold phases don't need a fresh kick - // and restarting would revert the phase back to capture. - // Skip stale inceptions (> 10 min old) — these are leftovers from - // previous runs that would interfere with new inceptions. - const staleInceptionThreshold = 10 * time.Minute - if state := b.inceptionEngine.GetState(); state != nil && - state.Phase != knowledge.PhaseComplete && - state.Phase != knowledge.PhaseScaffold { - if time.Since(state.StartedAt) < staleInceptionThreshold { - msg := b.sched.BuildAgentMessage("brainstorm", nil, nil) - if err := deps.restartBrainstorm(b.ctx, b.agentMgr, msg); err != nil { - b.logger.Warn("failed to resume brainstorm for active inception", "error", err) - } else { - b.logger.Info("brainstorm resumed for active inception", "phase", state.Phase) - } - } else { - b.logger.Info("skipping stale inception resume — resetting", - "phase", state.Phase, - "age", time.Since(state.StartedAt).Round(time.Second), - ) - _ = b.inceptionEngine.Reset() - if err := b.agentMgr.Pause("brainstorm", "startup", "stale inception cleared — on-demand only"); err != nil { - b.logger.Debug("brainstorm pause on startup", "error", err) - } - } - } else { - if err := b.agentMgr.Pause("brainstorm", "startup", "on-demand agent — triggered by inception only"); err != nil { - b.logger.Debug("brainstorm pause on startup", "error", err) - } + // The inception engine was retired in favour of Inception (spek) + // sessions. Facts past inception runs wrote to the inception-wiki vault + // stay served: reconnect that vault as the engine used to. + if deps.reconnectInceptionWiki != nil { + deps.reconnectInceptionWiki(b.knowledgeAPI, b.logger) + } + + // Brainstorm is on-demand only: park it at boot, as before. Nothing + // starts it automatically any more. + if err := b.agentMgr.Pause("brainstorm", "startup", "on-demand agent — kicked only on request"); err != nil { + b.logger.Debug("brainstorm pause on startup", "error", err) } // Provider rotation (RFC #3958): opt-in automatic failover when a @@ -3812,9 +3789,6 @@ func (b *boot) bootDashboardAPIWith(deps bootDashboardAPIDeps) { } } - if brainstormBeads, ok := b.beadStores["brainstorm"]; ok { - deps.startInceptionWatcher(b.ctx, dashboard.NewInceptionWatcher(brainstormBeads, b.inceptionEngine, b.sched, b.agentMgr, b.gov, b.logger)) - } } // bootPolicies applies the ACMM pack planACMMBoot chose and starts the @@ -6274,25 +6248,6 @@ func (b *boot) runLoopWith(deps runLoopDeps) { for _, name := range restarted { b.dashSrv.AuditLog("system", "restart", "trigger=crash-recovery", name) } - // If brainstorm crashed during inception, re-kick via SendKick. - // SendKick waits for the CLI to be ready and sends the message - // If brainstorm crashed during inception, re-kick with bootstrap. - // The table parser in the watcher will catch questions from the - // agent's output even if bd create doesn't execute. - for _, name := range restarted { - if name == "brainstorm" && b.inceptionEngine != nil { - if state := b.inceptionEngine.GetState(); state != nil && state.Phase == knowledge.PhaseCapture { - msg := b.sched.BuildAgentMessage("brainstorm", nil, b.sched.GetLastActionable()) - if err := b.agentMgr.RestartWithBootstrap(b.ctx, "brainstorm", msg); err != nil { - b.logger.Warn("inception re-kick after crash failed", "error", err) - } else { - b.logger.Info("brainstorm re-kicked after crash", "phase", state.Phase) - b.dashSrv.AuditLog("system", "kick", "trigger=inception-crash-recovery", "brainstorm") - } - b.gov.RecordKick("brainstorm") - } - } - } // Watchdog sweep (RFC #4665): synchronous but bounded — every // probe carries a deadline and restarts run detached under a hard // timeout, so a wedged agent can never stall this tick. Tick diff --git a/src/crux/agent/pluk_dirs.go b/src/crux/agent/pluk_dirs.go index 6273fb36ba..5e0ec14c64 100644 --- a/src/crux/agent/pluk_dirs.go +++ b/src/crux/agent/pluk_dirs.go @@ -40,8 +40,7 @@ var plukLogFileMode = os.FileMode(0o660) // plukSessionLogPath is where pluk's events for one tmux session are appended. // It mirrors what pluk's own `attach` builds — /logs/.jsonl — -// and is the path src/deploy/hive-panes.sh globs and -// src/pkg/dashboard/inception_watcher.go tails. +// and is the path src/deploy/hive-panes.sh globs. func plukSessionLogPath(runDir, session string) string { return filepath.Join(runDir, "logs", session+".jsonl") } @@ -147,9 +146,8 @@ func ensurePlukRunDirs(runDir string) error { // createWriteStream, appendFile, writeFile or openSync in any module — and // pipe-pane only feeds the pane into the command's stdin; it does nothing with // the command's stdout. So without the `>>` here the events are produced and -// discarded, /var/run/pluk/logs stays empty, and both consumers -// (src/deploy/hive-panes.sh, src/pkg/dashboard/inception_watcher.go) wait on -// files that never appear. +// discarded, /var/run/pluk/logs stays empty, and the consumer +// (src/deploy/hive-panes.sh) waits on files that never appear. // // The redirect and --include-raw were lost together in #1759, which replaced // the Go `pluk-publish` binary — a publisher, which wrote the log itself — with diff --git a/src/crux/agent/pluk_publisher_test.go b/src/crux/agent/pluk_publisher_test.go index d46a69bc7f..ff332ba0f3 100644 --- a/src/crux/agent/pluk_publisher_test.go +++ b/src/crux/agent/pluk_publisher_test.go @@ -83,15 +83,14 @@ func TestPlukPipePaneCmdQuotesEveryOperand(t *testing.T) { } } -// TestPlukSessionLogPathMatchesItsConsumers pins the path against the two -// readers, which hardcode it independently: inception_watcher.go builds -// "/hive-brainstorm.jsonl" and hive-panes.sh globs -// "$LOG_DIR"/hive-*.jsonl. If this drifts, both go quiet without erroring. +// TestPlukSessionLogPathMatchesItsConsumers pins the path against its +// reader, which hardcodes it independently: hive-panes.sh globs +// "$LOG_DIR"/hive-*.jsonl. If this drifts, it goes quiet without erroring. func TestPlukSessionLogPathMatchesItsConsumers(t *testing.T) { got := plukSessionLogPath(productionPlukRunDir, "hive-brainstorm") const want = "/var/run/pluk/logs/hive-brainstorm.jsonl" if got != want { - t.Fatalf("log path = %q, want %q — the inception watcher tails the literal %q", + t.Fatalf("log path = %q, want %q — hive-panes.sh globs the literal %q", got, want, want) } diff --git a/src/crux/agentparse/agentparse.go b/src/crux/agentparse/agentparse.go index abf94122ba..e2ffbf5289 100644 --- a/src/crux/agentparse/agentparse.go +++ b/src/crux/agentparse/agentparse.go @@ -5,8 +5,7 @@ // These parsers were lifted out of the inception (Level-1 ideation) watcher so // that other subsystems — notably planning intelligence (epic -> bead-DAG // decomposition) — can reuse the exact same battle-tested extraction logic -// instead of re-implementing it. Inception continues to use these via thin, -// behavior-preserving adapters. +// instead of re-implementing it. (The inception watcher itself was retired.) // // An Item carries a Title plus optional Default and Category metadata; callers // map Items into their own domain types (questions, sub-tasks, ...). diff --git a/src/crux/runtime.go b/src/crux/runtime.go index 97d911c1e7..384edafec6 100644 --- a/src/crux/runtime.go +++ b/src/crux/runtime.go @@ -63,16 +63,15 @@ type Lifecycle interface { // Dashboard: api_agent_config.go, api_agent_control.go. Restart(ctx context.Context, name string) error // RestartWithBootstrap relaunches an agent with a one-off bootstrap - // prompt. Dashboard: inception watcher. + // prompt. RestartWithBootstrap(ctx context.Context, name, prompt string) error // Pause quiesces an agent with a machine trigger and a human reason. - // Dashboard: api_packs.go (ACMM pack level), inception_handlers.go. + // Dashboard: api_packs.go (ACMM pack level). Pause(name, trigger, reason string) error // PauseBy is Pause with the acting user recorded. Dashboard: // api_agent_control.go. PauseBy(name, trigger, reason, by string) error - // Resume lifts a pause. Dashboard: api_agent_control.go, api_packs.go, - // inception_handlers.go. + // Resume lifts a pause. Dashboard: api_agent_control.go, api_packs.go. Resume(ctx context.Context, name, trigger, reason string) error // IsPaused reports whether an agent is paused. Dashboard: api_packs.go. IsPaused(name string) bool @@ -112,7 +111,7 @@ type Observer interface { // Kicker delivers prompts to running agents and exposes kick records. type Kicker interface { // SendKick types a message into the agent's pane synchronously. - // Dashboard: api_linear_agent.go, inception_handlers.go, swarm.go. + // Dashboard: api_linear_agent.go, swarm.go. SendKick(name string, message string) error // SendKickAsync queues a kick and returns whether delivery started; the // result is observed through KickDispatchState. Dashboard: diff --git a/src/docs/acmm-policy-matrix.md b/src/docs/acmm-policy-matrix.md index 21ec2b123f..59b866aae5 100644 --- a/src/docs/acmm-policy-matrix.md +++ b/src/docs/acmm-policy-matrix.md @@ -76,7 +76,7 @@ level-specific qualifications, not just its template's `full` suffix. ### L1 — Inception (Assisted) (2 agents) -A single interactive advisor helps with repo setup and architecture decisions. Guide agent makes advisory beads. Brainstorm agent handles project inception — turning raw ideas into structured KB facts and scaffold. No feedback loops. See the [Inception operator guide](inception.md) for the end-to-end workflow and API reference. +A single interactive advisor helps with repo setup and architecture decisions. Guide agent makes advisory beads. Brainstorm agent proposes ideas as advisory beads; turning a raw idea into a project happens in Inception (spek) sessions. No feedback loops. See [Inception](inception.md). | Agent | Mode | Template | |-------|------|----------| diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index 27323e4e56..4c8f7f7854 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -314,7 +314,7 @@ spec omits `launch_cmd`, Hive still builds the backend command normally. # hive-merge / hive-open-issue relays — not merely # discouraged. See docs/per-repo-agents.md. on_demand: false # true = never kicked by the governor timer; - # only triggered explicitly (e.g. inception) + # only triggered explicitly (e.g. by you) continuous: false # legacy shorthand: continuous in every # non-quiet governor mode; prefer per-mode # cadence: surge: continuous @@ -846,7 +846,7 @@ governor: - **Downtime catch-up.** If Hive was down at a scheduled time, restart/eval grants at most one catch-up kick when the missed occurrence is within the last 10 minutes. Older missed occurrences are skipped and the next future occurrence is used. - **Per-agent, per-mode intervals.** Anything Go's duration parser accepts works (`5m`, `2h`) for interval mode. - **Pausing.** The value `pause` (or `paused`) suspends an agent for that mode without disabling it. -- **On-demand agents** (`on_demand: true`) are skipped by the governor timer entirely — they run only when explicitly triggered (the inception workflow drives `brainstorm` this way). +- **On-demand agents** (`on_demand: true`) are skipped by the governor timer entirely — they run only when explicitly triggered (`brainstorm` works this way). - **Continuous agents** take another work prompt after their current turn finishes and a cooldown expires. Configure this per mode in the dashboard's **Cadences** form; see the settings and diagnostics below. - **Budget.** When the weekly token budget is exhausted, kicks are suppressed hive-wide (exempt agents excepted) until the period rolls over. @@ -1339,7 +1339,7 @@ is in [acmm-policy-matrix.md](acmm-policy-matrix.md#what-hive-will-say-on-github | `display_name`, `emoji`, `color` | the dashboard roster grows past a handful and you want it scannable | | a model pin 📌 | you need reproducible behavior and the governor keeps optimizing your model away | | `cli_pinned: true` | a CLI update broke an agent once and you never want that surprise again | -| `on_demand: true` | the agent should run only when something (you, inception) explicitly fires it | +| `on_demand: true` | the agent should run only when something (usually you) explicitly fires it | | cadence overrides | the pack's rhythm doesn't match your project — a hot repo may want `scanner: 15m`, a quiet one `4h` | | `pause` in a mode | an agent is noisy exactly when the queue is deep (e.g. pause `architect` during surge) | | `stale_timeout` | you changed cadences — keep it above the longest interval | diff --git a/src/docs/agent-logging.md b/src/docs/agent-logging.md index f0e9e4a562..b676ec7067 100644 --- a/src/docs/agent-logging.md +++ b/src/docs/agent-logging.md @@ -30,11 +30,11 @@ via `tmux pipe-pane`. `` is the agent's configured CLI backend is an inference backend. If the `pluk` binary is not on `PATH`, attachment is skipped silently — the agent still runs, it just has no peer-visible log. -Pluk also exposes a `send` subcommand. `pkg/dashboard/inception_handlers.go` -uses `pluk send hive- --text= --enter` as a fallback way to -deliver a kick message to an agent's pane when the normal `SendKick` path -fails, because it writes through a named FIFO and confirms delivery via a -`command_received` event rather than relying on `tmux send-keys`. +Pluk also exposes a `send` subcommand (`pluk send hive- +--text= --enter`), which writes through a named FIFO and confirms +delivery via a `command_received` event rather than relying on `tmux +send-keys`. Hive no longer calls it: its only caller was the retired inception +workflow's fallback kick path. ## Availability conditions @@ -87,8 +87,7 @@ reads work — leaving creation to the shell's `>>` would take whatever umask th pane shell carries and a tight one yields a log no peer can read. Nothing rotates or caps these files. `hive-panes` only ever reads the last 2000 -lines and the inception subscriber seeks to the end, so no consumer needs the -history, but the files themselves grow for the life of the container. +lines, so no consumer needs the history, but the files themselves grow for the life of the container. The event envelope, as read by Hive's own code, is: @@ -97,14 +96,13 @@ The event envelope, as read by Hive's own code, is: ``` `type` is a string discriminator; `data` is a flat string-to-string map whose -keys depend on `type`. Hive's dashboard subscribes to this stream for the -`brainstorm` session (`pkg/dashboard/inception_watcher.go`, `plukEvent`) and -reacts to a subset of event types: +keys depend on `type`. Hive's dashboard used to subscribe to this stream for +the `brainstorm` session (the inception watcher, retired with the inception +workflow); `hive-panes.sh` is the reader today. The event types: - `raw_output` — captured pane output. The text is on `data.line`, and only - there. Both readers now agree: `hive-panes.sh` has always read `data.line`, - and the dashboard's Go subscriber (`handlePlukEvent` in - `inception_watcher.go`) read `data.message` until + there. `hive-panes.sh` has always read `data.line`; the retired dashboard + subscriber read `data.message` until [#4285](https://github.com/hivecommons/hive/issues/4285) corrected it, which had left its whole `raw_output` arm dead. Earlier revisions of this page advised new consumers to check both keys; that was wrong, and generalised @@ -115,20 +113,12 @@ reacts to a subset of event types: publisher has to pass `--include-raw` or no such event is ever emitted. It is the only event type `hive-panes.sh` consumes, so peer awareness depends on that flag. -- `state_change` — `data.state` is `"working"` or `"idle"`. The inception - watcher uses idle transitions to decide when to re-kick a stalled agent or - fall back to auto-generating questions/facts. -- `rate_limit` — `data.message` describes a provider rate limit; the watcher - suppresses retries for a cooldown window when it sees this. -- `error` — `data.message` describes an agent-side error; logged, not acted - on beyond that. -- `tool_call_completed` — no payload used; the watcher treats this as a cue - to poll bead state immediately (e.g. after a `bd create`/`bd update`) - instead of waiting for the next timer tick. - -Only the `brainstorm` session is subscribed to for real-time event handling -today. Other agents' logs exist under the same directory in the same format -but are not tailed by any in-process Hive consumer — they exist for +- `state_change` — `data.state` is `"working"` or `"idle"`. +- `rate_limit` — `data.message` describes a provider rate limit. +- `error` — `data.message` describes an agent-side error. +- `tool_call_completed` — no payload; emitted after a tool call finishes. + +No in-process Hive consumer tails these logs today. They exist for `hive-panes` and manual/operator inspection. ## How `hive-panes` reads it @@ -173,13 +163,6 @@ lifetime the files grow unbounded from Hive's side. Any rotation behavior `@kubestellar/pluk` version's own behavior if you need to reason about disk growth, since Hive does not manage it. -The dashboard's own subscriber (`runPlukSubscriber` in -`inception_watcher.go`) detects rotation defensively: it compares the open -file handle's inode against the on-disk file on each idle poll and, if they -differ, logs `"pluk log rotated, restarting subscriber"` and returns so the -caller can reopen — but this is a consumer-side safeguard, not evidence that -Hive itself rotates the file. - ## Using peer awareness as an agent - Use `hive-panes [lines]` when you need situational awareness of what other @@ -189,7 +172,7 @@ Hive itself rotates the file. - Treat its output as recent raw terminal text, not structured data — it is ANSI-stripped CLI output, not a machine-readable event feed. Do not parse it for automation; if you need structured events, read the JSONL files - directly the way `inception_watcher.go` does. + directly. - Avoid depending on it being present. It requires `hive-panes.sh` to be deployed and `pluk` to have attached successfully; on a deployment that omits either, `/var/run/pluk/logs` will not exist and the command exits diff --git a/src/docs/api-reference/agents-and-controls.md b/src/docs/api-reference/agents-and-controls.md index 1a59c6b438..c6e8aef250 100644 --- a/src/docs/api-reference/agents-and-controls.md +++ b/src/docs/api-reference/agents-and-controls.md @@ -23,16 +23,16 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/model-advisor` | Dashboard auth/session | Model Advisor | `pkg/dashboard/api.go:156` | | `GET` | `/api/governor/pr-models` | Dashboard auth/session | Agent-authored PR distribution by normalized attribution model/backend for `window=7d`, `30d`, or `all`, including per-model rework stats and the top 10 most-reworked PRs | `pkg/dashboard/api.go:157` | | `GET` | `/api/reviewer/accuracy` | Dashboard auth/session | Reviewer verdict calibration for the configured window: false-approve/false-block rates and confidence buckets per perspective and reviewer model | `pkg/dashboard/api.go:220` | -| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:500` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:503` | -| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:504` | -| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:508` | +| `GET` | `/api/review/queue` | Dashboard auth/session | PR review queue: every open PR (agent and contributor, actionable and held) ranked by triage class, confidence band, CI state and age, with per-PR `reasons`; unreviewed items carry `pending_since` and `redispatch_count` from the review dispatch state; each entry carries `stage` `{stage, entered_at, last_activity_at, quiet_for, stalled, waiting_on_hive, past_dwell, history[]}` from the stage-label store (`stalled`/`past_dwell` follow `governor.labels.stage.dwell` and `stalled.require_quiet`; `history[]` is `{from, to, at, reason, regressed}`, newest last, capped at 8) and the top-level `hive_held` counts PRs past their stage dwell while waiting on the hive (`waiting_on_hive` and `past_dwell` both true); paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:502` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/close` | Owner only | Close a superseded PR now (grace window or not): posts the close comment, adds `hive/superseded`, closes it | `pkg/dashboard/api.go:505` | +| `POST` | `/api/review/queue/{owner}/{repo}/{number}/superseded/keep-open` | Owner only | Keep a superseded PR open: adds `hive/keep-open`, which the supersession sweep never auto-closes | `pkg/dashboard/api.go:506` | +| `GET` | `/api/review/pipeline` | Dashboard auth/session | Review pipeline: one card per review-queue PR placed in its stage (`unreviewed`, `reviewing`, `changes_requested`, `fixing`, `human_hold`, `approved`, `merged`, `abandoned`) with `since`, `reviewers`, P0–P3 `severity` counts, `loop_count`/`loop_cap`, `next_action` and `reasons`; filtered by `repo` and `stage`, paged with `limit` (1-200, default 50) and `offset` | `pkg/dashboard/api.go:510` | | `GET` | `/api/review/dispatch/events` | Dashboard auth/session | Webhook review dispatch queue: `enabled`, `webhooks_configured`, `debounce_s`, `pending` (soonest first) and `recent` (newest first) dispatches with repo, number, head SHA, action, timestamps and coalesced count, plus `stats` counters; in memory, never calls GitHub | `pkg/dashboard/api_review_event_dispatch.go:15` | -| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:512` | -| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:513` | -| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:515` | -| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:518` | -| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:519` | +| `GET` | `/api/review/evidence` | Merger or owner | [Review evidence bundle](../review-evidence.md) for one PR head. Query `repo` (`owner/name`), `number`, optional `head` (full SHA or unique prefix of at least 7 characters; `409` when ambiguous; default is the newest head), `format=json\|zip` (default `json`) and `download=1` for an attachment. `json` returns the bundle bytes exactly as sealed (verdicts, posted reviews, policy, CI check runs, sentinel findings, human actions, merge event, `hash`, optional `signature`); `zip` adds `verdicts.json`, `review-links.json` and a `manifest.json` of SHA-256s plus the signing public key when readable. `400` for a bad `repo`/`number`; `404` with `status: "expired"`/`expired: true` when retention removed a bundle Hive can prove existed, otherwise `status: "not_found"` | `pkg/dashboard/api.go:514` | +| `GET` | `/api/review/evidence/list` | Merger or owner | Every retained evidence bundle id and head for one PR (`repo`, `number`), oldest first, with the newest marked latest; `400` for a bad `repo`/`number` | `pkg/dashboard/api.go:515` | +| `GET` | `/api/evidence/write-counters` | Merger or owner | Durable attempted vs blocked agent GitHub write counters ([#12069](https://github.com/hivecommons/hive/issues/12069)): `totals` by intent tier (ACMM mode) with `blocked_by_reason`, and `weeks` keyed by the UTC Monday of each ISO week with per-tier and per-reason counts. Persisted across restarts; observation only, never gates a write or merge. Empty `totals`/`weeks` before anything is recorded | `pkg/dashboard/api.go:517` | +| `GET` | `/api/evidence/summary` | Dashboard auth/session | Read-only aggregate over `/data/evidence` bundles (schema v1) plus reviewer accuracy. Query `hours` (default 24, capped like `/api/pr-throughput`; `0` = all time) or a custom `from`/`to` range (RFC3339 or `YYYY-MM-DD`, date-only `to` inclusive, `to` defaults to now; `400` when `to` precedes `from`, the span exceeds 3 × 366 days, or `to` is given without `from`; the response echoes `from`/`to`), `repo` (`owner/name`) and `author_kind=human\|agent\|bot`; `400` for a bad value. A PR falls in the window by its open time (earliest bundle `created_at` or `merge.opened_at`), never by when a bundle was written; all bundles of a PR are folded so the newest supplies verdicts and the merge / `reverted_by` / backfilled close come from whichever record knows them. Returns `available_windows` (`{"24","168","720","all"}` → PR count under the same filters), `outcomes_by_author_kind` (merged/closed/open; `closed` comes from backfilled records, `reverted_14d` is null until bundles record it), `reviewer_calibration` buckets per perspective, `reviewer_accuracy_by_model` split by author kind (blocks split into `enforced_blocks` / `advisory_blocks` by `policy.require_approval`; advisory blocks that preceded a merge are `dissent_before_merge`, not false blocks), `sentinel_hits_per_week`, `shadow_gate` (`n`, `would_have_held`, `would_have_blocked`, and per gate `review_gate` / `intent` the evaluated `n` with `held` / `passed` outcomes `{n, merged, closed, open, reverted}`, plus `review_gate_by_lane` `{merge_eligible, self_merge}`), `write_counters` (per intent tier `{attempted, blocked, blocked_by_reason}` from the proxy write counter file; omitted when absent or unreadable), `write_activity` (blocked ÷ every agent write in the window: `total_writes`, `blocked`, `direct` `{recorded, since, partial_coverage, attempted, blocked, by_tier, blocked_by_reason}` from the proxy's weekly counter buckets under `/data/hive-metrics/write-counters.json`, `mediated` `{n, refused, by_action}` from the audit log), `claim_vs_verdict` (per ISO week of agent-authored PRs: `n`, `claimed`, `ci_captured`, `ci_not_green`, `verdict_not_approve`, `both`; records with empty CI are excluded from the CI column and disclosed under `missing.records_empty_ci`), `ci_recovery` (`policy` `{self_authored_automerge, required_checks}`, `n`, `at_claim` `{green, red, pending, none}`, `red` `{n, recovered_merged, green_open, abandoned, pending, outcome_unknown, enriched, not_enriched, median_pushes_to_green, median_hours_to_green, same_head_recovered}`, `gate` `{merged_n, with_checks, green, green_from_bundles, non_required_red, required_unknown, breaches, breach_prs[], suspected, suspected_prs[], pending, unknown, green_to_merge_n, median_green_to_merge_hours}` over every merged PR by GitHub-confirmed state of the *required* checks on the merged head, as the merge gate judges (`breach_prs[]` carry `red`, `merged_by`; a red non-required check is disclosed, not a breach; a red review-time snapshot, a required check with no run, or a red read without a resolvable required set is only suspected), and `convergence` `{n, passes {"1","2","3","4+","never"}, settled, in_flight, unknown, median_passes, from_github, from_bundles, by_week[]}` over agent PRs by CI passes to first green, from the durable `/data/hive-metrics/ci-recovery.json` GitHub check-run trail rollup), `work_balance` (per ISO week: `n`, `opened` by actor kind `{human, agent, bot}`, `closed`, `prs_opened`, `prs_merged`, `prs_closed`, `queue_issues`, `queue_prs`, `issue_source` `github|audit`, `throttled`) with `work_balance_sources` (`issues_github_since`, `issues_fetched_at`, `issues_known`, `audit_only_weeks`, `issue_series_weeks`, `queue_samples`, `queue_retention_days`; issues from the durable GitHub rollup `/data/hive-metrics/issue-activity.json` for weeks at or after `issues_github_since` and, for earlier weeks, from the backfilled issue series `///issues/.json` written by the issue backfill ([#12527](https://github.com/hivecommons/hive/pull/12527)) when its coverage spans the requested portion of the week (`issue_series_weeks` counts the repo-weeks it supplied), else the audit log (`audit_only_weeks`), PRs from folded bundles, queue depth from governor snapshots; `missing.issues_human_opens_unobserved` is true while no GitHub rollup exists unless the issue series covers every row, and whenever any row fell back to the audit log, `missing.throttle_windows_unavailable` discloses that no governor throttle windows are reported), `intent_counters` (per intent tier `{attempted, blocked}` from `/data/hive-metrics/intent-counters.json` — evaluations and the subset the intent gate would have blocked with enforcement on, [#12362](https://github.com/hivecommons/hive/issues/12362); omitted when absent or unreadable), `complexity_by_repo` (per managed repo the newest 12 monthly complexity snapshots, oldest first, each `{month, ref, captured_at, files, functions, mean_cyclomatic, median_cyclomatic, p90_cyclomatic, max_cyclomatic, functions_over_threshold, threshold, static_warnings, static_warnings_by_tool}`; omitted when no repo has a snapshot), the `/api/reviewer/accuracy` summary, and `n` plus `missing` counts (unknown-model verdicts, empty CI, unreadable records). Never consulted by merge decisions. | `pkg/dashboard/api.go:520` | +| `GET` | `/api/benchmarks/export` | Owner only | Anonymized per-PR [benchmark records](../benchmarks.md) (schema `hivecommons/benchmarks` `result.schema.json`) built from the evidence bundles updated since `since` (RFC3339 or `YYYY-MM-DD`; default 90 days; `400` when malformed) plus `hive_hash`, `publish`, `generated_at` and `count`. `records` is empty when `benchmarks.publish: false`; repo/org names appear only for GitHub-public repos when `benchmarks.repo_consent` is on | `pkg/dashboard/api.go:521` | | `GET` | `/api/agents` | Dashboard auth/session | Agents List | `pkg/dashboard/api.go:305` | | `POST` | `/api/agents` | Owner only | Agent Create | `pkg/dashboard/api.go:306` | | `POST` | `/api/agents/import` | Owner only | Agent Import | `pkg/dashboard/api.go:307` | diff --git a/src/docs/api-reference/auth.md b/src/docs/api-reference/auth.md index 18498e9ac8..2d9846b631 100644 --- a/src/docs/api-reference/auth.md +++ b/src/docs/api-reference/auth.md @@ -24,10 +24,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/openrouter/models` | Dashboard auth/session | Open Router Models | `pkg/dashboard/openrouter.go:47` | | `GET` | `/api/openrouter/credit` | Dashboard auth/session | Open Router Credit | `pkg/dashboard/openrouter.go:48` | | `GET` | `/openrouter/callback` | Public | Open Router Callback | `pkg/dashboard/openrouter.go:49` | -| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1782` | -| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1783` | -| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1784` | -| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:552` | -| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:553` | -| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:554` | -| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:555` | +| `POST` | `/api/github-app/recheck` | Dashboard auth/session | GitHub App Recheck | `pkg/dashboard/server.go:1778` | +| `POST` | `/api/github-app/install-clicked` | Dashboard auth/session | GitHub App Install Clicked | `pkg/dashboard/server.go:1779` | +| `GET` | `/gh-setup` | Public | GitHub App Setup Callback | `pkg/dashboard/server.go:1780` | +| `GET` | `/api/github-owner-identity` | Owner only | The hive owner's GitHub identity for remote repos ([#18197](https://github.com/hivecommons/hive/issues/18197)): `connected`, `login`, `scope`, `connected_at`, `usable`, `reason`, `verified_at`, `scope_required` (`public_repo`), `private_repos_supported` (false) and `file` (the token file path on the spoke). Never the token | `pkg/dashboard/api.go:554` | +| `POST` | `/api/github-owner-identity/start` | Owner only | Start the consent: a GitHub device flow with the spoke's `oauth_client_id` asking for `public_repo`, separate from the scope-free login flow. Returns `user_code`, `verification_uri`, `expires_in`, `interval`, `scope` and the `flow_id` the poll must present. 502 when GitHub refused the device-code request | `pkg/dashboard/api.go:555` | +| `POST` | `/api/github-owner-identity/poll` | Owner only | Poll the consent with `{"flow_id"}`: `status` `pending` / `slow_down` (poll again), `complete` (with `login` and the identity) or `error`. On completion the granted scope must cover `public_repo`, the token must validate and the account must be the logged-in owner's; the identity is then stored on the spoke (`/data/secrets/github-owner-token`, `HIVE_GITHUB_OWNER_TOKEN_FILE` overrides) and the reference-repo policies re-resolve. 400 without a live flow or with the wrong `flow_id`; audited as `github_owner_identity_connected` / `_rejected` | `pkg/dashboard/api.go:556` | +| `DELETE` | `/api/github-owner-identity` | Owner only | Disconnect: removes the token file, drops every write-tier reference repo to read-only on the next pass, returns the previous `login` and a `note` that GitHub-side revocation is done under Settings → Applications on github.com; audited as `github_owner_identity_disconnected` | `pkg/dashboard/api.go:557` | diff --git a/src/docs/api-reference/beads.md b/src/docs/api-reference/beads.md index b2f87ad343..b47bb6ce42 100644 --- a/src/docs/api-reference/beads.md +++ b/src/docs/api-reference/beads.md @@ -5,8 +5,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:484` | -| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:485` | -| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:486` | -| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:487` | -| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:488` | +| `GET` | `/api/beads` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:486` | +| `GET` | `/api/beads/{agent}` | Dashboard auth/session | Beads List | `pkg/dashboard/api.go:487` | +| `POST` | `/api/beads/{agent}` | Owner only | Beads Create | `pkg/dashboard/api.go:488` | +| `POST` | `/api/beads/reset` | Owner only | Beads Reset | `pkg/dashboard/api.go:489` | +| `POST` | `/api/beads/reset/{agent}` | Owner only | Beads Reset Agent | `pkg/dashboard/api.go:490` | diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index 2d79a5ecca..051773a54c 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -90,7 +90,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/compliance/export` | Owner only | Evidence download for `?since=`/`?until=`: `kind=controls` (`json`/`md`), `posture` (`json`/`csv`), `audit` (`json`), `config` (redacted effective config + sha256, `json`), `attestations` (`json`/`csv`) or `bundle` (`json`). Every format includes source, period, generator, selected profile versions, attesters, retention and a per-section SHA-256 manifest; audited as `compliance_export` with the SHA-256 of the delivered bytes ([#11081](https://github.com/hivecommons/hive/issues/11081), [#13582](https://github.com/hivecommons/hive/issues/13582)) | `pkg/dashboard/api.go:354` | | `GET` | `/api/compliance/attestations` | Owner only | Owner attestations, newest first (`?framework=` filters) ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:355` | | `POST` | `/api/compliance/attestations` | Owner only | Record `{"framework", "reviewed_on", "note"}` for the signed-in owner; audited as `compliance_attestation`; `201` with the attestation, `400` for an unknown framework, a bad or future date, or a note over 2000 characters ([#11081](https://github.com/hivecommons/hive/issues/11081)) | `pkg/dashboard/api.go:356` | -| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:526` | +| `PUT` | `/api/config/governor/compliance` | Owner only | Settings → Compliance framework picker: `{"frameworks": [...]}` sets `compliance.frameworks` (empty list deselects all, absent key leaves it unchanged; unknown/duplicate ids are a `400` before any change); audited as `config_compliance`; returns the re-evaluated `compliance.Report` ([#11080](https://github.com/hivecommons/hive/issues/11080)) | `pkg/dashboard/api.go:528` | | `GET` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Get | `pkg/dashboard/api.go:201` | | `PUT` | `/api/config/governor/threshold-scaling` | Owner only | Governor Threshold Scaling Set | `pkg/dashboard/api.go:202` | @@ -99,10 +99,10 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/governor/watchdog` | Owner only | Governor Watchdog | `pkg/dashboard/api.go:211` | | `GET` | `/api/config/escalation` | Owner only | Escalation Config Get | `pkg/dashboard/api.go:214` | | `PUT` | `/api/config/escalation` | Owner only | Escalation Config Set | `pkg/dashboard/api.go:215` | -| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:522` | -| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:523` | -| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:548` | -| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:549` | +| `GET` | `/api/config/write-surface` | Owner only | Lane write allowlist (`write_surface.allowlist`, [#9587](https://github.com/hivecommons/hive/issues/9587)): `allowlist`, `ops`, `warnings` | `pkg/dashboard/api.go:524` | +| `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:525` | +| `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:550` | +| `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:551` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | diff --git a/src/docs/api-reference/dashboard-misc.md b/src/docs/api-reference/dashboard-misc.md index fe8f994873..27cda0f936 100644 --- a/src/docs/api-reference/dashboard-misc.md +++ b/src/docs/api-reference/dashboard-misc.md @@ -25,7 +25,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/audit` | Read-write role | Audit Log — `{"entries": [...]}` envelope, newest first, capped at 200; response shape and the serve-time `user_name` field in [audit-log.md](../audit-log.md#get-apiaudit) | `pkg/dashboard/api.go:63` | -| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:495` | +| `GET` | `/api/watchdog/activity` | Read-write role | Watchdog activity readout for the Health tab (#7254): `watchdog-*` audit actions over `?days=` (default 30, clamped to 90) — total / taken / observed / `byAction`, a zero-filled per-day `daily` histogram, per-agent `agents` liveness, and the Observe → Heal `promotion` hint; see [agent-watchdog.md](../agent-watchdog.md#watchdog-activity-strip) | `pkg/dashboard/api.go:497` | | `POST` | `/api/presence` | Dashboard auth/session | Presence | `pkg/dashboard/api.go:66` | | `POST` | `/api/upgrade/announce` | Owner role | Announce a pod roll before it happens ([#15788](https://github.com/hivecommons/hive/issues/15788)): body `{"target": "", "source": "hub"|"operator", "reason": "..."}` (`version` is an alias of `target`; all fields optional). Marks `/api/status`/`/api/version` `upgradeProgress` as `state: pulling, phase: announced` with the target and publishes an SSE `upgrading` event so every open dashboard shows the upgrade animation; a SIGTERM afterwards (or with no announce at all) publishes `phase: restarting` from the same record. The hub sends the same announce through the heartbeat response (`upgrade_announce`) for hub-managed hives; an announce with no kill expires after 15 minutes. Returns `{ok, upgradeProgress}` | `pkg/dashboard/api.go:69` | | `GET` | `/api/prompt-history` | Dashboard auth/session | Prompt History | `pkg/dashboard/api.go:67` | @@ -40,18 +40,18 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `GET` | `/api/convergence/soak` | Owner only | Convergence Soak Status | `pkg/dashboard/api.go:245` | -| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:447` | -| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:450` | -| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:451` | -| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:453` | -| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:454` | +| `POST` | `/api/plan/from-issue` | Dashboard auth/session | Plan From Issue | `pkg/dashboard/api.go:449` | +| `GET` | `/api/plan/{epicID}` | Dashboard auth/session | Plan Tree | `pkg/dashboard/api.go:452` | +| `POST` | `/api/plan/{epicID}/approve` | Owner only | Plan Approve | `pkg/dashboard/api.go:453` | +| `POST` | `/api/plan/{epicID}/reject` | Owner only | Plan Reject | `pkg/dashboard/api.go:455` | +| `POST` | `/api/plan/{epicID}/child/{childID}` | Owner only | Plan Child Action | `pkg/dashboard/api.go:456` | | `POST` | `/api/linear/agent/install` | Owner only | Linear Agent Install (OAuth start) | `pkg/dashboard/api_linear_agent.go:215` | | `GET` | `/api/linear/agent/status` | Owner only | Linear Agent Status | `pkg/dashboard/api_linear_agent.go:216` | | `POST` | `/api/linear/agent/disconnect` | Owner only | Linear Agent Disconnect | `pkg/dashboard/api_linear_agent.go:217` | | `GET` | `/api/upstream-watch` | Owner only | Upstream-watch divergence: per watched fork the upstream followed, the watermark and last-run time, surfaced/ported/dismissed/skipped counts, and the recent upstream refs with their upstream URL, diff URL, fork issue number and state. Read-only — it reads the config and the watch state file, never GitHub. Also carries `interval`, `project_repos` and each repo's configured entry (`config`) for the editor. | `pkg/dashboard/api.go:288` | | `PUT` | `/api/config/upstream-watch` | Owner only | Upstream Watch Config Update: edit `upstream_watch` from the Features tab. Body `{enabled?, interval?, repos?: {: {upstream?, sources?, pr_labels?, max_issues_per_run?, label?} \| null}}` — absent keys are unchanged, `null` removes a repo, keys are stored as the bare repo name. Validated with the loader's rules before the config changes (400 on failure), then persisted and audited as `config_upstream_watch`. | `pkg/dashboard/api.go:289` | -| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:533` | +| `GET` | `/api/hotspots` | Dashboard auth/session | Merge-hotspot advisor report (`?repo=owner/name` optional): files repeatedly touched by concurrent PRs over the last `governor.hotspot_window_days`, each with `prs` (distinct PRs), `pr_numbers`, `overlaps` (PR pairs open at the same time), `conflicts` (rebase conflicts blamed on the file), `lines`, `kind` (`code`/`doc`/`lock`/`generated`/`data`), `score`, `symbol_groups`, `recommendation` (`split-code`/`split-doc`/`split-source`/`report-only`/`none`), `reason`, `generated_from`, `source_files` (files under `generated_from`, when known), `issue_number`/`issue_url` of the modularize issue filed, `last_updated`; top-level `count`/`actionable`/`filed`. Derived from the merge train's own PR file lists and the rebase follow-through's conflict records — never lists PRs or files from GitHub. See [operator-reference.md § Merge-hotspot advisor](../operator-reference.md#merge-hotspot-advisor-governorhotspot_). | `pkg/dashboard/api.go:535` | | `GET` | `/api/widget` | Dashboard auth/session | Widget | `pkg/dashboard/api.go:99` | | `GET` | `/api/pane/{agent}` | Dashboard auth/session | Pane | `pkg/dashboard/api.go:104` | | `GET` | `/api/role` | Dashboard auth/session | Role | `pkg/dashboard/api.go:118` | @@ -65,8 +65,8 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `GET` | `/api/inference/models/{backend}` | Dashboard auth/session | Inference Models | `pkg/dashboard/api.go:363` | | `GET` | `/api/hive-id` | Dashboard auth/session | Hive IDGet | `pkg/dashboard/api.go:426` | | `PUT` | `/api/hive-id` | Owner only | Hive IDSet | `pkg/dashboard/api.go:427` | -| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:456` | -| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:490` | +| `POST` | `/api/chat` | Dashboard auth/session | Chat | `pkg/dashboard/api.go:458` | +| `GET` | `/api/auth/token` | Public | Auth Token | `pkg/dashboard/api.go:492` | | `GET` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:350` | | `POST` | `/api/v1/` | GitHub token | Contributor v1 API dispatcher | `pkg/dashboard/api_contribute.go:351` | | `GET` | `/api/docs` | Dashboard auth/session | APIDocs | `pkg/dashboard/api_contribute.go:352` | @@ -84,7 +84,7 @@ The monitor renders CI and Review concurrently on one shared PR row; see | `POST` | `/api/hives/{id}/heartbeat` | Dashboard auth/session | Hives Heartbeat | `pkg/dashboard/api_contribute.go:377` | | `DELETE` | `/api/hives/{id}` | Owner only | Hives Delete | `pkg/dashboard/api_contribute.go:378` | | `POST` | `/api/hives/onboard` | Dashboard auth/session | Hives Onboard | `pkg/dashboard/api_contribute.go:379` | -| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1789` | +| `GET` | `/sso` | Public | SSO | `pkg/dashboard/server.go:1785` | ### Activity observation provenance The CI snapshot retains real check/node IDs, head, App ID and transition times. diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index c15ccd85bf..bafbac20c7 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -24,17 +24,17 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/version` | Dashboard auth/session | Build/version metadata; includes `upgradeMarker` (`target`, `current`, `attempts`, `maxAttempts`, `failed`, `requestedAt`, `lastError`) while a self-upgrade is in flight or has failed ([#6765](https://github.com/hivecommons/hive/issues/6765)), the hub-delivered `upgradePolicy` (`hub_managed`, `spoke_managed`, `schedule`, `schedule_hour`, `schedule_timezone`, `schedule_weekday`, `paused`, `branch`, `channel`, `target_sha`, `target_resolved`, `armed_target`, and `next_update_at` — the hub's RFC3339 ETA for the next promotion into the `stable` channel, omitted when unknown ([#10256](https://github.com/hivecommons/hive/issues/10256))) when available, and an `autoUpdate` object (`enabled`, `state` — one of `disabled`/`up_to_date`/`behind`/`retrying`/`failed`/`unknown` — `healthy`, `period`, `targetBranch`, `targetCommit`, `currentCommit`, `commitsBehind`, `lastAttemptAt`, `lastError`, `detail`, and `nextUpdateAt` — the hub's RFC3339 ETA for the next update, omitted when unknown, disabled or paused ([#10257](https://github.com/hivecommons/hive/issues/10257))) that never reports a failed or unknown update as healthy ([#6962](https://github.com/hivecommons/hive/issues/6962), [#6963](https://github.com/hivecommons/hive/issues/6963)). Also `startedAt` (RFC3339 process start — changes on every pod roll even when the build does not, so the dashboard can say "Restarted" vs "Upgraded") and, until the first status is published, `startupPhase`/`startupPhaseLabel` (the boot phase a fresh pod is in) ([#15788](https://github.com/hivecommons/hive/issues/15788)) | `pkg/dashboard/api.go:45` | | `GET` | `/api/version/release-notes` | Dashboard auth/session | Changelog gap between two revisions: `?from=&to=` returns `{from:{sha,version?}, to:{sha,ref,version?}, sections:[{version,date,categories:{added,changed,fixed,security,deprecated}}], unreleased?, truncated, source, error?}` — the `CHANGELOG.md` release sections present at `to` and absent at `from`, newest first, plus (when `to` is not a release tag) the `changelog.d/` fragments new at `to` under an `Unreleased (in this build)` section. Fetch failures return `source: "unavailable"` with `error` rather than an error status; results are cached per (from, to) for an hour ([#11065](https://github.com/hivecommons/hive/issues/11065)) | `pkg/dashboard/api.go:46` | | `POST` | `/api/release-channel` | Owner only | Hosted spoke self-service release-channel selector; relays `stable`/`candidate`/`edge` to the hub's existing switch-branch endpoint with the spoke dashboard-token proof, and reports the requested channel as pending until the Deployment image lands | `pkg/dashboard/api.go:70` | -| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1762` | -| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1763` | -| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1764` | -| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1770` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1775` | -| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1776` | -| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1777` | -| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1778` | -| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1779` | -| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1780` | -| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1781` | +| `GET` | `/api/health` | Public | Basic health probe | `pkg/dashboard/server.go:1758` | +| `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1759` | +| `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1760` | +| `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1766` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `workflow_approvals` `{approved, denied, permission_errors, last}` counts the hive's approvals of GitHub-gated workflow runs since boot (#16603) — runs approved, runs refused by the trust policy (once per head), `403`/`404` refusals for want of `actions: write`, and the most recent decision `{repo, number, head, run_id, outcome, at}`; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`); `referenceRepos[]` `{full, tier, reference_tier}` lists `project.reference_repos` apart from `repos[]` — `reference_tier` is `read-only`, `issues`, `prs` or `issues+prs` (`tier` is the same value, kept for older clients) and an entry carries no ACMM, work-item or pause fields, since a reference repo is studied, not worked (#18021); `config.gate_regressions[]` `{gate, previous, effective, source}` is the boot-time safety-gate regression list (#16438) — gates a previous runtime overlay on the PVC carried that the running config lacks or loosens (`review.require_labels`, `project.issue_filter.require_labels`, `project.paused_repos[]`, `writeback.per_repo[].mode`), empty on a healthy boot | `pkg/dashboard/server.go:1771` | +| `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1772` | +| `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1773` | +| `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1774` | +| `GET` | `/api/overview/prs.csv` | Dashboard auth/session | Cached Overview PR-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1775` | +| `GET` | `/api/overview/prs.json` | Dashboard auth/session | Cached Overview PR-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1776` | +| `GET` | `/api/events` | Dashboard auth/session | Server-sent event stream | `pkg/dashboard/server.go:1777` | | `GET` | `/api/swarm` | Dashboard auth/session | Current swarm status: display name, duration, active repo, expiry, persisted prep metrics when available, and idle-unlock fields. | `pkg/dashboard/swarm.go:310` | | `POST` | `/api/swarm` | Owner only | Start a 24h repo swarm for a configured repo, returning 409 when another swarm is active and 423 when a previous swarm keeps the next swarm locked until enough agents are idle unless body `{"repo":"owner/name","force":true}` is used; saves the active record before repo prep, persists prep metrics, and announces the start to Discord when configured. | `pkg/dashboard/swarm.go:311` | | `DELETE` | `/api/swarm` | Owner only | End the active swarm, score issues closed and PRs merged in the window, append it to history, and announce the result to Discord when configured. | `pkg/dashboard/swarm.go:312` | diff --git a/src/docs/api-reference/inception.md b/src/docs/api-reference/inception.md index 92198c6b14..10649937e9 100644 --- a/src/docs/api-reference/inception.md +++ b/src/docs/api-reference/inception.md @@ -2,20 +2,22 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page for how auth levels and `pkg/:` source citations are read and checked. Edit this file for routes in this area and run `src/scripts/check-api-reference-citations.sh --fix` to resync citations. +The inception API was retired in favour of [Inception (spek) sessions](sessions.md). For one release every route below answers `410 Gone` with a JSON body (`error`, `replacement: "/api/sessions"`, `docs`); nothing is read or changed. See [Inception](../inception.md). + | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `POST` | `/api/inception/start` | Owner only | Inception Start | `pkg/dashboard/api.go:429` | -| `POST` | `/api/inception/scan` | Owner only | Inception Scan | `pkg/dashboard/api.go:430` | -| `GET` | `/api/inception/state` | Dashboard auth/session | Inception State | `pkg/dashboard/api.go:431` | -| `POST` | `/api/inception/questions` | Owner only | Inception Set Questions | `pkg/dashboard/api.go:432` | -| `POST` | `/api/inception/answer` | Owner only | Inception Answer | `pkg/dashboard/api.go:433` | -| `POST` | `/api/inception/facts` | Owner only | Inception Record Facts | `pkg/dashboard/api.go:434` | -| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Inception Scaffold | `pkg/dashboard/api.go:435` | -| `POST` | `/api/inception/approve` | Owner only | Inception Approve | `pkg/dashboard/api.go:436` | -| `POST` | `/api/inception/reset` | Owner only | Inception Reset | `pkg/dashboard/api.go:437` | -| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Inception Ideation Facts | `pkg/dashboard/api.go:438` | -| `GET` | `/api/inception/download` | Dashboard auth/session | Inception Download | `pkg/dashboard/api.go:439` | -| `GET` | `/api/inception/has-files` | Dashboard auth/session | Inception Has Files | `pkg/dashboard/api.go:440` | -| `PUT` | `/api/inception/wiki-name` | Owner only | Inception Rename Wiki | `pkg/dashboard/api.go:441` | -| `POST` | `/api/inception/import` | Owner only | Inception Import | `pkg/dashboard/api.go:442` | +| `POST` | `/api/inception/start` | Dashboard auth/session | Retired (was: Inception Start): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:431` | +| `POST` | `/api/inception/scan` | Dashboard auth/session | Retired (was: Inception Scan): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:432` | +| `GET` | `/api/inception/state` | Dashboard auth/session | Retired (was: Inception State): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:433` | +| `POST` | `/api/inception/questions` | Dashboard auth/session | Retired (was: Inception Set Questions): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:434` | +| `POST` | `/api/inception/answer` | Dashboard auth/session | Retired (was: Inception Answer): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:435` | +| `POST` | `/api/inception/facts` | Dashboard auth/session | Retired (was: Inception Record Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:436` | +| `GET` | `/api/inception/scaffold` | Dashboard auth/session | Retired (was: Inception Scaffold): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:437` | +| `POST` | `/api/inception/approve` | Dashboard auth/session | Retired (was: Inception Approve): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:438` | +| `POST` | `/api/inception/reset` | Dashboard auth/session | Retired (was: Inception Reset): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:439` | +| `GET` | `/api/inception/ideation-facts` | Dashboard auth/session | Retired (was: Inception Ideation Facts): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:440` | +| `GET` | `/api/inception/download` | Dashboard auth/session | Retired (was: Inception Download): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:441` | +| `GET` | `/api/inception/has-files` | Dashboard auth/session | Retired (was: Inception Has Files): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:442` | +| `PUT` | `/api/inception/wiki-name` | Dashboard auth/session | Retired (was: Inception Rename Wiki): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:443` | +| `POST` | `/api/inception/import` | Dashboard auth/session | Retired (was: Inception Import): answers `410 Gone` pointing to `/api/sessions` | `pkg/dashboard/api.go:444` | diff --git a/src/docs/api-reference/nous.md b/src/docs/api-reference/nous.md index aa50f2970f..fa3d46b69b 100644 --- a/src/docs/api-reference/nous.md +++ b/src/docs/api-reference/nous.md @@ -5,28 +5,28 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| -| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:458` | -| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:459` | -| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:460` | -| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:461` | -| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:462` | -| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:463` | -| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:464` | -| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:465` | -| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:466` | -| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:467` | -| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:468` | -| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:469` | -| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:470` | -| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:471` | -| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:472` | -| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:473` | -| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:474` | -| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:475` | -| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:476` | -| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:477` | -| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:478` | -| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:479` | -| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:480` | -| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:481` | -| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:482` | +| `GET` | `/api/nous/status` | Dashboard auth/session | Nous Status — includes `experimentLoop` (`dir`, `lastWriteAt`, `running`, `idleAfterSeconds`): whether the external experiment loop, the only producer of proposals, has written under `/var/run/nous/governor` within 24 evaluation cycles; ready cards then carry `experimentLoopIdle` ([#12541](https://github.com/hivecommons/hive/issues/12541)) | `pkg/dashboard/api.go:460` | +| `GET` | `/api/nous/ledger` | Dashboard auth/session | Nous Ledger | `pkg/dashboard/api.go:461` | +| `GET` | `/api/nous/principles` | Dashboard auth/session | Nous Principles | `pkg/dashboard/api.go:462` | +| `POST` | `/api/nous/approve` | Owner only | Nous Approve | `pkg/dashboard/api.go:463` | +| `POST` | `/api/nous/abort` | Owner only | Nous Abort | `pkg/dashboard/api.go:464` | +| `PUT` | `/api/nous/mode` | Owner only | Nous Mode | `pkg/dashboard/api.go:465` | +| `PUT` | `/api/nous/scope` | Owner only | Nous Scope | `pkg/dashboard/api.go:466` | +| `GET` | `/api/nous/phase` | Dashboard auth/session | Nous Phase | `pkg/dashboard/api.go:467` | +| `PUT` | `/api/nous/gate-decision` | Owner only | Nous Gate Decision | `pkg/dashboard/api.go:468` | +| `GET` | `/api/nous/gate-pending` | Dashboard auth/session | Nous Gate Pending | `pkg/dashboard/api.go:469` | +| `POST` | `/api/nous/gate-respond` | Owner only | Nous Gate Respond | `pkg/dashboard/api.go:470` | +| `GET` | `/api/nous/gate-response` | Dashboard auth/session | Nous Gate Response | `pkg/dashboard/api.go:471` | +| `GET` | `/api/nous/config` | Dashboard auth/session | Nous Config Get | `pkg/dashboard/api.go:472` | +| `PUT` | `/api/nous/config/goals` | Owner only | Nous Config Goals — legacy; the dashboard no longer exposes the research question in the ⚙ dialog, use `PATCH /api/nous/campaigns/{id}` | `pkg/dashboard/api.go:473` | +| `PUT` | `/api/nous/config/repos` | Owner only | Nous Config Repos — the allow-list of repos experiments may target (empty = any) | `pkg/dashboard/api.go:474` | +| `PUT` | `/api/nous/config/output` | Owner only | Nous Config Output | `pkg/dashboard/api.go:475` | +| `PUT` | `/api/nous/config/fast-fail` | Owner only | Nous Config Fast Fail | `pkg/dashboard/api.go:476` | +| `PUT` | `/api/nous/config/schedule` | Owner only | Nous Config Schedule | `pkg/dashboard/api.go:477` | +| `PUT` | `/api/nous/config/controllables` | Owner only | Nous Config Controllables | `pkg/dashboard/api.go:478` | +| `PUT` | `/api/nous/config/principles` | Owner only | Nous Config Principles | `pkg/dashboard/api.go:479` | +| `DELETE` | `/api/nous/principles/{id}` | Owner only | Nous Delete Principle | `pkg/dashboard/api.go:480` | +| `POST` | `/api/nous/campaign/start` | Owner only | Nous Campaign Start — archives the active campaign and starts a new experiment whose baseline restarts at 0 ([#12501](https://github.com/hivecommons/hive/issues/12501)) | `pkg/dashboard/api.go:481` | +| `GET` | `/api/nous/campaigns` | Any | Nous Campaigns List — every experiment with its per-campaign baseline, scope, results and stage ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:482` | +| `POST` | `/api/nous/campaigns` | Owner only | Nous Campaigns Create — starts an experiment alongside the running ones; 409 `scope_conflict` when a running experiment shares a repo target or both are hive-wide ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:483` | +| `PATCH` | `/api/nous/campaigns/{id}` | Owner only | Nous Campaign Patch — pause / resume / archive, or edit question, hypothesis and scope. Hypothesis/tag edits save in place (`status: "updated"`); a changed question or repo set needs `restart: true` (else 409 `restart_required`) and archives the campaign as version N while creating version N+1 with `restartedFrom` (`status: "restarted", campaign, archived`); resume, scope widening and restarts re-run the conflict guard ([#12532](https://github.com/hivecommons/hive/issues/12532)) | `pkg/dashboard/api.go:484` | diff --git a/src/docs/api-reference/packs-and-acmm.md b/src/docs/api-reference/packs-and-acmm.md index 71379fe6e6..8e820e4363 100644 --- a/src/docs/api-reference/packs-and-acmm.md +++ b/src/docs/api-reference/packs-and-acmm.md @@ -25,7 +25,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/repos/{owner}/{repo}/items/{number}/decide-delegated/plan` | Same as `…/decide-delegated` | Preview for *Let hive decide*: runs the same owner-delegate policy with **no side effects** (nothing written, no job) and answers `{would, rule, acting, title, summary, why, consequences[], ladder, mergeable_as_is, alternatives[], writes: false, prior, notes}` — `summary` is one verb-first sentence with no "Hive would:" prefix (*Send #15332 back to its author with one instruction: make CI green, nothing else.*), `why` one short line (*CI is red.*), `consequences` at most two items, `ladder` the rung that decided with its `ruled_out` list, and `mergeable_as_is` whether an as-is merge is honest (the queue-merge and merge-now alternatives are dropped when it is not). The dialog shows **Cancel** / **Let hive do that**, plus **Approve and let hive merge** (or **Merge now as maintainer** when the hive would approve anyway) only when `mergeable_as_is`; only then does the SPA post `…/decide-delegated` with `chosen` naming the button. A transient GitHub failure (5xx, rate limit, timeout) is retried twice with backoff before the plan gives up. A failure answers `{ok: false, error, reason, retryable, attempts, elapsed_ms, hive, hint}` under **409** when the item is no longer open (`reason: not-open`) or **424** when a read it depends on failed (`github`), is not configured (`config`) or the plan itself failed (`plan`) — never 502/503, which the hosted Ingress intercepts and replaces with its generic *hive unavailable* page (hivecommons/hive#16776). See [dashboard-sections.md](../dashboard-sections.md#let-hive-decide). | `pkg/dashboard/api.go:341`, `pkg/dashboard/api_repo_item_decide_delegated_plan.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/recheck` | Same as `…/hold` (owner or repo write), signed-in GitHub user | *Re-check permissions* on an issue parked on a capability blocker (#15099): probes the GitHub App installation's permissions; when the missing permission is granted, clears every ledger entry blocked on it and un-parks the item (`{result: {outcome: "released", …}}`), otherwise `{result: {outcome: "no-effect", reason: "blocker", options: [...]}}`; 404 when the item has no blocker, 409 when the blocker is not a capability gap | `pkg/dashboard/api.go:342` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/blocker/close-partial` | Same as `…/hold` (owner or repo write), signed-in GitHub user | Option (c) on a capability blocker (#15099): labels the issue `hive/partially-addressed`, posts the operator's `{"comment"}` naming what remains and closes it; the ledger entry is cleared | `pkg/dashboard/api.go:343` | -| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:546`, `pkg/dashboard/api_repo_item_accept_triage.go` | +| `POST` | `/api/repos/{owner}/{repo}/items/{number}/accept-triage` | Owner or repo write/maintain/admin | Accept triage on an issue from the activity monitor's row menu — what a maintainer accepting triage on GitHub does by hand: adds the reporter-trust triage label (`triage/accepted`, or the first of `issue_filter.reporter_trust.untrusted_require_labels`; the label is created in the repo if missing) and removes the awaiting label (`needs-triage` / `reporter_trust.awaiting_label`) and a Hive-written `stage/015-triage-needed`. Empty body. Returns `{ok, repo, number, acceptLabel, added, removed, alreadyAccepted, minStatusSeq}`; an issue already carrying the accept label with nothing left to remove is a no-op (`alreadyAccepted: true`, no write, no audit). 404 for a pull request or an unknown item. The status snapshot's labels are patched so the next reconcile reads 010 Actionable before the engine's own 015 → 010 derivation. Every write is audited as `repo_item_accept_triage` under the dashboard user. | `pkg/dashboard/api.go:548`, `pkg/dashboard/api_repo_item_accept_triage.go` | | `POST` | `/api/repos/{owner}/{repo}/items/{number}/sentinel-confirm` | Owner or repo write/maintain/admin | **Confirm safe** on the activity monitor's human-gate pill ([#17470](https://github.com/hivecommons/hive/issues/17470)): a person confirms a sentinel finding is intended. Body `{comment?, type?}` (`type` is `pr` or `issue`, comment ≤ 4000 characters). Posts the confirmation as a comment first — ``, `@user confirmed the sentinel finding safe from the dashboard.`, then the comment text — and removes every label matching the configured sentinel label (`sentinel.label`, default `sentinel-alert`, case-insensitive). Returns `{ok, repo, number, label, removed, alreadyClear, result}`; with no sentinel label on the item the comment is still posted and `alreadyClear` is true. 403 for a repository the hive does not watch. Audited as `repo_item_sentinel_confirm` under the dashboard user; the operator-action ledger records it as `confirm-sentinel`. | `pkg/dashboard/api.go:333`, `pkg/dashboard/api_repo_item_sentinel_confirm.go` | | `GET` | `/api/acmm/evaluation` | Dashboard auth/session | ACMMEvaluation — combined codebase + operational result, cached server-side for 1 hour (`acmmEvalTTL`). `?refresh=1` (the dashboard's "🔄 Re-evaluate" button, #5877) bypasses the hourly TTL but is debounced server-side: requests within 1 minute of the last evaluation (`acmmRefreshDebounce`) still serve the cache, since a full refresh costs up to ~29 GitHub GetContents calls per repo. The response's `last_evaluated_at` timestamp reports when the cached evaluation was computed | `pkg/dashboard/api.go:345`, `pkg/dashboard/api_acmm_eval.go` | | `POST` | `/api/acmm/issue` | Owner only | ACMMCreate Issue — files on GitHub or, with `governor.acmm.issue_tracker: work_source` / body `tracker: "work_source"` on a Linear-sourced hive, on Linear; response `tracker` says which. See [ACMM policy matrix](../acmm-policy-matrix.md#where-acmm-gap-issues-are-filed) | `pkg/dashboard/api.go:346` | diff --git a/src/docs/api-reference/snapshots-and-style.md b/src/docs/api-reference/snapshots-and-style.md index 43abac7a2d..cd7b093869 100644 --- a/src/docs/api-reference/snapshots-and-style.md +++ b/src/docs/api-reference/snapshots-and-style.md @@ -6,7 +6,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | Method | Path | Auth | Purpose | Source | |---|---|---|---|---| | `GET` | `/api/style` | Public | Sanitized custom dashboard CSS | `pkg/dashboard/api.go:47` | -| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1852` | +| `GET` | `/branding/custom.css` | Dashboard auth/session | Operator branding stylesheet override, read per request (see [branding](../branding.md)) | `pkg/dashboard/server.go:1848` | | `GET` | `/api/snapshot/frame-ancestors` | Public | Snapshot framing allowlist | `pkg/dashboard/api.go:83` | | `GET` | `/api/snapshot` | Public | Snapshot data | `pkg/dashboard/api.go:84` | | `GET` | `/snapshot` | Public | Public read-only snapshot page | `pkg/dashboard/api.go:85` | diff --git a/src/docs/documentation-map.md b/src/docs/documentation-map.md index a00b938f27..e7971aeef8 100644 --- a/src/docs/documentation-map.md +++ b/src/docs/documentation-map.md @@ -112,10 +112,10 @@ Documentation for the current Hive line (branch `v5`; the code and docs live und - [CEL-based agent triggers](cel-triggers.md) — the `triggers:` config key: declarative CEL rules that kick an agent on a normalized source-control event, additive to built-in label/governor triggering, the `event.*` field reference, and the fail-closed compile/runtime contract. ### Long-running work and external execution -- [Long-running runs](runs.md) — how a run starts, including default-off triage admission and inception completion admitting an explicit GitHub issue into the first `spec` lease. +- [Long-running runs](runs.md) — how a run starts through default-off triage admission into the first `spec` lease. - [Spektacular (Spek) stage runner](spektacular.md) — **Operator; opt-in:** configure and monitor Hive's `spec` → `plan` → `implement` stages. Artifact design: [run artifacts](design/run-artifacts.md). - [ClankeR and Flue-style external execution](integrations/clanker-flue.md) — how the contributor relay and `pkg/extwork` let an external engine receive bounded work, report status, and return digest-verified receipts without repository credentials. -- [Spektacular and Project Inception](integrations/spektacular.md) — **Developer integration:** CLI status, final-plan import, and inception admission; not the operator stage-runner setup above. +- [Spektacular and Project Inception](integrations/spektacular.md) — **Developer integration:** CLI status and final-plan import; not the operator stage-runner setup above. - [vibe-kanban mirror and dispatch](vibe-kanban.md) — default-off side-car that mirrors one repository's admitted hive queue onto a local vibe-kanban board, records board pick-ups as shadow executions, and documents the opt-in `pkg/extwork/vibekanban` report-only workspace dispatch adapter. - [Audit campaign](audit-campaign.md) — **Owner-triggered; publication off by default:** run report-only inspections with credential guards, stage receipts, and explicit publication gates. - [Public snapshots](snapshots.md) — read-only `/snapshot`, custom CSS, and frame-ancestor sharing. @@ -196,7 +196,7 @@ Documentation for the current Hive line (branch `v5`; the code and docs live und - [ACMM policy matrix](acmm-policy-matrix.md) — capability levels and policy modes. - [ACMM level-up advisor](acmm-advisor.md) — the advisory-only `pkg/acmmadvisor` computation behind `GET /api/acmm-recommendation`: the signals it measures, per-level thresholds, and why it never changes the applied level. - [ACMM waivers](acmm-waivers.md) — record criteria satisfied outside the repo; a waiver can restore green status, never advance a level. -- [Inception](inception.md) — operator guide to the L1 brainstorm/inception workflow: phases, API, and template variables. +- [Inception](inception.md) — Inception (spek) sessions, what the retired inception API, watcher and brainstorm inception mode left behind, and the one-time retired-campaigns export. - [Planning intelligence](planning-intelligence.md) — how a large GitHub issue becomes an epic the architect lane decomposes into child beads, the human plan-review gate that withholds those children until approved, and stall-replan. - [Review swarm](review-swarm.md) — the five review perspectives, the verdict collector and its report contract, and the opt-in merge-gate integration and bounded auto-fix cycle for review findings. - [Swarm mode](swarm.md) — focusing the hive on one repository for a bounded window: Discord announcements, theming (`swarm:` config, `HIVE_SWARM_EVENT_NAME` / `HIVE_SWARM_CALL_TO_ARMS`), the `/api/leaderboard/swarm` endpoint and scoring. diff --git a/src/docs/inception.md b/src/docs/inception.md index 681465229f..4da0fd8657 100644 --- a/src/docs/inception.md +++ b/src/docs/inception.md @@ -1,4 +1,4 @@ -# Inception — Inception (spek) sessions and the inception API +# Inception — Inception (spek) sessions In the dashboard, **Inception (spek)** is the interactive way to turn an idea (or an existing repo) into specs, plans and a starting project: named, shared @@ -12,176 +12,54 @@ and the [Sessions API](api-reference/sessions.md). An Inbox recording can seed a session directly (**🔗 Share ▾ → Hive → spek…**, see [Inbox and voice sources](inbox-voice-sources.md#from-recording-to-an-inception-spek-session)). -The dashboard's old step-by-step Inception wizard was removed; Inception (spek) -replaces it. Campaigns, their Jam workspace and campaign recheck have been -retired too: start a session for new inception work, and find Spektacular runs -in [Runs](runs.md). See [Retired campaigns export](#retired-campaigns-export) -for where their data went. - -The rest of this guide covers the ACMM **L1 ("Inception")** workflow behind -`/api/inception/*`, which is unchanged and still available to API callers. It -drives the `brainstorm` agent through a fixed phase sequence that turns a raw -idea (or an existing repo) into structured knowledge-base facts and a -downloadable project scaffold. It documents only what the code in -`pkg/dashboard/inception_handlers.go` and `pkg/knowledge/inception.go` -actually does; see those files for implementation detail. - -## When to use it - -Use inception when you are standing up a brand-new hive at ACMM level 1 and -want a starting point beyond an empty repo: a `README.md`, `AGENTS.md`, -`CLAUDE.md`, `CONTRIBUTING.md`, CI workflows, a `.gitignore`, and -language-specific stubs (Go, Python, TypeScript, JavaScript, Rust, Java, or -shell), generated from a short description of the project. - -Two modes are supported: - -- **Greenfield** — you have an idea but no code yet. Inception interviews you - and produces a scaffold from scratch. -- **Brownfield** — you have an existing repo URL. Inception scans it and - produces facts/amendments rather than a from-scratch skeleton. - -## Prerequisites - -- The hive must be running the `brainstorm` agent (present by default in the - `level-1` ACMM pack — see `pkg/config/packs/level-1.yaml`). -- You must be signed in with the **owner** role. Every state-changing - inception endpoint calls `requireOwnerRole`, which checks the - `X-Hive-Role` header and the hub's owner-verification proof - (`X-Hive-Proxy-Auth`). Read-only endpoints (state, scaffold preview, - ideation-facts, download, has-files) do not require owner role. -- Only one inception run can be in progress at a time. Starting a new one - while `phase != complete` returns an error unless you pass `force: true`, - which archives the existing run as a campaign before resetting it. - -## The phase sequence - -Inception state moves through a strict, server-enforced state machine -(`InceptionPhase` in `pkg/knowledge/types.go`). Each phase transition is -gated — the corresponding handler rejects the call if the engine isn't in the -expected phase: - -``` -capture → clarify → structure → scaffold → complete -``` - -| Phase | What happens | Who acts | -|---|---|---| -| `capture` | You submit an idea (or a repo URL for brownfield). The engine seeds a `FactIdea` KB fact and creates the inception state. Hive kicks the `brainstorm` agent, which must generate 5–7 clarification questions as beads. | Operator starts; agent generates questions | -| `clarify` | Questions are recorded (`POST /api/inception/questions` records them and advances the phase). You answer them. | Operator answers | -| `structure` | Your answers are submitted (`POST /api/inception/answer`); the agent is re-kicked with the idea + answers and must create fact beads — 1 vision, 1 constitution, 2+ requirements, plus constraints/stakeholders/acceptance criteria as needed. You record them (`POST /api/inception/facts`), which writes each fact to the inception wiki vault and advances to `scaffold`. | Agent produces facts; operator records them | -| `scaffold` | `GET /api/inception/scaffold` (or `/download`) generates the project scaffold from the recorded facts — README, AGENTS.md, CLAUDE.md, CONTRIBUTING.md, CI workflows, `.gitignore`, and language-specific stubs inferred from the constitution fact (falling back to language cues in the idea text). | Operator reviews the generated files | -| `complete` | `POST /api/inception/approve` marks the run finished and re-pauses the `brainstorm` agent so the governor doesn't kick it again with generic ideation prompts. If `runs.spektacular.enabled` is on and the approve request identifies a real GitHub issue, Hive also admits that issue as the first `spec` stage of a long-running run. | Operator approves | - -Notes on the state machine, verified from `pkg/knowledge/inception.go`: - -- `SetQuestions` only succeeds from `capture` and moves to `clarify`. -- `SubmitAnswers` is accepted in both `clarify` and `structure` (the agent - can race ahead of the user submitting answers); it only advances the phase - when called from `clarify`. -- `RecordFacts` only succeeds from `structure` and moves to `scaffold`. -- `AdvanceToComplete` (approve) only succeeds from `scaffold` (or is a no-op - if already `complete`). -- `ProduceScaffold` (the scaffold/download handlers) can be called from any - phase where facts exist — it doesn't itself change phase. -- Starting a new inception (`Start` / `StartBrownfield`) is rejected unless - the previous run reached `complete`, or `force: true` is passed. - -## Driving the workflow through the API - -The dashboard no longer has a wizard for these steps; an API caller (with the -owner role for state-changing calls) drives them: - -1. Submit an idea (greenfield) with `POST /api/inception/start` or a repo URL - (brownfield) with `POST /api/inception/scan`. Both kick the `brainstorm` - agent (unpausing it first if the governor had paused it). -2. Wait for the agent to post 5–7 clarification questions as beads; poll - `GET /api/inception/state` until `POST /api/inception/questions` has - recorded them. -3. Answer them with `POST /api/inception/answer`. The agent is re-kicked (via - `SendKick`, not a full restart, to avoid losing its clarify-phase context) - with the idea, phase, and your answers injected via `${INCEPTION_*}` - template variables. -4. Wait for the agent to create fact beads, then record them via - `POST /api/inception/facts`. This writes each fact as a Markdown file - with YAML frontmatter into an `inception-wiki` vault directory and - connects that vault as a knowledge source for all agents. -5. Review the generated scaffold (`GET /api/inception/scaffold`) or download - it as a zip (`GET /api/inception/download`). -6. Approve (`POST /api/inception/approve`) to mark the run complete. This - also re-pauses `brainstorm` so the L2+ governor doesn't restart it with - unrelated ideation prompts. When long-running runs are enabled, include - either `issue_url` or `repo`/`issue_number` in the approve body to admit - the linked issue as the first `spec` stage. Inception does not create or - guess an issue number on its own; if the approve request does not name one, - completion remains a no-op for run admission. -7. If anything goes wrong, `POST /api/inception/reset` first archives the - current state and wiki files as an Inception campaign, then clears the - active state and state file under `inception/campaigns//`, so a reset - does not discard completed work. Nothing lists these archives any more; - see [Retired campaigns export](#retired-campaigns-export). - -Optional wiki-management calls, usable at any point once an inception has -produced wiki files: - -- `GET /api/inception/has-files` — whether the inception wiki has any `.md` - files. -- `PUT /api/inception/wiki-name` — rename the inception wiki vault - (persisted into inception state). -- `POST /api/inception/import` — upload a zip of Markdown files - (10 MiB max, 1 MiB per file, `.md` only, path-traversal guarded) to seed - or supplement the inception wiki without going through the agent. - -## API reference - -All 14 endpoints live under `/api/inception/*`, registered in -`pkg/dashboard/api.go` and implemented in `pkg/dashboard/inception_handlers.go`. -"Owner required" means the handler calls `requireOwnerRole` before doing -anything else. - -| Method | Path | Owner required | Purpose | -|---|---|---|---| -| `POST` | `/api/inception/start` | Yes | Begin a greenfield inception from idea text. `force: true` archives then resets any in-progress run first. | -| `POST` | `/api/inception/scan` | Yes | Begin a brownfield inception against a repo URL (`https://` or `http://` only). `force: true` archives then resets first. | -| `GET` | `/api/inception/state` | No | Current inception state (`null`/`active: false` if none in progress). | -| `POST` | `/api/inception/questions` | Yes | Record clarification questions generated by the agent; advances `capture` → `clarify`. | -| `POST` | `/api/inception/answer` | Yes | Submit answers to clarification questions; advances `clarify` → `structure` (accepted in both phases). | -| `POST` | `/api/inception/facts` | Yes | Record structured KB facts produced by the agent; advances `structure` → `scaffold`. | -| `GET` | `/api/inception/scaffold` | No | Generate and return the scaffold file set (does not change phase). | -| `POST` | `/api/inception/approve` | Yes | Advance `scaffold` → `complete`; re-pauses the `brainstorm` agent. Optional body fields `issue_url` or `repo`/`issue_number` admit the issue as a `spec` run when `runs.spektacular.enabled` is true. | -| `POST` | `/api/inception/reset` | Yes | Archive the current session as a campaign, then clear active inception state and re-pause `brainstorm`. | -| `GET` | `/api/inception/ideation-facts` | No | List recorded ideation facts (falls back to the inception engine's own fact gathering if the knowledge API has none). | -| `GET` | `/api/inception/download` | No | Download the scaffold as a zip, named from the idea slug. | -| `GET` | `/api/inception/has-files` | No | Whether the inception wiki vault has any `.md` files. | -| `PUT` | `/api/inception/wiki-name` | Yes | Rename the inception wiki vault (max 80 characters). | -| `POST` | `/api/inception/import` | Yes | Upload a zip of Markdown files into the inception wiki (10 MiB max upload, 1 MiB max per file). | - -See [Dashboard API reference](api-reference.md) for these endpoints in the -project-wide route index, and the [OpenAPI spec](../../dashboard/openapi.json) -for a machine-readable version. - -## Template variables - -The `brainstorm` agent's kick prompt (`pkg/policies/defaults/brainstorm-advisory.md`) -is built by the scheduler (`pkg/scheduler/templates.go`, `inceptionVars`) with these -inception-specific substitutions, documented in full in -[`policies/README.md`](../policies/README.md): - -| Variable | Value | -|---|---| -| `${INCEPTION_IDEA}` | Current inception idea text. Empty when no run is active — the template then falls through to "Normal Ideation Mode". | -| `${INCEPTION_PHASE}` | Current phase (`capture`, `clarify`, `structure`, `scaffold`, or `complete`). | -| `${INCEPTION_MODE}` | `greenfield` or `brownfield`. | -| `${INCEPTION_ANSWERS}` | Markdown-rendered Q&A, injected during the `clarify`/`structure` kick. | -| `${INCEPTION_SLUG}` | The idea/repo slug, used as the bead `--external-ref` (`inception/`) so the engine can distinguish inception beads from ordinary ideation beads on reap. | -| `${INCEPTION_REPO_URL}` | The scanned repo URL, brownfield mode only. | - -The template branches on `${INCEPTION_PHASE}` to give the agent -phase-specific instructions (generate questions in `capture`, review answers -in `clarify`, produce fact beads in `structure`, emit scaffold content in -`scaffold`). When `${INCEPTION_IDEA}` is empty, the agent falls back to -"Normal Ideation Mode" — general feature/architecture/strategy proposals -recorded as advisory beads, unrelated to any specific inception run. +## Retired: the inception API, watcher and brainstorm inception mode + +The old ACMM L1 inception workflow (a fixed `capture → clarify → structure → +scaffold → complete` state machine that drove the `brainstorm` agent and +generated a downloadable project scaffold) was retired in favour of Inception +(spek) sessions. Its dashboard wizard and Campaigns tab were removed first. +Now the backend is gone too: + +- **`/api/inception/*`**: all 14 routes (`start`, `scan`, `state`, + `questions`, `answer`, `facts`, `scaffold`, `approve`, `reset`, + `ideation-facts`, `download`, `has-files`, `wiki-name`, `import`) answer + **`410 Gone`** for one release, with a JSON body: + + ```json + {"ok": false, "error": "The inception API was retired. ...", "replacement": "/api/sessions", "docs": "https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md"} + ``` + + Nothing is read or changed. A later release removes the routes, and they + then answer `404`. Scripts that drove the workflow (`curl` against + `/api/inception/start` and friends) should start an Inception (spek) + session instead (`POST /api/sessions`, see the + [Sessions API](api-reference/sessions.md)). +- **The inception watcher** that turned brainstorm beads into inception + questions and facts no longer runs. +- **Inception approval as a run admission path** is gone. Spektacular runs are + admitted through run triage; see [Runs](runs.md). +- **The brainstorm agent's inception mode** is gone. `brainstorm` is + ideation-only: its kick template (`brainstorm-advisory.md`) records feature, + architecture, strategy, integration and DX proposals as advisory beads. It + is still on-demand and parked at boot. The `${INCEPTION_IDEA}`, + `${INCEPTION_PHASE}`, `${INCEPTION_MODE}`, `${INCEPTION_ANSWERS}`, + `${INCEPTION_SLUG}` and `${INCEPTION_REPO_URL}` template variables always + render empty for one release, so a custom template that still names them + keeps rendering. See [`policies/README.md`](../policies/README.md). + +### What is kept + +- **Knowledge facts from past inception runs.** The ideation facts those runs + recorded (vision, constitution, requirements, constraints, stakeholders, + acceptance criteria) live in the knowledge store and as Markdown files in + the `/data/inception-wiki` vault. Nothing deletes them. On boot Hive still + reconnects `/data/inception-wiki` as a knowledge vault, under the name the + run saved (`inception-wiki` by default), so agents keep reading those facts. +- **Files on the PVC.** `/data/inception/state.json`, `/data/inception-wiki/` + and `/data/inception/campaigns/` are left in place. The campaign archives + are also bundled into the one-time export described below. +- **Ideation fact types** (`idea`, `vision`, `constitution`, `requirement`, + `constraint`, `stakeholder`, `acceptance`) remain valid knowledge fact types. ## Retired campaigns export @@ -216,38 +94,13 @@ and stay as they are. To read the export: tar -tzf /data/exports/campaigns-*.tar.gz ``` -## Configuring the brainstorm agent - -The `brainstorm` agent is defined per ACMM pack, e.g. -`pkg/config/packs/level-1.yaml`. Two fields control how it participates in -inception: - -- **`on_demand: true`** — the agent is not kicked on a fixed cadence like - other agents; it is driven entirely by the inception workflow (via - `kickBrainstorm`/`sendKickBrainstorm` in `inception_handlers.go`) and - direct user queries. This is why `approve` and `reset` explicitly re-pause - the agent afterward — without `on_demand` semantics the governor would - otherwise pick it back up on its normal eval cycle. -- **`stale_timeout: 7200`** (seconds) — how long the agent's session may sit - idle before the supervisor considers it stale. Set this higher than the - time you expect a real user to take answering clarification questions, - since the session must stay alive across the `capture` → `clarify` → - `structure` round trip. - -`clear_on_kick: true` is also set — each inception kick clears prior CLI -context (`/clear`) before sending the new prompt, so multi-turn inception -state doesn't leak stale context from a previous kick. - -See [Agent configuration](agent-configuration.md) for the full field -reference and [ACMM policy matrix](acmm-policy-matrix.md) for how `brainstorm` -evolves in mode and responsibility from L1 onward. - ## Related documents +- [Inception (spek)](dashboard-sections/workflow-and-agents.md#inception-spek) + and the [Sessions API](api-reference/sessions.md). - [ACMM policy matrix](acmm-policy-matrix.md) — L1 agent roster and policy mode for `brainstorm`/`guide`. -- [`policies/README.md`](../policies/README.md) — full template variable - reference, including the `${INCEPTION_*}` family. -- [Dashboard API reference](api-reference.md) — project-wide endpoint index. +- [`policies/README.md`](../policies/README.md) — template variable reference, + including the deprecated `${INCEPTION_*}` family. - [Knowledge system design](design/knowledge-system.md) — how the inception wiki vault fits into the broader knowledge-base layering. diff --git a/src/docs/integrations/spektacular.md b/src/docs/integrations/spektacular.md index 885d965bae..24370e6c26 100644 --- a/src/docs/integrations/spektacular.md +++ b/src/docs/integrations/spektacular.md @@ -2,7 +2,7 @@ ## Audience -Use this page to choose between operating the existing runner and implementing a compatible planning CLI. Project Inception can turn an approved idea into a specification, a plan, then implementation work. +Use this page to choose between operating the existing runner and implementing a compatible planning CLI. A run turns a triaged issue into a specification, a plan, then implementation work. ## Operator path: use the existing runner @@ -16,7 +16,7 @@ Operators do not need to implement the interface below. Keep the tool's version A **lease** records temporary ownership of one workflow stage. An **artifact** is the resulting specification or plan; a **receipt** records stage completion. The **planner** imports plan tasks into work that an owner must approve before implementation. For example, a final specification can finish the `spec` stage without granting permission to implement its unapproved plan. -Project Inception can admit an approved issue into a long-running `spec` run when Spektacular support is enabled. The approval handler checks `runs.spektacular.enabled` before admission (`src/pkg/dashboard/inception_handlers.go:269`). The stage runner is installed at boot only when that same config flag is true (`src/cmd/hive/spektacularwire.go:19`). +Run triage admits a `spec`-classified issue into a long-running run when Spektacular support is enabled (Inception approval was a second admission path until the inception API was retired). The stage runner is installed at boot only when that same config flag is true (`src/cmd/hive/spektacularwire.go:19`). Spektacular owns artifact state; Hive owns the workflow lease. Hive polls Spektacular for `spec` and `plan` artifacts, advances leases on final documents, and imports final plan tasks into Hive's planner (`src/pkg/spektacular/adapter.go:97`). The dashboard side stays decoupled through the stage lease interface and `SetStageRunner` (`src/pkg/dashboard/stage_leases.go:87`). @@ -106,7 +106,7 @@ If export is unavailable, Hive falls back to `spektacular plan file read / ## Example flow -1. An operator approves an Inception run with an issue URL; when Spektacular is enabled, Hive admits the issue as a `spec` run (`src/pkg/dashboard/inception_handlers.go:269`). +1. Run triage classifies an issue as `spec`; when Spektacular is enabled, Hive admits it as a `spec` run (see [Runs](../runs.md)). 2. The runner polls `spektacular spec status ` until the spec is final (`src/pkg/spektacular/runner.go:359`). 3. Hive writes a stage receipt and advances the lease to `plan` (`src/pkg/spektacular/adapter.go:97`). 4. The runner polls `plan status`; on final it imports the structured plan (`src/pkg/spektacular/runner.go:403`). diff --git a/src/docs/runs.md b/src/docs/runs.md index 8e3080e574..ee383fcbcb 100644 --- a/src/docs/runs.md +++ b/src/docs/runs.md @@ -28,7 +28,7 @@ From the repository root, the same command is available as: just runs-e2e ``` -The test uses the same `HIVE_URL` / `HIVE_TOKEN` gating as the inception suite: +The test uses the `HIVE_URL` / `HIVE_TOKEN` gating shared by the `src/test` integration suite: if `HIVE_URL` is unset, the whole `src/test` integration suite skips. The run target must be a pinned issue that triages to `run/spec`; use either `HIVE_RUNS_E2E_KEY` or `HIVE_RUNS_E2E_REPO` plus `HIVE_RUNS_E2E_ISSUE`. @@ -145,7 +145,7 @@ subsequent reds. Long-running runs are the Hive workflow behind `spec` -> `plan` -> `implement` work. The workflow is default-off: with `runs.spektacular.enabled` unset or -`false`, Hive does not create the first stage lease from inception and does not +`false`, Hive does not create the first stage lease and does not start the Spek poll loop. ## How a run starts @@ -156,19 +156,12 @@ Admission creates one unowned `spec` lease keyed as that lease to agents when `governor.work_source.run_stages` is enabled. Repeated admission of the same repo/issue is idempotent and leaves one run active. -Today there are two admission paths: - -- **Run triage**: when `runs.triage.enabled` and `runs.spektacular.enabled` are - both true, incoming actionable issues classified as `spec` call `AdmitRun` - before the ordinary direct-fix dispatch path. -- **Inception approval**: when an inception moves to `complete` and - `runs.spektacular.enabled` is true, `POST /api/inception/approve` may include - `issue_url` or `repo` plus `issue_number`. Hive uses that explicit issue as - the run key and calls `AdmitRun`. - -Inception does not currently create or link a GitHub issue by itself. If an -approve request does not name an issue, Hive logs that no target was supplied -and does not fabricate a run. +Today the admission path is **run triage**: when `runs.triage.enabled` and +`runs.spektacular.enabled` are both true, incoming actionable issues +classified as `spec` call `AdmitRun` before the ordinary direct-fix dispatch +path. (Inception approval, `POST /api/inception/approve` with an explicit +issue, was the second path; it was retired with the inception API, which now +answers `410 Gone`.) See [spektacular.md](spektacular.md) for runner configuration and stage advancement, and [work-sources.md](work-sources.md) for how pending run stages diff --git a/src/internal/testutil/dashboard_import_allowlist.txt b/src/internal/testutil/dashboard_import_allowlist.txt index 25f17efbd9..acd50a4185 100644 --- a/src/internal/testutil/dashboard_import_allowlist.txt +++ b/src/internal/testutil/dashboard_import_allowlist.txt @@ -10,7 +10,6 @@ # workflowmodel: /api/workflows handlers compile lifecycle models (Compile, Profile diagnostics) and the tracker emits per-repo workflow columns; the store and bindings already route through Dependencies (hivecommons/hive#17620 P2). # egressmark: deployment_upgrade.go dials the in-cluster Kubernetes API for the hive's own rollout; the dial must carry the forced-egress SO_MARK or nodes without xt_owner redirect it into the MITM proxy (hivecommons/hive#17817). github.com/hivecommons/hive/crux -github.com/hivecommons/hive/crux/agentparse github.com/hivecommons/hive/crux/claude github.com/hivecommons/hive/crux/egressmark github.com/hivecommons/hive/crux/kubejob diff --git a/src/pkg/config/packs/level-1.yaml b/src/pkg/config/packs/level-1.yaml index 426b9c6295..3b14251408 100644 --- a/src/pkg/config/packs/level-1.yaml +++ b/src/pkg/config/packs/level-1.yaml @@ -1,9 +1,9 @@ level: 1 name: Inception description: > - Project inception. Brainstorm turns raw ideas into structured KB facts and - project scaffolding while guide provides interactive documentation and setup - advice. Both agents remain advisory and conversational; no GitHub write + Project inception. Inception (spek) sessions turn raw ideas into specs, + plans and a starting project; brainstorm proposes ideas as advisory beads + while guide provides interactive documentation and setup advice. Both agents remain advisory and conversational; no GitHub write actions or feedback loops run without a human. governor: modes: none @@ -41,11 +41,9 @@ agents: display_name: brainstorm role: brainstorm description: > - Project inception and ideation agent. At L1, turns a raw idea into - structured knowledge — vision, constitution, requirements, constraints, - acceptance criteria. Queries community KB for scaffolding patterns and - produces project bootstrap files. At higher levels, proposes features, - architecture directions, and strategic improvements. + Ideation agent. Proposes features, architecture directions, and + strategic improvements as advisory beads. (Turning a raw idea into a + project now happens in Inception (spek) sessions.) emoji: "💡" color: "#f39c12" sort_order: 5 @@ -58,7 +56,7 @@ agents: on_demand: true include_repos: false stale_timeout: 7200 - interactions: "Standalone. Driven by inception workflow and user queries." + interactions: "Standalone. Kicked on request." knowledge_use: > Heavy consumer of community wiki patterns, scaffolding templates, and language-specific defaults. PRODUCES ideation facts (idea, vision, diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 8cd84f91ee..cb14c9a5f8 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -426,20 +426,22 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("GET /api/hive-id", s.handleHiveIDGet) s.mux.HandleFunc("PUT /api/hive-id", s.handleHiveIDSet) - s.mux.HandleFunc("POST /api/inception/start", s.handleInceptionStart) - s.mux.HandleFunc("POST /api/inception/scan", s.handleInceptionScan) - s.mux.HandleFunc("GET /api/inception/state", s.handleInceptionState) - s.mux.HandleFunc("POST /api/inception/questions", s.handleInceptionSetQuestions) - s.mux.HandleFunc("POST /api/inception/answer", s.handleInceptionAnswer) - s.mux.HandleFunc("POST /api/inception/facts", s.handleInceptionRecordFacts) - s.mux.HandleFunc("GET /api/inception/scaffold", s.handleInceptionScaffold) - s.mux.HandleFunc("POST /api/inception/approve", s.handleInceptionApprove) - s.mux.HandleFunc("POST /api/inception/reset", s.handleInceptionReset) - s.mux.HandleFunc("GET /api/inception/ideation-facts", s.handleInceptionIdeationFacts) - s.mux.HandleFunc("GET /api/inception/download", s.handleInceptionDownload) - s.mux.HandleFunc("GET /api/inception/has-files", s.handleInceptionHasFiles) - s.mux.HandleFunc("PUT /api/inception/wiki-name", s.handleInceptionRenameWiki) - s.mux.HandleFunc("POST /api/inception/import", s.handleInceptionImport) + // The inception API was retired in favour of Inception (spek) sessions; + // every former route answers 410 Gone for one release (inception_gone.go). + s.mux.HandleFunc("POST /api/inception/start", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/scan", s.handleInceptionGone) + s.mux.HandleFunc("GET /api/inception/state", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/questions", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/answer", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/facts", s.handleInceptionGone) + s.mux.HandleFunc("GET /api/inception/scaffold", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/approve", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/reset", s.handleInceptionGone) + s.mux.HandleFunc("GET /api/inception/ideation-facts", s.handleInceptionGone) + s.mux.HandleFunc("GET /api/inception/download", s.handleInceptionGone) + s.mux.HandleFunc("GET /api/inception/has-files", s.handleInceptionGone) + s.mux.HandleFunc("PUT /api/inception/wiki-name", s.handleInceptionGone) + s.mux.HandleFunc("POST /api/inception/import", s.handleInceptionGone) // Plan-review gate (Phase 2 planning intelligence). Mirrors /api/inception/*. // Phase 4 adds the issue entry point: mint an epic from a GitHub issue and diff --git a/src/pkg/dashboard/coverage_boost2_test.go b/src/pkg/dashboard/coverage_boost2_test.go index 178b55722a..e94db782a1 100644 --- a/src/pkg/dashboard/coverage_boost2_test.go +++ b/src/pkg/dashboard/coverage_boost2_test.go @@ -17,36 +17,6 @@ import ( "github.com/hivecommons/hive/pkg/knowledge" ) -// --- isTemplatePlaceholder --- - -func TestIsTemplatePlaceholder(t *testing.T) { - tests := []struct { - input string - want bool - }{ - {"", true}, - {"", true}, - {"", true}, - {"<your question>", true}, - {"<description>", true}, - {"<bead title>", true}, - {"fact_title", true}, - {"question_title", true}, - {"your question here", true}, - {"<ANYTHING>", true}, - {"<AnY UPPER>", true}, - {"What is the deployment strategy?", false}, - {"", false}, - {"normal text", false}, - } - for _, tt := range tests { - got := isTemplatePlaceholder(tt.input) - if got != tt.want { - t.Errorf("isTemplatePlaceholder(%q) = %v, want %v", tt.input, got, tt.want) - } - } -} - // --- handleGovernorRepos --- func TestHandleGovernorRepos_EmptyBody(t *testing.T) { @@ -230,20 +200,6 @@ func TestHandleAgentPromptSave_BadBody(t *testing.T) { } } -// --- handleInceptionState --- - -func TestHandleInceptionState_NoInception(t *testing.T) { - srv := newFullServer(t) - srv.deps.Inception = nil - req := httptest.NewRequest("GET", "/api/inception/state", nil) - w := httptest.NewRecorder() - srv.handleInceptionState(w, req) - - if w.Code != http.StatusServiceUnavailable { - t.Errorf("code = %d, want 503", w.Code) - } -} - // --- MetricsCollector loadFromDisk with temp file --- func TestMetricsCollector_SaveAndLoadFromDisk(t *testing.T) { diff --git a/src/pkg/dashboard/coverage_boost4_test.go b/src/pkg/dashboard/coverage_boost4_test.go index a7a863f9c4..18e27c1d87 100644 --- a/src/pkg/dashboard/coverage_boost4_test.go +++ b/src/pkg/dashboard/coverage_boost4_test.go @@ -18,34 +18,6 @@ import ( "github.com/hivecommons/hive/pkg/knowledge" ) -// --- buildStructureKickMessage --- - -func TestBuildStructureKickMessage(t *testing.T) { - srv := newFullServer(t) - state := &knowledge.InceptionState{ - IdeaText: "Build a task manager", - IdeaSlug: "task-manager", - Questions: []knowledge.Question{ - {ID: "q1", Text: "What database?", Category: "storage"}, - {ID: "q2", Text: "What framework?", Category: "language"}, - }, - Answers: map[string]string{ - "q1": "PostgreSQL", - "q2": "React", - }, - } - msg := srv.buildStructureKickMessage(state) - if !strings.Contains(msg, "Structure phase") { - t.Error("expected Structure phase mention") - } - if !strings.Contains(msg, "PostgreSQL") { - t.Error("expected answer in message") - } - if !strings.Contains(msg, "task-manager") { - t.Error("expected idea slug in message") - } -} - // --- buildAgentLeaderboardEntries --- func TestBuildAgentLeaderboardEntries(t *testing.T) { @@ -138,16 +110,6 @@ func TestHandleAPIDocs_Boost(t *testing.T) { } } -// --- clearInceptionBeads --- - -func TestClearInceptionBeads(t *testing.T) { - srv := newFullServer(t) - dir := t.TempDir() - store, _ := beads.NewStore(dir) - srv.clearInceptionBeads(store) - // No open beads, should be a no-op -} - // --- LeaderboardForHub --- func TestLeaderboardForHub(t *testing.T) { diff --git a/src/pkg/dashboard/coverage_boost_test.go b/src/pkg/dashboard/coverage_boost_test.go index 6c5ce93797..681e7dfcaf 100644 --- a/src/pkg/dashboard/coverage_boost_test.go +++ b/src/pkg/dashboard/coverage_boost_test.go @@ -12,9 +12,9 @@ import ( "testing" "time" + "github.com/hivecommons/hive/crux" "github.com/hivecommons/hive/pkg/beads" "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/crux" "github.com/hivecommons/hive/pkg/governor" ) @@ -1580,36 +1580,6 @@ func TestCheckModelAllowed_EmptyModelRejected(t *testing.T) { } } -// --- handleInceptionStart --- - -func TestHandleInceptionStart_NoInception(t *testing.T) { - srv := newFullServer(t) - srv.deps.Inception = nil - req := httptest.NewRequest("POST", "/api/inception/start", strings.NewReader(`{"idea":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionStart(w, req) - - if w.Code != http.StatusServiceUnavailable { - t.Errorf("code = %d, want 503", w.Code) - } -} - -func TestHandleInceptionStart_BadBody(t *testing.T) { - srv := newFullServer(t) - srv.deps.Inception = nil - req := httptest.NewRequest("POST", "/api/inception/start", strings.NewReader("not json")) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionStart(w, req) - - if w.Code != http.StatusServiceUnavailable { - t.Errorf("code = %d, want 503 (inception nil checked first)", w.Code) - } -} - // --- handleKick edge cases --- func TestHandleKick_AgentNotFound(t *testing.T) { diff --git a/src/pkg/dashboard/dashboard_inception_handlers_test.go b/src/pkg/dashboard/dashboard_inception_handlers_test.go deleted file mode 100644 index 2589e8f7c8..0000000000 --- a/src/pkg/dashboard/dashboard_inception_handlers_test.go +++ /dev/null @@ -1,391 +0,0 @@ -package dashboard - -import ( - "context" - "log/slog" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/hivecommons/hive/pkg/config" -) - -func newMinimalServer(t *testing.T) *Server { - t.Helper() - cfg := &config.Config{ - Project: config.ProjectConfig{Org: "testorg", Name: "test", PrimaryRepo: "testrepo"}, - AgentRuntimeConfig: config.AgentRuntimeConfig{ - Agents: map[string]config.AgentConfig{}, - }, - } - srv := NewServer(0, slog.Default()) - srv.deps = &Dependencies{ - Config: cfg, - Logger: slog.Default(), - Ctx: context.Background(), - } - srv.RegisterAPI(srv.deps) - t.Cleanup(srv.CloseContributeHub) - return srv -} - -func TestHandleInceptionStartNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/start", strings.NewReader(`{"idea":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionStart(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionScanNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/scan", nil) - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionScan(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionStateNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/inception/state", nil) - w := httptest.NewRecorder() - srv.handleInceptionState(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionSetQuestionsNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/questions", strings.NewReader(`{"questions":[]}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionSetQuestions(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionAnswerNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/answer", strings.NewReader(`{"answers":{}}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionAnswer(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionRecordFactsNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/facts", strings.NewReader(`{"facts":[]}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionRecordFacts(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionScaffoldNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/scaffold", nil) - w := httptest.NewRecorder() - srv.handleInceptionScaffold(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionApproveNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/approve", nil) - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionApprove(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionResetNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/reset", nil) - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionReset(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionIdeationFactsNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/inception/ideation-facts", nil) - w := httptest.NewRecorder() - srv.handleInceptionIdeationFacts(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionDownloadNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/inception/download", nil) - w := httptest.NewRecorder() - srv.handleInceptionDownload(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionHasFilesNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/inception/has-files", nil) - w := httptest.NewRecorder() - srv.handleInceptionHasFiles(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } - if !strings.Contains(w.Body.String(), "false") { - t.Error("should return has_files=false when engine is nil") - } -} - -func TestHandleInceptionRenameWikiNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/rename-wiki", strings.NewReader(`{"name":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionRenameWiki(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleInceptionImportNilEngine(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/inception/import", strings.NewReader(`{"files":[]}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleInceptionImport(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Errorf("expected 503, got %d", w.Code) - } -} - -func TestHandleGHUserAuthStatusNoToken(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/gh-user-auth/status", nil) - w := httptest.NewRecorder() - srv.handleGHUserAuthStatus(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } - if !strings.Contains(w.Body.String(), "false") { - t.Error("should return logged_in=false") - } -} - -// A blank oauth_client_id resolves to the PUBLIC github.com Hive App client -// rather than failing: device-flow login is always github.com, even for a hive -// whose App and repos live on GHE. An earlier revision returned 400 here, which -// broke login for every hive that had not set oauth_client_id explicitly. -func TestHandleGHUserAuthStartBlankClientIDResolvesPublicDefault(t *testing.T) { - srv := newMinimalServer(t) - if got := srv.deps.Config.GitHub.OAuthClientID; got != "" { - t.Fatalf("precondition: want blank oauth_client_id, got %q", got) - } - if got := srv.deps.Config.GitHub.OAuthClientIDResolved(); got != config.DefaultOAuthClientID { - t.Fatalf("blank oauth_client_id must resolve to the public default %q, got %q", - config.DefaultOAuthClientID, got) - } - // Login host stays public github.com regardless of a GHE App host. - srv.deps.Config.GitHub.BaseURL = "https://github.ibm.com" - if got := srv.deps.Config.GitHub.OAuthBaseURL(); got != config.DefaultGitHubBaseURL { - t.Fatalf("GHE hive must still log in via %q, got %q", config.DefaultGitHubBaseURL, got) - } -} - -func TestHandleGHUserAuthPollNoState(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/gh-user-auth/poll", nil) - w := httptest.NewRecorder() - srv.handleGHUserAuthPoll(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("expected 400, got %d", w.Code) - } - if !strings.Contains(w.Body.String(), "no device flow") { - t.Error("should say no device flow in progress") - } -} - -func TestHandleGHUserAuthLogout(t *testing.T) { - srv := newMinimalServer(t) - sid := srv.createUserSession("owner", config.RoleOwner) - req := httptest.NewRequest("POST", "/api/gh-user-auth/logout", nil) - req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: sid}) - w := httptest.NewRecorder() - srv.handleGHUserAuthLogout(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } - if !strings.Contains(w.Body.String(), "logged_out") { - t.Error("should return logged_out status") - } -} - -func TestHandleSelfUpgradeNonOwner(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/self-upgrade", nil) - req.Header.Set("X-Hive-Role", "contributor") - w := httptest.NewRecorder() - srv.handleSelfUpgrade(w, req) - if w.Code != http.StatusForbidden { - t.Errorf("expected 403, got %d", w.Code) - } -} - -func TestHandleSelfUpgradeNoHubURL(t *testing.T) { - srv := newMinimalServer(t) - srv.deps.Config.Deployment = config.DeploymentConfig{Runtime: "kubernetes"} - req := httptest.NewRequest("POST", "/api/self-upgrade", nil) - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleSelfUpgrade(w, req) - if w.Code != http.StatusBadRequest { - t.Errorf("expected 400, got %d", w.Code) - } -} - -func TestHandleSnapshotAPINotEnabled(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/snapshot", nil) - w := httptest.NewRecorder() - srv.handleSnapshotAPI(w, req) - if w.Code != http.StatusNotFound { - t.Errorf("expected 404, got %d", w.Code) - } -} - -func TestHandleSnapshotPageNotEnabled(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/snapshot", nil) - w := httptest.NewRecorder() - srv.handleSnapshotPage(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } - if !strings.Contains(w.Body.String(), "Snapshots are not enabled") { - t.Logf("body: %s", w.Body.String()[:200]) - } -} - -func TestHandleGitSourcesListNilKnowledge(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/knowledge/git-sources", nil) - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleGitSourcesList(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } -} - -func TestHandleGitSourcesConnectNoKnowledge(t *testing.T) { - srv := newMinimalServer(t) - // ensureKnowledge will try to create a file-based knowledge API - req := httptest.NewRequest("POST", "/api/knowledge/git-sources", strings.NewReader(`{}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleGitSourcesConnect(w, req) - // Should get 400 (invalid request body or missing fields) since ensureKnowledge creates a fallback - if w.Code != http.StatusBadRequest { - t.Logf("git sources connect: got %d (body: %s)", w.Code, w.Body.String()) - } -} - -func TestHandleGitSourcesDisconnectNilKnowledge(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("POST", "/api/knowledge/git-sources/disconnect", strings.NewReader(`{"url":"https://example.com"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - markOwnerRequest(req) - srv.handleGitSourcesDisconnect(w, req) - if w.Code != http.StatusServiceUnavailable { - t.Logf("git sources disconnect: got %d", w.Code) - } -} - -func TestHandleAPIDocs(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/v1/docs", nil) - w := httptest.NewRecorder() - srv.handleAPIDocs(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected 200, got %d", w.Code) - } - if !strings.Contains(w.Header().Get("Content-Type"), "text/html") { - t.Error("should return HTML") - } -} - -func TestReadJSONValid(t *testing.T) { - body := strings.NewReader(`{"idea":"test project"}`) - req := httptest.NewRequest("POST", "/test", body) - var result struct { - Idea string `json:"idea"` - } - err := readJSON(req, &result) - if err != nil { - t.Errorf("readJSON error: %v", err) - } - if result.Idea != "test project" { - t.Errorf("idea = %q", result.Idea) - } -} - -func TestReadJSONInvalid(t *testing.T) { - body := strings.NewReader(`{invalid`) - req := httptest.NewRequest("POST", "/test", body) - var result struct{} - err := readJSON(req, &result) - if err == nil { - t.Error("should error on invalid JSON") - } -} - -func TestReadJSONEmpty(t *testing.T) { - body := strings.NewReader(``) - req := httptest.NewRequest("POST", "/test", body) - var result struct{} - err := readJSON(req, &result) - if err == nil { - t.Error("should error on empty body") - } -} - -func TestHandleKnowledgeExportNilKnowledge(t *testing.T) { - srv := newMinimalServer(t) - req := httptest.NewRequest("GET", "/api/knowledge/export", nil) - markOwnerRequest(req) - w := httptest.NewRecorder() - srv.handleKnowledgeExport(w, req) - // Should handle nil knowledge gracefully — either 503 or creates fallback - _ = w.Code -} diff --git a/src/pkg/dashboard/deps.go b/src/pkg/dashboard/deps.go index bb02a9ae41..3d635a6d2e 100644 --- a/src/pkg/dashboard/deps.go +++ b/src/pkg/dashboard/deps.go @@ -106,7 +106,6 @@ type Dependencies struct { ReviewerAutoscaleStatus func() autoscale.Status Tokens *tokens.Collector Knowledge *knowledge.KnowledgeAPI - Inception *knowledge.InceptionEngine Nous *NousState Scheduler SchedulerControl MetricsCollector *MetricsCollector diff --git a/src/pkg/dashboard/inception_auth_boundary_test.go b/src/pkg/dashboard/inception_auth_boundary_test.go deleted file mode 100644 index f22c84b8b5..0000000000 --- a/src/pkg/dashboard/inception_auth_boundary_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package dashboard - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -// TestInceptionHandlers_NonOwnerReturns403 verifies that all owner-protected -// inception handlers reject requests without owner role headers with 403. -// This is a security boundary test — if requireOwnerRole is accidentally -// removed from any handler, this test catches it. -func TestInceptionHandlers_NonOwnerReturns403(t *testing.T) { - srv := newMinimalServer(t) - - cases := []struct { - name string - method string - path string - body string - }{ - {"start", "POST", "/api/inception/start", `{"idea":"test"}`}, - {"scan", "POST", "/api/inception/scan", `{"repo_url":"https://example.com/repo"}`}, - {"questions", "POST", "/api/inception/questions", `{"questions":[]}`}, - {"answer", "POST", "/api/inception/answer", `{"answers":{}}`}, - {"facts", "POST", "/api/inception/facts", `{"facts":[]}`}, - {"approve", "POST", "/api/inception/approve", ``}, - {"reset", "POST", "/api/inception/reset", ``}, - {"rename-wiki", "PUT", "/api/inception/wiki-name", `{"name":"test"}`}, - {"import", "POST", "/api/inception/import", ``}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - var body *strings.Reader - if tc.body != "" { - body = strings.NewReader(tc.body) - } - - var req *http.Request - if body != nil { - req = httptest.NewRequest(tc.method, tc.path, body) - req.Header.Set("Content-Type", "application/json") - } else { - req = httptest.NewRequest(tc.method, tc.path, nil) - } - // Explicitly set a non-owner role. - req.Header.Set("X-Hive-Role", "contributor") - - w := httptest.NewRecorder() - srv.mux.ServeHTTP(w, req) - if w.Code != http.StatusForbidden { - t.Errorf("expected 403 for non-owner %s %s, got %d", tc.method, tc.path, w.Code) - } - }) - } -} - -// TestInceptionHandlers_NoRoleReturns403 verifies that requests with -// no role header at all are rejected with 403. -func TestInceptionHandlers_NoRoleReturns403(t *testing.T) { - srv := newMinimalServer(t) - - req := httptest.NewRequest("POST", "/api/inception/start", strings.NewReader(`{"idea":"test"}`)) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - srv.mux.ServeHTTP(w, req) - if w.Code != http.StatusForbidden { - t.Errorf("expected 403 for missing role header, got %d", w.Code) - } -} - -// TestInceptionHandlers_UnprotectedEndpointsNoAuthRequired verifies that -// read-only inception endpoints work without owner role headers. -func TestInceptionHandlers_UnprotectedEndpointsNoAuthRequired(t *testing.T) { - s, _, _ := covFInceptionServer(t) - - // Start an inception so state endpoints return data. - rec := doOwnerPost(s, "/api/inception/start", map[string]interface{}{"idea": "auth test idea"}) - if rec.Code != http.StatusOK { - t.Fatalf("start: %d", rec.Code) - } - - unprotected := []struct { - name string - path string - }{ - {"state", "/api/inception/state"}, - {"scaffold", "/api/inception/scaffold"}, - {"has-files", "/api/inception/has-files"}, - {"ideation-facts", "/api/inception/ideation-facts"}, - {"download", "/api/inception/download"}, - } - - for _, tc := range unprotected { - t.Run(tc.name, func(t *testing.T) { - // GET without owner headers — should NOT return 403. - rec := doGet(s, tc.path) - if rec.Code == http.StatusForbidden { - t.Errorf("%s should be accessible without owner role, got 403", tc.path) - } - }) - } -} diff --git a/src/pkg/dashboard/inception_beads_kick_test.go b/src/pkg/dashboard/inception_beads_kick_test.go deleted file mode 100644 index b1c96dcd95..0000000000 --- a/src/pkg/dashboard/inception_beads_kick_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package dashboard - -import ( - "context" - "io" - "log/slog" - "net/http" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/knowledge" -) - -// covFInceptionServerWithBeads builds a test server with a real bead store -// under the "brainstorm" key so that clearInceptionBeads gets exercised. -func covFInceptionServerWithBeads(t *testing.T) (*Server, *knowledge.InceptionEngine, *beads.Store) { - t.Helper() - logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})) - kapi := knowledge.NewKnowledgeAPI(nil, knowledge.KnowledgeConfig{}, logger) - eng := knowledge.NewInceptionEngine(t.TempDir(), kapi, logger) - - beadDir := t.TempDir() - store, err := beads.NewStore(beadDir) - if err != nil { - t.Fatalf("NewStore: %v", err) - } - - s := NewServer(0, logger) - deps := testDeps(t) - deps.Inception = eng - deps.Knowledge = kapi - deps.BeadStores = map[string]*beads.Store{"brainstorm": store} - s.RegisterAPI(deps) - return s, eng, store -} - -func TestCovF_ClearInceptionBeadsOnForceStart(t *testing.T) { - s, _, store := covFInceptionServerWithBeads(t) - - // Seed the bead store with open brainstorm/inception beads that should be closed. - b1, err := store.Create("brainstorm bead 1", beads.TypeTask, beads.PriorityMedium, "brainstorm", "") - if err != nil { - t.Fatalf("create bead1: %v", err) - } - b2, err := store.Create("inception bead", beads.TypeAdvisory, beads.PriorityHigh, "inception", "") - if err != nil { - t.Fatalf("create bead2: %v", err) - } - // A bead with a different actor should NOT be closed. - b3, err := store.Create("scanner bead", beads.TypeTask, beads.PriorityLow, "scanner", "") - if err != nil { - t.Fatalf("create bead3: %v", err) - } - - // First start to get into an active state. - rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "clear beads test idea"}) - if rec.Code != http.StatusOK { - t.Fatalf("start1: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - // Force start — this should call clearInceptionBeads and close b1 + b2. - rec = doPost(s, "/api/inception/start", map[string]interface{}{ - "idea": "second idea after force reset", - "force": true, - }) - if rec.Code != http.StatusOK { - t.Fatalf("start2 force: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - time.Sleep(80 * time.Millisecond) // let kickBrainstorm goroutine run - - // Verify brainstorm/inception beads were closed. - allBeads := store.List(beads.ListFilter{}) - for _, b := range allBeads { - switch b.ID { - case b1.ID, b2.ID: - if b.Status != beads.StatusClosed { - t.Errorf("bead %s (actor=%s) should be closed, got status=%s", b.ID, b.Actor, b.Status) - } - case b3.ID: - if b.Status != beads.StatusOpen { - t.Errorf("scanner bead %s should remain open, got status=%s", b.ID, b.Status) - } - } - } -} - -func TestCovF_ClearInceptionBeadsOnForceScan(t *testing.T) { - s, _, store := covFInceptionServerWithBeads(t) - - // Seed beads. - b1, err := store.Create("brainstorm finding", beads.TypeAdvisory, beads.PriorityHigh, "brainstorm", "") - if err != nil { - t.Fatalf("create: %v", err) - } - - // Do a normal start first. - rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "scan test idea"}) - if rec.Code != http.StatusOK { - t.Fatalf("start: expected 200, got %d", rec.Code) - } - - // Force scan — exercises the force branch in handleInceptionScan. - rec = doPost(s, "/api/inception/scan", map[string]interface{}{ - "repo_url": "https://github.com/example/repo", - "force": true, - }) - if rec.Code != http.StatusOK { - t.Fatalf("scan force: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - time.Sleep(80 * time.Millisecond) - - // Verify bead was closed. - allBeads := store.List(beads.ListFilter{}) - for _, b := range allBeads { - if b.ID == b1.ID && b.Status != beads.StatusClosed { - t.Errorf("brainstorm bead should be closed after force scan, got %s", b.Status) - } - } -} - -func TestCovF_ClearInceptionBeadsOnReset(t *testing.T) { - s, _, store := covFInceptionServerWithBeads(t) - - // Seed beads. - b1, _ := store.Create("inception bead for reset", beads.TypeTask, beads.PriorityMedium, "inception", "") - b2, _ := store.Create("other agent bead", beads.TypeTask, beads.PriorityMedium, "quality", "") - - // Start, then reset. - doPost(s, "/api/inception/start", map[string]interface{}{"idea": "reset beads test"}) - rec := doPost(s, "/api/inception/reset", map[string]interface{}{}) - if rec.Code != http.StatusOK { - t.Fatalf("reset: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - allBeads := store.List(beads.ListFilter{}) - for _, b := range allBeads { - switch b.ID { - case b1.ID: - if b.Status != beads.StatusClosed { - t.Errorf("inception bead should be closed on reset, got %s", b.Status) - } - case b2.ID: - if b.Status != beads.StatusOpen { - t.Errorf("quality bead should remain open, got %s", b.Status) - } - } - } -} - -func TestCovF_ClearInceptionBeadsSkipsNonOpen(t *testing.T) { - s, _, store := covFInceptionServerWithBeads(t) - - // Create a bead and close it manually before force-start. - b1, _ := store.Create("already closed bead", beads.TypeTask, beads.PriorityMedium, "brainstorm", "") - _ = store.Close(b1.ID) - - doPost(s, "/api/inception/start", map[string]interface{}{"idea": "skip closed beads test"}) - rec := doPost(s, "/api/inception/start", map[string]interface{}{ - "idea": "second idea", - "force": true, - }) - if rec.Code != http.StatusOK { - t.Fatalf("force start: expected 200, got %d", rec.Code) - } - time.Sleep(50 * time.Millisecond) - // No panic, no error — already-closed bead should be skipped gracefully. -} - -func TestCovF_KickBrainstormWithBeadStore(t *testing.T) { - s, eng, _ := covFInceptionServerWithBeads(t) - - // Start and advance to structure phase to exercise sendKickBrainstorm path. - doPost(s, "/api/inception/start", map[string]interface{}{"idea": "kick with beads test"}) - doPost(s, "/api/inception/questions", map[string]interface{}{ - "questions": []knowledge.Question{ - {ID: "lang", Text: "Language?", Category: "language"}, - }, - }) - rec := doPost(s, "/api/inception/answer", map[string]interface{}{ - "answers": map[string]string{"lang": "Python"}, - }) - if rec.Code != http.StatusOK { - t.Fatalf("answer: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - // Let sendKickBrainstorm goroutine run. - time.Sleep(150 * time.Millisecond) - - // Record facts to get to scaffold phase. - _ = eng.RecordFacts(context.Background(), []knowledge.IdeationFact{ - {Title: "Vision", Body: "a tool", Type: knowledge.FactVision}, - {Title: "Const", Body: "keep it simple", Type: knowledge.FactConstitution}, - {Title: "Req", Body: "do stuff", Type: knowledge.FactRequirement}, - }) - - // kickBrainstorm should now skip (past structure phase). - s.kickBrainstorm() - time.Sleep(50 * time.Millisecond) -} diff --git a/src/pkg/dashboard/inception_buffer_interceptors_test.go b/src/pkg/dashboard/inception_buffer_interceptors_test.go deleted file mode 100644 index 91f23056c6..0000000000 --- a/src/pkg/dashboard/inception_buffer_interceptors_test.go +++ /dev/null @@ -1,326 +0,0 @@ -package dashboard - -import ( - "context" - "slices" - "testing" - - "github.com/hivecommons/hive/crux" - "github.com/hivecommons/hive/crux/cruxtest" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func newBufferInterceptorWatcher( - t *testing.T, - lines []string, - withBrainstormAgent bool, -) (*InceptionWatcher, *knowledge.InceptionEngine) { - t.Helper() - - w, eng, _ := covFWatcher(t) - agents := map[string]config.AgentConfig{} - if withBrainstormAgent { - agents["brainstorm"] = config.AgentConfig{Backend: "claude"} - } - mgr := cruxtest.NewRuntime(agents, covFWatcherLogger(), crux.ProjectContext{}) - if withBrainstormAgent { - status, err := mgr.GetStatus("brainstorm") - if err != nil { - t.Fatalf("GetStatus(brainstorm): %v", err) - } - for _, line := range lines { - status.OutputBuffer.Write(line) - } - } - w.agentMgr = mgr - return w, eng -} - -func startBufferInterceptorInception( - t *testing.T, - eng *knowledge.InceptionEngine, -) *knowledge.InceptionState { - t.Helper() - - if _, err := eng.Start("exercise inception output buffer parsing"); err != nil { - t.Fatalf("Start: %v", err) - } - state := eng.GetState() - if state == nil { - t.Fatal("expected inception state after Start") - } - return state -} - -func TestInterceptFactsFromBuffer(t *testing.T) { - tests := []struct { - name string - lines []string - withAgent bool - existingSlugs []string - initialFactLines []string - want []string - }{ - { - name: "captures realistic fact markers and deduplicates", - withAgent: true, - lines: []string{ - "Starting analysis of the project", - "Vision: Build a reliable incident console for operators", - "Requirement: operators can replay failed events", - "Requirement: operators can replay failed events", - "Testing: exercise agent output split across polls", - "Deployment: run the service in Kubernetes", - }, - want: []string{ - "Vision: Build a reliable incident console for operators", - "Requirement: operators can replay failed events", - "Testing: exercise agent output split across polls", - "Deployment: run the service in Kubernetes", - }, - }, - { - name: "does not join partial lines or capture noise", - withAgent: true, - lines: []string{ - "Vis", - "ion: continued in the next buffer line", - "require", - "ment: also split across lines", - "ordinary command output", - }, - }, - { - name: "retains previously buffered facts without duplicates", - withAgent: true, - initialFactLines: []string{ - "Vision: Build a reliable incident console for operators", - }, - lines: []string{ - "Vision: Build a reliable incident console for operators", - "Constraint: keep every parser operation bounded", - }, - want: []string{ - "Vision: Build a reliable incident console for operators", - "Constraint: keep every parser operation bounded", - }, - }, - { - name: "skips interception after enough facts exist", - withAgent: true, - existingSlugs: []string{ - "vision", "requirement", "constraint", - }, - lines: []string{"Vision: this line must not be buffered"}, - }, - { - name: "empty buffer is ignored", - withAgent: true, - }, - { - name: "buffer lookup error is ignored", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - w, _ := newBufferInterceptorWatcher(t, tt.lines, tt.withAgent) - w.plukFactLines = append([]string(nil), tt.initialFactLines...) - state := &knowledge.InceptionState{FactSlugs: tt.existingSlugs} - - w.interceptFactsFromBuffer(context.Background(), state) - - if !slices.Equal(w.plukFactLines, tt.want) { - t.Fatalf("buffered fact lines = %#v, want %#v", w.plukFactLines, tt.want) - } - }) - } -} - -func TestInterceptQuestionsFromBuffer(t *testing.T) { - tests := []struct { - name string - lines []string - withAgent bool - preexisting []knowledge.Question - wantPhase knowledge.InceptionPhase - wantBufferedCount int - wantQuestionCount int - }{ - { - name: "accepts command preview and question formats", - withAgent: true, - lines: []string{ - `bd create --title "Who are the primary users?" --type advisory`, - ` └ --title "Which features are required?" --type advisory`, - "3. Which language should power the service?", - "4. What testing strategy should validate releases?", - "5. Which deployment target should host it?", - }, - wantPhase: knowledge.PhaseClarify, - wantQuestionCount: minQuestionsForAdvance, - }, - { - name: "deduplicates repeated questions", - withAgent: true, - lines: []string{ - `bd create --title "Who are the primary users?" --type advisory`, - `bd create --title "Who are the primary users?" --type advisory`, - }, - wantPhase: knowledge.PhaseCapture, - wantBufferedCount: 1, - }, - { - name: "does not join partial lines or capture noise", - withAgent: true, - lines: []string{ - "bd create --tit", - `le "What should happen?"`, - "Which deployment target", - "should host the service?", - "ordinary command output", - }, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "skips interception after enough questions exist", - withAgent: true, - preexisting: []knowledge.Question{ - {ID: "1"}, {ID: "2"}, {ID: "3"}, {ID: "4"}, {ID: "5"}, - }, - lines: []string{`bd create --title "Who are the users?"`}, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "empty buffer is ignored", - withAgent: true, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "buffer lookup error is ignored", - wantPhase: knowledge.PhaseCapture, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - w, eng := newBufferInterceptorWatcher(t, tt.lines, tt.withAgent) - state := startBufferInterceptorInception(t, eng) - state.Questions = append([]knowledge.Question(nil), tt.preexisting...) - - w.interceptQuestionsFromBuffer(state) - - gotState := eng.GetState() - if gotState.Phase != tt.wantPhase { - t.Fatalf("phase = %q, want %q", gotState.Phase, tt.wantPhase) - } - if len(w.plukQuestions) != tt.wantBufferedCount { - t.Fatalf("buffered questions = %d, want %d", len(w.plukQuestions), tt.wantBufferedCount) - } - if len(gotState.Questions) != tt.wantQuestionCount { - t.Fatalf("stored questions = %d, want %d", len(gotState.Questions), tt.wantQuestionCount) - } - }) - } -} - -func TestCheckForQuestionsInOutput(t *testing.T) { - tableLines := []string{ - "┌─────────────┬─────────────────────────────────────────┬──────────────┐", - "│ Category │ Question │ Default │", - "├─────────────┼─────────────────────────────────────────┼──────────────┤", - "│ users │ Who are the primary users? │ Operators │", - "│ features │ Which features are required? │ Replay │", - "│ language │ Which language should power it? │ Go │", - "│ testing │ How should releases be validated? │ Unit tests │", - "│ deployment │ Where should the service run? │ Kubernetes │", - "└─────────────┴─────────────────────────────────────────┴──────────────┘", - } - tests := []struct { - name string - lines []string - withAgent bool - lastQuestionCount int - wantPhase knowledge.InceptionPhase - wantQuestionCount int - }{ - { - name: "extracts a complete question table", - lines: tableLines, - withAgent: true, - wantPhase: knowledge.PhaseClarify, - wantQuestionCount: minQuestionsForAdvance, - }, - { - name: "falls back to numbered questions", - lines: []string{ - "1. Users — who will use this?", - "2. Features — what must it do?", - "3. Language — what language should we use?", - "4. Testing — how should we test it?", - "5. Deployment — where should it run?", - }, - withAgent: true, - wantPhase: knowledge.PhaseClarify, - wantQuestionCount: minQuestionsForAdvance, - }, - { - name: "deduplicates repeated table categories before applying", - lines: []string{ - "│ language │ Which language should power it? │ Go │", - "│ language │ Which language should power it? │ Go │", - "│ language │ Which language should power it? │ Go │", - "│ language │ Which language should power it? │ Go │", - "│ language │ Which language should power it? │ Go │", - }, - withAgent: true, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "partial table and noise do not advance", - withAgent: true, - lines: []string{ - "│ Category │ Question │ Default │", - "│ users │ Who are the primary", - "users? │ Operators │", - "ordinary command output", - }, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "unchanged question count is ignored", - lines: tableLines, - withAgent: true, - lastQuestionCount: minQuestionsForAdvance, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "empty buffer is ignored", - withAgent: true, - wantPhase: knowledge.PhaseCapture, - }, - { - name: "buffer lookup error is ignored", - wantPhase: knowledge.PhaseCapture, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - w, eng := newBufferInterceptorWatcher(t, tt.lines, tt.withAgent) - startBufferInterceptorInception(t, eng) - w.lastQuestionCount = tt.lastQuestionCount - - w.checkForQuestionsInOutput() - - gotState := eng.GetState() - if gotState.Phase != tt.wantPhase { - t.Fatalf("phase = %q, want %q", gotState.Phase, tt.wantPhase) - } - if len(gotState.Questions) != tt.wantQuestionCount { - t.Fatalf("stored questions = %d, want %d", len(gotState.Questions), tt.wantQuestionCount) - } - }) - } -} diff --git a/src/pkg/dashboard/inception_facts_grace_test.go b/src/pkg/dashboard/inception_facts_grace_test.go deleted file mode 100644 index 10874ad416..0000000000 --- a/src/pkg/dashboard/inception_facts_grace_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package dashboard - -import ( - "context" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/knowledge" -) - -// factWatcher builds a watcher (via the shared covFWatcher fixture) whose -// engine has been walked to the fact-gathering phase: started, questions set, -// answers submitted. Beads created after this call count as inception beads. -func factWatcher(t *testing.T) (*InceptionWatcher, *knowledge.InceptionEngine, *beads.Store) { - t.Helper() - w, eng, store := covFWatcher(t) - if _, err := eng.Start("a grace-period idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - if err := eng.SetQuestions([]knowledge.Question{{ID: "q1", Text: "lang?", Category: "language"}}); err != nil { - t.Fatalf("SetQuestions: %v", err) - } - if _, err := eng.SubmitAnswers(map[string]string{"q1": "Go"}); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - // Backdate StartedAt slightly so freshly-created beads count as "after". - time.Sleep(10 * time.Millisecond) - return w, eng, store -} - -func createFactBead(t *testing.T, store *beads.Store, title, factType string) *beads.Bead { - t.Helper() - b, err := store.Create(title, beads.TypeAdvisory, beads.PriorityHigh, "brainstorm", "inception/idea") - if err != nil { - t.Fatalf("create bead %q: %v", title, err) - } - if factType != "" { - if err := store.SetMetadata(b.ID, "fact_type", factType); err != nil { - t.Fatalf("set fact_type: %v", err) - } - } - return b -} - -// TestCheckForFactsBelowMinimumDoesNothing pins the floor: fewer than -// minFactsForAdvance facts must neither advance the phase nor start the -// enrichment grace clock — otherwise two early beads could freeze the -// grace window before the brainstorm has really produced anything. -func TestCheckForFactsBelowMinimumDoesNothing(t *testing.T) { - w, eng, store := factWatcher(t) - for i := 0; i < minFactsForAdvance-1; i++ { - createFactBead(t, store, "Requirement early "+string(rune('A'+i)), "requirement") - } - - w.checkForFacts(context.Background(), w.findInceptionBeads()) - - if st := eng.GetState(); st == nil || st.Phase == knowledge.PhaseScaffold { - t.Fatalf("phase advanced on %d facts (< min %d): %+v", minFactsForAdvance-1, minFactsForAdvance, st) - } - if !w.factGraceStart.IsZero() { - t.Fatal("grace period started below the minimum fact count") - } -} - -// TestCheckForFactsGracePeriodLifecycle walks the between-min-and-target -// path: the first sighting starts the grace clock without advancing, more -// facts arriving during grace only update the running count, and once the -// grace period has elapsed the watcher records and advances to scaffold, -// resetting the clock. -func TestCheckForFactsGracePeriodLifecycle(t *testing.T) { - w, eng, store := factWatcher(t) - - // minFactsForAdvance facts: enough to start grace, short of the target. - titles := []string{"Vision statement", "Requirement one", "Constraint one"} - types := []string{"vision", "requirement", "constraint"} - for i, title := range titles { - createFactBead(t, store, title, types[i]) - } - - // First sighting: grace starts, no advance. - w.checkForFacts(context.Background(), w.findInceptionBeads()) - if w.factGraceStart.IsZero() { - t.Fatal("grace period did not start at the minimum fact count") - } - if st := eng.GetState(); st == nil || st.Phase == knowledge.PhaseScaffold { - t.Fatalf("phase advanced immediately at minimum count: %+v", st) - } - - // One more fact during grace: count updates, still no advance. - createFactBead(t, store, "Stakeholder one", "stakeholder") - w.checkForFacts(context.Background(), w.findInceptionBeads()) - if w.lastFactCount != len(titles)+1 { - t.Fatalf("lastFactCount = %d, want %d (updated during grace)", w.lastFactCount, len(titles)+1) - } - if st := eng.GetState(); st == nil || st.Phase == knowledge.PhaseScaffold { - t.Fatalf("phase advanced during grace period: %+v", st) - } - - // Grace elapsed (backdated) plus one more fact: record and advance. - createFactBead(t, store, "Acceptance one", "acceptance") - w.factGraceStart = time.Now().Add(-factEnrichmentGracePeriod - time.Second) - w.checkForFacts(context.Background(), w.findInceptionBeads()) - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold after grace elapsed, got %+v", st) - } - if !w.factGraceStart.IsZero() { - t.Fatal("grace clock not reset after recording facts") - } -} - -// TestCheckForFactsFallbacksAndSkips pins the per-bead salvage rules: a -// missing fact_type is inferred from the title (and an uninferable title -// skips the bead entirely), the body falls back through detail → Notes → -// Title, and fact_tags is split and trimmed. Advancing to scaffold on -// exactly targetFactCount salvageable beads — with an unsalvageable one in -// the mix — proves the skip didn't eat a real fact and the fallbacks didn't -// drop one. -func TestCheckForFactsFallbacksAndSkips(t *testing.T) { - w, eng, store := factWatcher(t) - - // Unsalvageable: no fact_type metadata, title infers nothing. Must be - // skipped without poisoning the batch. - createFactBead(t, store, "hello world", "") - - // Inferred from title (no fact_type metadata), body falls back to Title. - createFactBead(t, store, "Constraint: no external calls", "") - - // Body from the detail metadata fallback. - b := createFactBead(t, store, "Requirement one", "requirement") - if err := store.SetMetadata(b.ID, "detail", "detail body"); err != nil { - t.Fatalf("set detail: %v", err) - } - - // Body from the Notes fallback. - b = createFactBead(t, store, "Requirement two", "requirement") - if err := store.Update(b.ID, func(bd *beads.Bead) { bd.Notes = "notes body" }); err != nil { - t.Fatalf("set notes: %v", err) - } - - // fact_tags split and trimmed. - b = createFactBead(t, store, "Vision statement", "vision") - if err := store.SetMetadata(b.ID, "fact_tags", " alpha , beta "); err != nil { - t.Fatalf("set fact_tags: %v", err) - } - - // Top up to targetFactCount salvageable facts so the watcher advances - // immediately (no grace period on a full batch). - for i := 0; i < targetFactCount-4; i++ { - createFactBead(t, store, "Requirement extra "+string(rune('A'+i)), "requirement") - } - - w.checkForFacts(context.Background(), w.findInceptionBeads()) - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold from %d salvageable facts, got %+v", targetFactCount, st) - } -} diff --git a/src/pkg/dashboard/inception_gone.go b/src/pkg/dashboard/inception_gone.go new file mode 100644 index 0000000000..a3aaecd79a --- /dev/null +++ b/src/pkg/dashboard/inception_gone.go @@ -0,0 +1,28 @@ +package dashboard + +import "net/http" + +const ( + // inceptionGoneMessage is the body of every retired /api/inception/* + // route. The step-by-step inception workflow (start, scan, questions, + // answers, facts, scaffold, approve, reset, wiki import and rename) was + // retired in favour of Inception (spek) sessions. + inceptionGoneMessage = "The inception API was retired. Use Inception (spek) sessions instead: the dashboard's Inception (spek) section, or /api/sessions. Facts from past inception runs stay in the knowledge base." + // inceptionGoneDocs points callers at the migration notes. + inceptionGoneDocs = "https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md" + // inceptionGoneReplacement is the API that replaces it. + inceptionGoneReplacement = "/api/sessions" +) + +// handleInceptionGone answers every former /api/inception/* route with 410 +// Gone for one release, so a script or bookmark that still calls it gets a +// pointer to Sessions instead of a bare 404. It reads nothing and changes +// nothing. +func (s *Server) handleInceptionGone(w http.ResponseWriter, _ *http.Request) { + jsonStatusResponse(w, http.StatusGone, map[string]any{ + "ok": false, + "error": inceptionGoneMessage, + "replacement": inceptionGoneReplacement, + "docs": inceptionGoneDocs, + }) +} diff --git a/src/pkg/dashboard/inception_gone_test.go b/src/pkg/dashboard/inception_gone_test.go new file mode 100644 index 0000000000..c4cb41aa4a --- /dev/null +++ b/src/pkg/dashboard/inception_gone_test.go @@ -0,0 +1,45 @@ +package dashboard + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +// Every former /api/inception/* route answers 410 Gone and points to +// Inception (spek) sessions (the inception API was retired). +func TestInceptionRoutesAnswerGone(t *testing.T) { + s := covApiServer(t) + for _, c := range []struct{ method, path string }{ + {http.MethodPost, "/api/inception/start"}, + {http.MethodPost, "/api/inception/scan"}, + {http.MethodGet, "/api/inception/state"}, + {http.MethodPost, "/api/inception/questions"}, + {http.MethodPost, "/api/inception/answer"}, + {http.MethodPost, "/api/inception/facts"}, + {http.MethodGet, "/api/inception/scaffold"}, + {http.MethodPost, "/api/inception/approve"}, + {http.MethodPost, "/api/inception/reset"}, + {http.MethodGet, "/api/inception/ideation-facts"}, + {http.MethodGet, "/api/inception/download"}, + {http.MethodGet, "/api/inception/has-files"}, + {http.MethodPut, "/api/inception/wiki-name"}, + {http.MethodPost, "/api/inception/import"}, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest(c.method, c.path, nil) + markOwnerRequest(req) + s.mux.ServeHTTP(rec, req) + if rec.Code != http.StatusGone { + t.Fatalf("%s %s = %d, want 410", c.method, c.path, rec.Code) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("%s %s body: %v", c.method, c.path, err) + } + if body["error"] != inceptionGoneMessage || body["replacement"] != inceptionGoneReplacement || body["docs"] != inceptionGoneDocs { + t.Fatalf("%s %s body = %v", c.method, c.path, body) + } + } +} diff --git a/src/pkg/dashboard/inception_handlers.go b/src/pkg/dashboard/inception_handlers.go deleted file mode 100644 index 4a2279aa1a..0000000000 --- a/src/pkg/dashboard/inception_handlers.go +++ /dev/null @@ -1,830 +0,0 @@ -package dashboard - -import ( - "archive/zip" - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/fleetreport" - "github.com/hivecommons/hive/pkg/knowledge" -) - -const maxInceptionBodyBytes = 64 * 1024 - -func (s *Server) handleInceptionStart(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var req struct { - Idea string `json:"idea"` - Force bool `json:"force,omitempty"` - } - if err := readJSON(r, &req); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - if req.Force { - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - _ = s.deps.Inception.Reset() - // Don't kill the session — kickBrainstorm will SendKick to the - // running agent, which is faster than kill+restart. Killing a - // busy session causes the next RestartWithBootstrap to race - // with shell initialization, producing the alternating pattern. - if s.deps.AgentMgr != nil { - _ = s.deps.AgentMgr.Pause("brainstorm", "inception-force-reset", "forced reset before new inception") - } - if store, ok := s.deps.BeadStores["brainstorm"]; ok { - s.clearInceptionBeads(store) - } - } else if state := s.deps.Inception.GetState(); state != nil && state.Phase == knowledge.PhaseComplete { - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - } - - state, err := s.deps.Inception.Start(req.Idea) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - s.kickBrainstorm() - - s.auditFromRequest(r, "inception_start", "", "") - jsonResponse(w, map[string]interface{}{ - "ok": true, - "state": state, - }) -} - -func (s *Server) handleInceptionScan(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var req struct { - RepoURL string `json:"repo_url"` - Force bool `json:"force,omitempty"` - } - if err := readJSON(r, &req); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - if req.Force { - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - _ = s.deps.Inception.Reset() - if s.deps.AgentMgr != nil { - _ = s.deps.AgentMgr.Pause("brainstorm", "inception-force-reset", "forced reset before brownfield scan") - } - if store, ok := s.deps.BeadStores["brainstorm"]; ok { - s.clearInceptionBeads(store) - } - } else if state := s.deps.Inception.GetState(); state != nil && state.Phase == knowledge.PhaseComplete { - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - } - - state, err := s.deps.Inception.StartBrownfield(req.RepoURL) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - s.kickBrainstorm() - - s.auditFromRequest(r, "inception_scan", auditDetail("repo_url", req.RepoURL), "") - jsonResponse(w, map[string]interface{}{ - "ok": true, - "state": state, - }) -} - -func (s *Server) handleInceptionState(w http.ResponseWriter, r *http.Request) { - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - state := s.deps.Inception.GetState() - jsonResponse(w, map[string]interface{}{ - "ok": true, - "state": state, - "active": state != nil, - }) -} - -func (s *Server) handleInceptionSetQuestions(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var req struct { - Questions []knowledge.Question `json:"questions"` - } - if err := readJSON(r, &req); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - if err := s.deps.Inception.SetQuestions(req.Questions); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - s.auditFromRequest(r, "inception_set_questions", auditDetail("count", strconv.Itoa(len(req.Questions))), "") - jsonResponse(w, map[string]interface{}{"ok": true}) -} - -func (s *Server) handleInceptionAnswer(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var req struct { - Answers map[string]string `json:"answers"` - } - if err := readJSON(r, &req); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - state, err := s.deps.Inception.SubmitAnswers(req.Answers) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - // Use SendKick (not RestartWithBootstrap) for the structure-phase kick. - // The agent is already running from the capture kick — restarting it - // kills its context and can revert the phase back to capture (bug #117). - s.sendKickBrainstorm() - - s.auditFromRequest(r, "inception_answer", auditDetail("count", strconv.Itoa(len(req.Answers))), "") - jsonResponse(w, map[string]interface{}{ - "ok": true, - "state": state, - }) -} - -func (s *Server) handleInceptionRecordFacts(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var req struct { - Facts []knowledge.IdeationFact `json:"facts"` - } - if err := readJSON(r, &req); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - if err := s.deps.Inception.RecordFacts(s.deps.Ctx, req.Facts); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - s.auditFromRequest(r, "inception_record_facts", auditDetail("count", strconv.Itoa(len(req.Facts))), "") - jsonResponse(w, map[string]interface{}{"ok": true}) -} - -func (s *Server) handleInceptionScaffold(w http.ResponseWriter, r *http.Request) { - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - result, err := s.deps.Inception.ProduceScaffold(s.deps.Ctx) - if err != nil { - jsonError(w, err.Error(), http.StatusNotFound) - return - } - - jsonResponse(w, map[string]interface{}{ - "ok": true, - "scaffold": result, - }) -} - -func (s *Server) handleInceptionApprove(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - var target inceptionRunTarget - admitRun := s.deps.Config != nil && s.deps.Config.Runs.Spektacular.Enabled - if admitRun { - var err error - target, err = s.inceptionRunAdmissionTarget(r) - if err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - } - if err := s.deps.Inception.AdvanceToComplete(); err != nil { - jsonError(w, err.Error(), http.StatusBadRequest) - return - } - - if admitRun { - if target.ok { - if err := s.AdmitRun(target.repo, target.issueNumber, target.title, time.Now()); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - s.logger.Info("inception complete admitted run", - "repo", target.repo, - "issue", target.issueNumber, - ) - s.auditFromRequest(r, "inception_run_admitted", - auditDetail("repo", target.repo, "issue", strconv.Itoa(target.issueNumber)), "") - } else { - s.logger.Info("inception complete did not admit run: no issue target supplied") - } - } - - // Re-pause brainstorm so the governor doesn't kick it with generic - // messages after inception completes (which can revert the phase). - if s.deps.AgentMgr != nil { - _ = s.deps.AgentMgr.Pause("brainstorm", "inception-complete", "inception complete — on-demand only") - } - - s.auditFromRequest(r, "inception_approve", "", "") - jsonResponse(w, map[string]interface{}{"ok": true}) -} - -type inceptionRunTarget struct { - repo string - issueNumber int - title string - ok bool -} - -func (s *Server) inceptionRunAdmissionTarget(r *http.Request) (inceptionRunTarget, error) { - var req struct { - Repo string `json:"repo"` - TargetRepo string `json:"target_repo"` - IssueNumber int `json:"issue_number"` - IssueURL string `json:"issue_url"` - Title string `json:"title"` - } - if r.Body != nil { - body, err := io.ReadAll(io.LimitReader(r.Body, maxInceptionBodyBytes)) - if err != nil { - return inceptionRunTarget{}, fmt.Errorf("reading approve body: %w", err) - } - if strings.TrimSpace(string(body)) != "" { - if err := json.Unmarshal(body, &req); err != nil { - return inceptionRunTarget{}, fmt.Errorf("invalid approve body: %w", err) - } - } - } - - repo := strings.TrimSpace(req.TargetRepo) - if repo == "" { - repo = strings.TrimSpace(req.Repo) - } - issueNumber := req.IssueNumber - if strings.TrimSpace(req.IssueURL) != "" { - issueRepo, issue, err := parseGitHubIssueURL(req.IssueURL, s.deps.Config.GitHub.HostLabel()) - if err != nil { - return inceptionRunTarget{}, err - } - if repo != "" { - qualified := config.QualifyRepo(s.deps.Config.Project.Org, repo) - if !strings.EqualFold(qualified, issueRepo) { - return inceptionRunTarget{}, fmt.Errorf("repo does not match issue_url repo") - } - } - if issueNumber != 0 && issueNumber != issue { - return inceptionRunTarget{}, fmt.Errorf("issue_number does not match issue_url") - } - repo = issueRepo - issueNumber = issue - } - - state := s.deps.Inception.GetState() - if s.deps.Config != nil { - repo = config.QualifyRepo(s.deps.Config.Project.Org, repo) - } - if strings.TrimSpace(repo) == "" { - return inceptionRunTarget{}, nil - } - if issueNumber <= 0 { - return inceptionRunTarget{}, nil - } - - title := strings.TrimSpace(req.Title) - if title == "" && state != nil { - title = strings.TrimSpace(state.IdeaText) - } - if title == "" { - title = fmt.Sprintf("%s#%d", repo, issueNumber) - } - return inceptionRunTarget{repo: repo, issueNumber: issueNumber, title: title, ok: true}, nil -} - -func parseGitHubIssueURL(raw, wantHost string) (string, int, error) { - u, err := url.Parse(strings.TrimSpace(raw)) - if err != nil || u.Scheme == "" || u.Host == "" { - return "", 0, fmt.Errorf("issue_url must be an absolute GitHub issue URL") - } - if !strings.EqualFold(u.Hostname(), wantHost) { - return "", 0, fmt.Errorf("issue_url host must be %s", wantHost) - } - parts := strings.Split(strings.Trim(u.Path, "/"), "/") - if len(parts) != 4 || parts[2] != "issues" { - return "", 0, fmt.Errorf("issue_url must point to /owner/repo/issues/<number>") - } - n, err := strconv.Atoi(parts[3]) - if err != nil || n <= 0 { - return "", 0, fmt.Errorf("issue_url must include a positive issue number") - } - return parts[0] + "/" + parts[1], n, nil -} - -func (s *Server) clearInceptionBeads(store *beads.Store) { - all := store.List(beads.ListFilter{}) - closed := 0 - for _, b := range all { - if b.Status != beads.StatusOpen { - continue - } - if b.Actor == "brainstorm" || b.Actor == "inception" { - _ = store.Close(b.ID) - closed++ - } - } - if closed > 0 { - s.logger.Info("cleared inception beads on force-reset", "closed", closed) - } -} - -func (s *Server) handleInceptionReset(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - if _, err := s.deps.Inception.ArchiveCurrentCampaign(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - if err := s.deps.Inception.Reset(); err != nil { - jsonError(w, err.Error(), http.StatusInternalServerError) - return - } - - if store, ok := s.deps.BeadStores["brainstorm"]; ok { - s.clearInceptionBeads(store) - } - - if s.deps.AgentMgr != nil { - _ = s.deps.AgentMgr.Pause("brainstorm", "inception-reset", "inception reset — on-demand only") - } - - s.auditFromRequest(r, "inception_reset", "", "") - jsonResponse(w, map[string]interface{}{"ok": true}) -} - -func (s *Server) handleInceptionIdeationFacts(w http.ResponseWriter, r *http.Request) { - if s.deps.Knowledge == nil && s.deps.Inception == nil { - jsonError(w, "knowledge API not initialized", http.StatusServiceUnavailable) - return - } - - var facts []knowledge.Fact - if s.deps.Knowledge != nil { - facts = s.deps.Knowledge.ListIdeationFacts(s.deps.Ctx) - } - - if len(facts) == 0 && s.deps.Inception != nil { - facts = s.deps.Inception.GatherFactsPublic(s.deps.Ctx) - } - - if facts == nil { - facts = []knowledge.Fact{} - } - jsonResponse(w, map[string]interface{}{ - "ok": true, - "facts": facts, - }) -} - -func (s *Server) handleInceptionDownload(w http.ResponseWriter, r *http.Request) { - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - result, err := s.deps.Inception.ProduceScaffold(s.deps.Ctx) - if err != nil { - jsonError(w, err.Error(), http.StatusNotFound) - return - } - if result == nil || len(result.Files) == 0 { - jsonError(w, "no scaffold files to download", http.StatusNotFound) - return - } - - projectName := "inception-project" - state := s.deps.Inception.GetState() - if state != nil && state.IdeaSlug != "" { - slug := state.IdeaSlug - if len(slug) > 40 { - slug = slug[:40] - } - projectName = slug - } - - w.Header().Set("Content-Type", "application/zip") - safeName := strings.Map(func(r rune) rune { - if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' { - return r - } - return '-' - }, projectName) - w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.zip"`, safeName)) - - zw := zip.NewWriter(w) - defer func() { - if err := zw.Close(); err != nil { - s.logger.Warn("inception scaffold archive close failed", "error", err) - } - }() - - for _, f := range result.Files { - clean := filepath.Clean(f.Path) - if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) { - continue - } - fw, err := zw.Create(filepath.ToSlash(clean)) - if err != nil { - s.logger.Warn("inception scaffold archive entry creation failed", "path", clean, "error", err) - continue - } - if _, err := fw.Write([]byte(f.Content)); err != nil { - s.logger.Warn("inception scaffold archive write failed", "path", clean, "error", err) - return - } - } -} - -func (s *Server) handleInceptionHasFiles(w http.ResponseWriter, r *http.Request) { - if s.deps.Inception == nil { - jsonResponse(w, map[string]interface{}{"ok": true, "has_files": false}) - return - } - hasFiles := s.deps.Inception.HasWikiFiles() - jsonResponse(w, map[string]interface{}{"ok": true, "has_files": hasFiles}) -} - -const maxWikiNameLen = 80 - -func (s *Server) handleInceptionRenameWiki(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - var req struct { - Name string `json:"name"` - } - if err := readJSON(r, &req); err != nil || req.Name == "" { - jsonError(w, "name is required", http.StatusBadRequest) - return - } - if len(req.Name) > maxWikiNameLen { - jsonError(w, fmt.Sprintf("name must be %d characters or fewer", maxWikiNameLen), http.StatusBadRequest) - return - } - if s.deps.Knowledge == nil || s.deps.Inception == nil { - jsonError(w, "knowledge or inception not initialized", http.StatusServiceUnavailable) - return - } - store := s.deps.Knowledge.GetVaultStore(s.deps.Inception.WikiDir()) - if store == nil { - jsonError(w, "inception wiki vault not found", http.StatusNotFound) - return - } - store.SetName(req.Name) - - // Persist the name in inception state - if state := s.deps.Inception.GetState(); state != nil { - s.deps.Inception.SetWikiName(req.Name) - } - - s.auditFromRequest(r, "inception_rename_wiki", auditDetail("name", req.Name), "") - s.logger.Info("inception wiki renamed", "name", req.Name) - jsonResponse(w, map[string]interface{}{"ok": true, "name": req.Name}) -} - -func (s *Server) handleInceptionImport(w http.ResponseWriter, r *http.Request) { - if !requireOwnerRole(w, r) { - return - } - - if s.deps.Inception == nil { - jsonError(w, "inception engine not initialized", http.StatusServiceUnavailable) - return - } - - const maxZipUploadBytes = 10 << 20 // 10 MiB - r.Body = http.MaxBytesReader(w, r.Body, maxZipUploadBytes) - - file, _, err := r.FormFile("file") - if err != nil { - jsonError(w, "file upload required", http.StatusBadRequest) - return - } - defer func() { _ = file.Close() }() - - data, err := io.ReadAll(file) - if err != nil { - jsonError(w, "failed to read upload", http.StatusBadRequest) - return - } - - zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) - if err != nil { - jsonError(w, "invalid zip file", http.StatusBadRequest) - return - } - - wikiDir := s.deps.Inception.WikiDir() - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - jsonError(w, "failed to create wiki directory", http.StatusInternalServerError) - return - } - - imported := 0 - for _, f := range zr.File { - if f.FileInfo().IsDir() { - continue - } - // Normalize backslash paths (zip files from Windows use \) - cleanName := strings.ReplaceAll(f.Name, "\\", "/") - baseName := filepath.Base(cleanName) - if strings.Contains(baseName, "..") || !strings.HasSuffix(baseName, ".md") { - continue - } - const maxFileBytes = 1 << 20 // 1 MiB per file - rc, err := f.Open() - if err != nil { - continue - } - content, readErr := io.ReadAll(io.LimitReader(rc, maxFileBytes)) - closeErr := rc.Close() - if readErr != nil || closeErr != nil { - s.logger.Warn("inception wiki archive entry read failed", "file", baseName, "read_error", readErr, "close_error", closeErr) - continue - } - - outPath := filepath.Join(wikiDir, baseName) - if err := os.WriteFile(outPath, content, 0o644); err != nil { - continue - } - imported++ - } - - // Reconnect vault to pick up imported files - if s.deps.Knowledge != nil { - if err := s.deps.Knowledge.ConnectVault(wikiDir, "inception-wiki"); err != nil { - s.logger.Warn("inception wiki vault reconnect failed", "error", err) - jsonError(w, "files imported but reconnecting the wiki vault failed", http.StatusInternalServerError) - return - } - if store := s.deps.Knowledge.GetVaultStore(wikiDir); store != nil { - store.Reindex() - } - } - - s.logger.Info("inception wiki imported", "files", imported) - jsonResponse(w, map[string]interface{}{"ok": true, "imported": imported}) -} - -func (s *Server) kickBrainstorm() { - if s.deps.AgentMgr == nil || s.deps.Scheduler == nil { - return - } - - // Guard: only kick if inception is in a phase that needs the agent. - // Kicking during scaffold/complete is harmful — it restarts the agent - // and can revert the phase back to capture. - if s.deps.Inception != nil { - state := s.deps.Inception.GetState() - if state != nil && (state.Phase == knowledge.PhaseScaffold || state.Phase == knowledge.PhaseComplete) { - s.logger.Debug("skipping brainstorm kick — inception already past structure", - "phase", state.Phase) - return - } - } - - // Unpause brainstorm if it was paused (e.g., by a force-reset that - // preceded this start). Without this, the governor re-pauses the - // agent on its next eval cycle and the inception stalls in capture. - if s.deps.AgentMgr != nil { - _ = s.deps.AgentMgr.Resume(s.deps.Ctx, "brainstorm", "inception-start", "inception started — agent needed") - } - - go func() { - if s.kickBrainstormDoneFn != nil { - defer s.kickBrainstormDoneFn() - } - defer func() { - if r := recover(); r != nil { - s.logger.Error("panic in kickBrainstorm — recovered", "panic", r) - fleetreport.Observe(fleetreport.ClassPanicRecovered, "kickBrainstorm", fmt.Sprintf("panic in kickBrainstorm: %v", r), "") - } - }() - - msg := s.deps.Scheduler.BuildAgentMessage("brainstorm", nil, s.deps.Scheduler.GetLastActionable()) - - // Try SendKick to the running session — send /clear first to - // reset CLI context, then the inception prompt. No restart needed. - // This avoids the shell initialization race that causes the - // alternating responsive/unresponsive pattern. - clearErr := s.sendBrainstormKick("brainstorm", "/clear") - if clearErr == nil { - time.Sleep(kickBrainstormClearDelay) - if err := s.sendBrainstormKick("brainstorm", msg); err != nil { - s.logger.Warn("SendKick after /clear failed, trying RestartWithBootstrap", "error", err) - if err2 := s.restartBrainstormWithBootstrap(s.deps.Ctx, "brainstorm", msg); err2 != nil { - s.logger.Warn("failed to restart brainstorm for inception", "error", err2) - } - } else { - s.logger.Info("inception kick sent via /clear + SendKick") - } - } else { - // No running session — use RestartWithBootstrap - s.logger.Debug("no running session, using RestartWithBootstrap", "error", clearErr) - if err := s.restartBrainstormWithBootstrap(s.deps.Ctx, "brainstorm", msg); err != nil { - s.logger.Warn("failed to restart brainstorm for inception", "error", err) - } - } - - if s.deps.Governor != nil { - s.deps.Governor.RecordKick("brainstorm") - } - }() -} - -var kickBrainstormClearDelay = time.Second - -func (s *Server) sendBrainstormKick(name, msg string) error { - if s.kickBrainstormSendKickFn != nil { - return s.kickBrainstormSendKickFn(name, msg) - } - return s.deps.AgentMgr.SendKick(name, msg) -} - -func (s *Server) restartBrainstormWithBootstrap(ctx context.Context, name, prompt string) error { - if s.kickBrainstormRestartFn != nil { - return s.kickBrainstormRestartFn(ctx, name, prompt) - } - return s.deps.AgentMgr.RestartWithBootstrap(ctx, name, prompt) -} - -// sendKickBrainstorm sends an inception-specific prompt to the RUNNING -// brainstorm agent via SendKick (no restart). Includes the user's Q&A -// so the agent knows to extract facts and create fact beads. -func (s *Server) sendKickBrainstorm() { - if s.deps.AgentMgr == nil || s.deps.Inception == nil { - return - } - go func() { - defer func() { - if r := recover(); r != nil { - s.logger.Error("panic in sendKickBrainstorm — recovered", "panic", r) - fleetreport.Observe(fleetreport.ClassPanicRecovered, "sendKickBrainstorm", fmt.Sprintf("panic in sendKickBrainstorm: %v", r), "") - } - }() - - state := s.deps.Inception.GetState() - if state == nil { - return - } - - msg := s.buildStructureKickMessage(state) - if err := s.deps.AgentMgr.SendKick("brainstorm", msg); err != nil { - s.logger.Warn("sendKick for structure phase failed, trying pluk send", "error", err) - if err2 := plukSendKick("brainstorm", msg); err2 != nil { - s.logger.Warn("pluk send also failed", "error", err2) - } - } - - if s.deps.Governor != nil { - s.deps.Governor.RecordKick("brainstorm") - } - }() -} - -func (s *Server) buildStructureKickMessage(state *knowledge.InceptionState) string { - var sb strings.Builder - sb.WriteString(fmt.Sprintf("INCEPTION TASK: Structure phase for idea: %q\n", state.IdeaText)) - sb.WriteString("The user answered your clarification questions. Create fact beads NOW.\n\n") - for _, q := range state.Questions { - ans := state.Answers[q.ID] - if ans != "" { - sb.WriteString(fmt.Sprintf("Q: %s\nA: %s\n\n", q.Text, ans)) - } - } - sb.WriteString("Create at least 3 fact beads. For EACH fact, run:\n\n") - sb.WriteString(fmt.Sprintf("bd create --title \"<fact title>\" --type advisory --priority 1 --actor brainstorm --external-ref \"inception/%s\"\n", state.IdeaSlug)) - sb.WriteString("bd update <bead-id> --set-metadata fact_type=\"<vision|constitution|requirement|constraint|stakeholder|acceptance>\"\n") - sb.WriteString("bd update <bead-id> --set-metadata fact_body=\"<detailed fact content>\"\n\n") - sb.WriteString("Required facts: 1 vision, 1 constitution, 2+ requirements. Start creating beads IMMEDIATELY.") - return sb.String() -} - -// plukSendKick sends the inception prompt via pluk's send subcommand. -// This is more reliable than tmux send-keys + $(cat file) because pluk send -// writes to a named FIFO and confirms delivery via a command_received event. -// Returns error if pluk is not installed or the send fails. -func plukSendKick(session, message string) error { - plukPath, err := exec.LookPath("pluk") - if err != nil { - return fmt.Errorf("pluk not found: %w", err) - } - - cmd := exec.Command(plukPath, - "send", "hive-"+session, - "--text="+message, - "--enter", - ) - if out, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf("pluk send failed: %w (output: %s)", err, string(out)) - } - - return nil -} - -func readJSON(r *http.Request, v interface{}) error { - body, err := io.ReadAll(io.LimitReader(r.Body, maxInceptionBodyBytes+1)) - if err != nil { - return err - } - defer closeHTTPBody(r.Body) - if int64(len(body)) > maxInceptionBodyBytes { - return fmt.Errorf("request body exceeds %d bytes", maxInceptionBodyBytes) - } - return json.Unmarshal(body, v) -} diff --git a/src/pkg/dashboard/inception_handlers_coverage_test.go b/src/pkg/dashboard/inception_handlers_coverage_test.go deleted file mode 100644 index cf1c84d43a..0000000000 --- a/src/pkg/dashboard/inception_handlers_coverage_test.go +++ /dev/null @@ -1,321 +0,0 @@ -package dashboard - -import ( - "archive/zip" - "bytes" - "context" - "io" - "log/slog" - "mime/multipart" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// covFInceptionServer builds a dashboard Server wired with a real inception -// engine + knowledge API so the inception handlers exercise their rich paths -// (the state machine), not just the "engine not initialized" 503 branch that -// existing tests already cover. -func covFInceptionServer(t *testing.T) (*Server, *knowledge.InceptionEngine, *knowledge.KnowledgeAPI) { - t.Helper() - logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})) - kapi := knowledge.NewKnowledgeAPI(nil, knowledge.KnowledgeConfig{}, logger) - eng := knowledge.NewInceptionEngine(t.TempDir(), kapi, logger) - - s := NewServer(0, logger) - deps := testDeps(t) - deps.Inception = eng - deps.Knowledge = kapi - s.RegisterAPI(deps) - return s, eng, kapi -} - -func TestCovF_InceptionFullLifecycle(t *testing.T) { - s, eng, _ := covFInceptionServer(t) - - // 1. start - rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "build a todo app in Go"}) - if rec.Code != http.StatusOK { - t.Fatalf("start: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - if body := decodeJSON(t, rec); body["ok"] != true { - t.Fatalf("start: ok not true: %v", body) - } - - // 2. state — active - rec = doGet(s, "/api/inception/state") - if rec.Code != http.StatusOK { - t.Fatalf("state: expected 200, got %d", rec.Code) - } - if body := decodeJSON(t, rec); body["active"] != true { - t.Fatalf("state: expected active true: %v", body) - } - - // 3. questions (must be in capture phase) — need >=1 valid question. - qs := []knowledge.Question{ - {ID: "language", Text: "What language?", Category: "language"}, - {ID: "users", Text: "Who are the users?", Category: "users"}, - } - rec = doPost(s, "/api/inception/questions", map[string]interface{}{"questions": qs}) - if rec.Code != http.StatusOK { - t.Fatalf("questions: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - // 4. answer — advances to structure; spawns sendKickBrainstorm goroutine. - rec = doPost(s, "/api/inception/answer", map[string]interface{}{"answers": map[string]string{"language": "Go", "users": "devs"}}) - if rec.Code != http.StatusOK { - t.Fatalf("answer: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - time.Sleep(80 * time.Millisecond) // let the kick goroutine run for coverage - - // 5. record facts — advances to scaffold. - facts := []knowledge.IdeationFact{ - {Title: "Project Vision", Body: "A simple todo app", Type: knowledge.FactVision}, - {Title: "Go stdlib", Body: "Use Go standard library", Type: knowledge.FactConstitution}, - {Title: "Add tasks", Body: "Users can add tasks", Type: knowledge.FactRequirement}, - } - rec = doPost(s, "/api/inception/facts", map[string]interface{}{"facts": facts}) - if rec.Code != http.StatusOK { - t.Fatalf("facts: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - // 6. scaffold — should produce files now that facts exist. - rec = doGet(s, "/api/inception/scaffold") - if rec.Code != http.StatusOK { - t.Fatalf("scaffold: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - // 7. download — zip stream. - rec = doGet(s, "/api/inception/download") - if rec.Code != http.StatusOK { - t.Fatalf("download: expected 200, got %d", rec.Code) - } - if ct := rec.Header().Get("Content-Type"); ct != "application/zip" { - t.Fatalf("download: expected application/zip, got %q", ct) - } - - // 8. has-files + ideation-facts - rec = doGet(s, "/api/inception/has-files") - if rec.Code != http.StatusOK { - t.Fatalf("has-files: expected 200, got %d", rec.Code) - } - rec = doGet(s, "/api/inception/ideation-facts") - if rec.Code != http.StatusOK { - t.Fatalf("ideation-facts: expected 200, got %d", rec.Code) - } - - // 9. approve — from scaffold phase -> complete. - rec = doPost(s, "/api/inception/approve", map[string]interface{}{}) - if rec.Code != http.StatusOK { - t.Fatalf("approve: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - - _ = eng -} - -func TestCovF_InceptionRenameWiki(t *testing.T) { - s, _, _ := covFInceptionServer(t) - - // Start so there's state + a wiki vault the store can be found under. - if rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "a rename test idea"}); rec.Code != http.StatusOK { - t.Fatalf("start: %d", rec.Code) - } - - // empty name -> 400 - if rec := doPut(s, "/api/inception/wiki-name", map[string]interface{}{"name": ""}); rec.Code != http.StatusBadRequest { - t.Fatalf("rename empty: expected 400, got %d", rec.Code) - } - // too-long name -> 400 - long := strings.Repeat("x", maxWikiNameLen+1) - if rec := doPut(s, "/api/inception/wiki-name", map[string]interface{}{"name": long}); rec.Code != http.StatusBadRequest { - t.Fatalf("rename long: expected 400, got %d", rec.Code) - } - // valid name — the vault store may or may not exist yet (no facts written), - // so accept either 200 (renamed) or 404 (vault not found). Both are covered - // branches of the handler. - rec := doPut(s, "/api/inception/wiki-name", map[string]interface{}{"name": "My Wiki"}) - if rec.Code != http.StatusOK && rec.Code != http.StatusNotFound { - t.Fatalf("rename valid: expected 200 or 404, got %d body=%s", rec.Code, rec.Body.String()) - } -} - -func TestCovF_InceptionImport(t *testing.T) { - s, _, _ := covFInceptionServer(t) - - // no file -> 400 - rec := doPost(s, "/api/inception/import", nil) - if rec.Code != http.StatusBadRequest { - t.Fatalf("import no-file: expected 400, got %d", rec.Code) - } - - // Build a multipart form containing a small .zip with a foo.md file. - var zbuf bytes.Buffer - zw := zip.NewWriter(&zbuf) - fw, err := zw.Create("foo.md") - if err != nil { - t.Fatalf("zip create: %v", err) - } - fw.Write([]byte("# Foo\n\nsome content")) - // A non-.md file should be skipped by the handler. - if nfw, err := zw.Create("ignore.txt"); err == nil { - nfw.Write([]byte("nope")) - } - zw.Close() - - var body bytes.Buffer - mw := multipart.NewWriter(&body) - part, err := mw.CreateFormFile("file", "wiki.zip") - if err != nil { - t.Fatalf("form file: %v", err) - } - part.Write(zbuf.Bytes()) - mw.Close() - - req := httptest.NewRequest(http.MethodPost, "/api/inception/import", &body) - req.Header.Set("Content-Type", mw.FormDataContentType()) - wrec := httptest.NewRecorder() - markOwnerRequest(req) - s.mux.ServeHTTP(wrec, req) - if wrec.Code != http.StatusOK { - t.Fatalf("import: expected 200, got %d body=%s", wrec.Code, wrec.Body.String()) - } -} - -func TestCovF_InceptionForceResetBranch(t *testing.T) { - s, _, _ := covFInceptionServer(t) - - // First start. - if rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "first idea here"}); rec.Code != http.StatusOK { - t.Fatalf("start1: %d", rec.Code) - } - // Reset explicitly. - if rec := doPost(s, "/api/inception/reset", map[string]interface{}{}); rec.Code != http.StatusOK { - t.Fatalf("reset: %d body=%s", rec.Code, rec.Body.String()) - } - // Start again with force:true — exercises the force-reset branch - // (Reset + AgentMgr.Pause; BeadStores is empty so clearInceptionBeads is skipped). - rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "second idea here", "force": true}) - if rec.Code != http.StatusOK { - t.Fatalf("start2 force: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - time.Sleep(80 * time.Millisecond) // let kickBrainstorm goroutine run -} - -func TestCovF_InceptionScanBadURL(t *testing.T) { - s, _, _ := covFInceptionServer(t) - // StartBrownfield rejects a non-http URL -> 400. - rec := doPost(s, "/api/inception/scan", map[string]interface{}{"repo_url": "not-a-url"}) - if rec.Code != http.StatusBadRequest { - t.Fatalf("scan bad url: expected 400, got %d", rec.Code) - } - // Valid https URL -> 200 (capture phase). - rec = doPost(s, "/api/inception/scan", map[string]interface{}{"repo_url": "https://github.com/example/repo"}) - if rec.Code != http.StatusOK { - t.Fatalf("scan valid: expected 200, got %d body=%s", rec.Code, rec.Body.String()) - } - time.Sleep(80 * time.Millisecond) -} - -func TestCovF_InceptionBadBodies(t *testing.T) { - s, _, _ := covFInceptionServer(t) - - // Malformed JSON body on start -> 400 from readJSON. - req := httptest.NewRequest(http.MethodPost, "/api/inception/start", strings.NewReader("{not json")) - req.Header.Set("Content-Type", "application/json") - rec := httptest.NewRecorder() - markOwnerRequest(req) - s.mux.ServeHTTP(rec, req) - if rec.Code != http.StatusBadRequest { - t.Fatalf("start bad json: expected 400, got %d", rec.Code) - } - - // Empty idea -> Start returns error -> 400. - rec = doPost(s, "/api/inception/start", map[string]interface{}{"idea": ""}) - if rec.Code != http.StatusBadRequest { - t.Fatalf("start empty idea: expected 400, got %d", rec.Code) - } - - // questions with none in progress → after a fresh start we're in capture, - // but submitting an empty question list -> 400. - if rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "another valid idea"}); rec.Code != http.StatusOK { - t.Fatalf("start for empty-questions: %d", rec.Code) - } - rec = doPost(s, "/api/inception/questions", map[string]interface{}{"questions": []knowledge.Question{}}) - if rec.Code != http.StatusBadRequest { - t.Fatalf("empty questions: expected 400, got %d", rec.Code) - } -} - -func TestCovF_ReadJSONLimits(t *testing.T) { - // Valid body decodes. - var out struct { - A string `json:"a"` - } - r := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(`{"a":"hi"}`)) - if err := readJSON(r, &out); err != nil || out.A != "hi" { - t.Fatalf("readJSON valid: err=%v out=%v", err, out) - } - - // Oversized body -> error. - big := strings.Repeat("a", maxInceptionBodyBytes+10) - r2 := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(`{"a":"`+big+`"}`)) - if err := readJSON(r2, &out); err == nil { - t.Fatalf("readJSON oversized: expected error") - } -} - -func TestCovF_BuildStructureKickMessage(t *testing.T) { - s := &Server{} - state := &knowledge.InceptionState{ - IdeaText: "cool idea", - IdeaSlug: "cool-idea", - Questions: []knowledge.Question{ - {ID: "q1", Text: "What lang?"}, - }, - Answers: map[string]string{"q1": "Go"}, - } - msg := s.buildStructureKickMessage(state) - if !strings.Contains(msg, "cool idea") || !strings.Contains(msg, "What lang?") { - t.Fatalf("structure kick message missing content: %q", msg) - } -} - -func TestCovF_KickBrainstorm(t *testing.T) { - s, _, _ := covFInceptionServer(t) - // Start so state exists in capture phase. - if rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "kick test idea"}); rec.Code != http.StatusOK { - t.Fatalf("start: %d", rec.Code) - } - // Directly invoke kickBrainstorm — guarded by AgentMgr+Scheduler (both set - // by testDeps). The goroutine's SendKick will fail harmlessly (no session). - s.kickBrainstorm() - s.sendKickBrainstorm() - time.Sleep(100 * time.Millisecond) -} - -func TestCovF_PlukSendKickNotInstalled(t *testing.T) { - // pluk is not installed in the test environment -> LookPath fails. - if err := plukSendKick("brainstorm", "hello"); err == nil { - t.Fatalf("expected pluk not found error") - } -} - -func TestCovF_KickBrainstormPastStructureSkips(t *testing.T) { - s, eng, _ := covFInceptionServer(t) - // Drive to scaffold phase, then kickBrainstorm should skip (past structure). - doPost(s, "/api/inception/start", map[string]interface{}{"idea": "skip test idea in go"}) - doPost(s, "/api/inception/questions", map[string]interface{}{"questions": []knowledge.Question{{ID: "language", Text: "lang?", Category: "language"}}}) - doPost(s, "/api/inception/answer", map[string]interface{}{"answers": map[string]string{"language": "Go"}}) - _ = eng.RecordFacts(context.Background(), []knowledge.IdeationFact{ - {Title: "Vision", Body: "v", Type: knowledge.FactVision}, - {Title: "Const", Body: "c", Type: knowledge.FactConstitution}, - {Title: "Req", Body: "r", Type: knowledge.FactRequirement}, - }) - // Now in scaffold — kick should hit the "skip" guard. - s.kickBrainstorm() - time.Sleep(50 * time.Millisecond) -} diff --git a/src/pkg/dashboard/inception_parser_pin_test.go b/src/pkg/dashboard/inception_parser_pin_test.go deleted file mode 100644 index 4cfef1b57b..0000000000 --- a/src/pkg/dashboard/inception_parser_pin_test.go +++ /dev/null @@ -1,223 +0,0 @@ -package dashboard - -import ( - "log/slog" - "testing" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// This file "pins" the current behavior of the inception output parsers -// (parseQuestionTable, parseNumberedQuestions, parseQuestionFromBdCreate, and -// isTemplatePlaceholder) BEFORE they are lifted into the shared pkg/agentparse -// package. The lift-and-generalize refactor must keep every assertion below -// green, guaranteeing Level-1 ideation parsing is unchanged. - -func TestPin_ParseQuestionTable_FullTable(t *testing.T) { - lines := []string{ - "┌──────────┬──────────────────────────────┬─────────────┐", - "│ Category │ Question │ Default │", - "├──────────┼──────────────────────────────┼─────────────┤", - "│ language │ What language will you use? │ Go │", - "│ users │ Who are the primary users? │ developers │", - "│ features │ What must it do? │ │", - "└──────────┴──────────────────────────────┴─────────────┘", - } - got := parseQuestionTable(lines) - if len(got) != 3 { - t.Fatalf("want 3 questions, got %d: %+v", len(got), got) - } - want := []knowledge.Question{ - {ID: "language", Text: "What language will you use?", Default: "Go", Category: "language"}, - {ID: "users", Text: "Who are the primary users?", Default: "developers", Category: "users"}, - {ID: "features", Text: "What must it do?", Default: "", Category: "features"}, - } - for i, w := range want { - if got[i] != w { - t.Errorf("q[%d] = %+v, want %+v", i, got[i], w) - } - } -} - -func TestPin_ParseQuestionTable_BeadColumnLayout(t *testing.T) { - // The category is found dynamically regardless of the leading column. - lines := []string{ - "│ 1 │ storage │ Where do we persist state? │ local disk │", - "│ 2 │ testing │ How do we verify? │ unit tests │", - } - got := parseQuestionTable(lines) - if len(got) != 2 { - t.Fatalf("want 2, got %d: %+v", len(got), got) - } - if got[0].Category != "storage" || got[0].Text != "Where do we persist state?" || got[0].Default != "local disk" { - t.Errorf("q0 = %+v", got[0]) - } - if got[1].Category != "testing" { - t.Errorf("q1 category = %q", got[1].Category) - } -} - -func TestPin_ParseQuestionTable_ContinuationRow(t *testing.T) { - lines := []string{ - "│ features │ What must it │ nothing │", - "│ │ absolutely do │ special │", - } - got := parseQuestionTable(lines) - if len(got) != 1 { - t.Fatalf("want 1 merged question, got %d: %+v", len(got), got) - } - if got[0].Text != "What must it absolutely do" { - t.Errorf("continuation text = %q", got[0].Text) - } - if got[0].Default != "nothing special" { - t.Errorf("continuation default = %q", got[0].Default) - } -} - -func TestPin_ParseQuestionTable_EmptyAndNoPipes(t *testing.T) { - if got := parseQuestionTable(nil); len(got) != 0 { - t.Errorf("nil -> %d", len(got)) - } - if got := parseQuestionTable([]string{"regular text", "no table"}); len(got) != 0 { - t.Errorf("no-pipes -> %d", len(got)) - } -} - -func TestPin_ParseQuestionTable_Dedup(t *testing.T) { - lines := []string{ - "│ language │ What language? │ Go │", - "│ language │ What language? │ Go │", - } - if got := parseQuestionTable(lines); len(got) != 1 { - t.Errorf("dedup -> %d", len(got)) - } -} - -func TestPin_ParseNumberedQuestions_Numbered(t *testing.T) { - lines := []string{ - "1. Primary users — who will use this and how?", - "2. Must-have features — the 2-3 things it must do", - "3. Language — what programming language?", - "This is not a question", - "4. Testing — how should we verify it works?", - } - got := parseNumberedQuestions(lines) - if len(got) != 4 { - t.Fatalf("want 4, got %d: %+v", len(got), got) - } - // Category inference from the captured label. Note the regex captures the - // label up to the first non-\w/\s char, so "Must-have features" captures - // only "must" (-> general) and the question text keeps "have features ...". - if got[0].Category != "users" { - t.Errorf("q0 category = %q, want users", got[0].Category) - } - if got[0].Text != "who will use this and how?" { - t.Errorf("q0 text = %q", got[0].Text) - } - if got[1].Category != "general" { - t.Errorf("q1 category = %q, want general (label captured as 'must')", got[1].Category) - } - if got[1].Text != "have features — the 2-3 things it must do" { - t.Errorf("q1 text = %q", got[1].Text) - } - if got[2].Category != "language" { - t.Errorf("q2 category = %q, want language", got[2].Category) - } - if got[3].Category != "testing" { - t.Errorf("q3 category = %q, want testing", got[3].Category) - } -} - -func TestPin_ParseNumberedQuestions_Bullets(t *testing.T) { - lines := []string{ - "- Primary users: who will use this?", - "* Language: what language?", - } - got := parseNumberedQuestions(lines) - if len(got) != 2 { - t.Fatalf("want 2, got %d: %+v", len(got), got) - } -} - -func TestPin_ParseNumberedQuestions_Bold(t *testing.T) { - lines := []string{ - "1. **Primary users** — who will use this?", - "2. **Features** — what must it do?", - } - got := parseNumberedQuestions(lines) - if len(got) != 2 { - t.Fatalf("want 2, got %d: %+v", len(got), got) - } - if got[0].Category != "users" { - t.Errorf("q0 category = %q", got[0].Category) - } -} - -func TestPin_ParseNumberedQuestions_UnknownLabelGeneral(t *testing.T) { - lines := []string{"1. Timeline — when must it ship?"} - got := parseNumberedQuestions(lines) - if len(got) != 1 || got[0].Category != "general" { - t.Fatalf("unknown label -> %+v", got) - } -} - -func TestPin_ParseNumberedQuestions_EmptyAndDedup(t *testing.T) { - if got := parseNumberedQuestions(nil); len(got) != 0 { - t.Errorf("nil -> %d", len(got)) - } - dup := []string{"1. Users — who uses this?", "2. Users — who uses this?"} - if got := parseNumberedQuestions(dup); len(got) != 1 { - t.Errorf("dedup -> %d", len(got)) - } -} - -func TestPin_ParseQuestionFromBdCreate(t *testing.T) { - w := &InceptionWatcher{logger: slog.Default()} - - q := w.parseQuestionFromBdCreate(`bd create --title "What database should we use?" --type advisory`) - if q == nil || q.Text != "What database should we use?" { - t.Fatalf("basic -> %+v", q) - } - - q = w.parseQuestionFromBdCreate(`bd create --title "Who are the primary users?" --actor brainstorm`) - if q == nil || q.Category != "users" { - t.Fatalf("users category -> %+v", q) - } - - q = w.parseQuestionFromBdCreate(`bd create --title "Clarification: What language?"`) - if q == nil || q.Text != "What language?" { - t.Fatalf("clarification strip -> %+v", q) - } - if q.Category != "language" { - t.Errorf("language category -> %q", q.Category) - } - if q.Default != "Yes, use best practices" { - t.Errorf("default -> %q", q.Default) - } - - if got := w.parseQuestionFromBdCreate(`bd create --type advisory`); got != nil { - t.Errorf("no title -> %+v", got) - } - if got := w.parseQuestionFromBdCreate(`bd create --title "<fact title>"`); got != nil { - t.Errorf("placeholder -> %+v", got) - } - if got := w.parseQuestionFromBdCreate(`bd create --title ""`); got != nil { - t.Errorf("empty title -> %+v", got) - } -} - -func TestPin_IsTemplatePlaceholder(t *testing.T) { - cases := map[string]bool{ - "<fact title>": true, - "<question title>": true, - "<anything angled>": true, - "your question here": true, - "What database to use?": false, - "Primary users": false, - } - for in, want := range cases { - if got := isTemplatePlaceholder(in); got != want { - t.Errorf("isTemplatePlaceholder(%q) = %v, want %v", in, got, want) - } - } -} diff --git a/src/pkg/dashboard/inception_question_placeholder_test.go b/src/pkg/dashboard/inception_question_placeholder_test.go deleted file mode 100644 index d6d82dee81..0000000000 --- a/src/pkg/dashboard/inception_question_placeholder_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package dashboard - -import ( - "fmt" - "os" - "strings" - "testing" - - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func TestInceptionQuestionsRejectKickTemplate(t *testing.T) { - template, err := os.ReadFile("../policies/defaults/brainstorm-advisory.md") - if err != nil { - t.Fatal(err) - } - capture := strings.Split(string(template), "### If phase is `clarify`")[0] - if got := parseQuestionTable(strings.Split(capture, "\n")); len(got) != 0 { - t.Fatalf("echoed kick produced questions: %+v", got) - } -} - -func TestInceptionQuestionParsersSkipPlaceholders(t *testing.T) { - w, _, _ := covFWatcher(t) - for _, text := range []string{ - "<question text>", - "<question text> This table format is REQUIRED — the inception engine parses it to detect questions. Use", - "Clarification: <question text>", - "clarification: <question title>", - " YOUR QUESTION HERE ", - " ", - } { - t.Run(text, func(t *testing.T) { - if q := w.parseQuestionFromBdCreate(fmt.Sprintf(`bd create --title %q`, text)); q != nil { - t.Errorf("command placeholder accepted: %+v", q) - } - table := []string{"│ 1 │ users │ " + text + " │ <default value> │", "│ 2 │ users │ Who will use the issue classifier? │ triagers │"} - got := parseQuestionTable(table) - if len(got) != 1 || got[0].Text != "Who will use the issue classifier?" { - t.Errorf("table questions = %+v", got) - } - numbered := []string{"1. Users — " + text, "2. Users — Who will use the issue classifier?"} - got = parseNumberedQuestions(numbered) - if len(got) != 1 || got[0].Text != "Who will use the issue classifier?" { - t.Errorf("numbered questions = %+v", got) - } - }) - } -} - -func TestInceptionPlaceholderQuestionsDoNotAdvance(t *testing.T) { - for _, source := range []string{"beads", "pluk"} { - t.Run(source, func(t *testing.T) { - w, eng, _ := covFWatcher(t) - state, err := eng.Start("an agent that categorises GitHub issues") - if err != nil { - t.Fatal(err) - } - var questionBeads []*beads.Bead - for i := 0; i < minQuestionsForAdvance; i++ { - // Distinct text prevents deduplication from masking missing validation. - text := fmt.Sprintf("<question text> instruction %d", i) - questionBeads = append(questionBeads, &beads.Bead{Title: "Clarification: " + text}) - w.plukQuestions = append(w.plukQuestions, knowledge.Question{ID: fmt.Sprint(i), Text: text, Category: "general"}) - } - if source == "beads" { - w.checkForQuestions(questionBeads) - } else { - w.applyPlukQuestions(state) - } - if got := eng.GetState(); got.Phase != knowledge.PhaseCapture || len(got.Questions) != 0 { - t.Fatalf("placeholder questions advanced inception: %+v", got) - } - // A rejected batch must not prevent subsequent real questions from advancing. - w.plukQuestions = nil - questionBeads = nil - for i := 0; i < minQuestionsForAdvance; i++ { - text := fmt.Sprintf("Should the classifier support label taxonomy %d?", i) - questionBeads = append(questionBeads, &beads.Bead{Title: "Clarification: " + text}) - w.plukQuestions = append(w.plukQuestions, knowledge.Question{ID: fmt.Sprint(i), Text: text, Category: "general"}) - } - if source == "beads" { - w.checkForQuestions(questionBeads) - } else { - w.applyPlukQuestions(state) - } - if got := eng.GetState(); got.Phase != knowledge.PhaseClarify || len(got.Questions) != minQuestionsForAdvance { - t.Fatalf("real questions did not advance inception: %+v", got) - } - }) - } -} diff --git a/src/pkg/dashboard/inception_run_admission_test.go b/src/pkg/dashboard/inception_run_admission_test.go deleted file mode 100644 index 849ce62259..0000000000 --- a/src/pkg/dashboard/inception_run_admission_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package dashboard - -import ( - "context" - "net/http" - "strings" - "testing" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -func driveInceptionToScaffold(t *testing.T, s *Server) { - t.Helper() - if rec := doPost(s, "/api/inception/start", map[string]interface{}{"idea": "ship a run-backed idea"}); rec.Code != http.StatusOK { - t.Fatalf("start: %d body=%s", rec.Code, rec.Body.String()) - } - qs := []knowledge.Question{{ID: "scope", Text: "What scope?", Category: "features"}} - if rec := doPost(s, "/api/inception/questions", map[string]interface{}{"questions": qs}); rec.Code != http.StatusOK { - t.Fatalf("questions: %d body=%s", rec.Code, rec.Body.String()) - } - if rec := doPost(s, "/api/inception/answer", map[string]interface{}{"answers": map[string]string{"scope": "first spec"}}); rec.Code != http.StatusOK { - t.Fatalf("answer: %d body=%s", rec.Code, rec.Body.String()) - } - facts := []knowledge.IdeationFact{ - {Title: "Vision", Body: "Run-backed inception", Type: knowledge.FactVision}, - {Title: "Constitution", Body: "Use Go", Type: knowledge.FactConstitution}, - {Title: "Requirement", Body: "Create the first spec run", Type: knowledge.FactRequirement}, - } - if rec := doPost(s, "/api/inception/facts", map[string]interface{}{"facts": facts}); rec.Code != http.StatusOK { - t.Fatalf("facts: %d body=%s", rec.Code, rec.Body.String()) - } -} - -func pendingRunStages(t *testing.T, s *Server) int { - t.Helper() - stages, err := s.RunStageAccessor().PendingRunStages(context.Background()) - if err != nil { - t.Fatalf("PendingRunStages: %v", err) - } - return len(stages) -} - -func TestInceptionApproveAdmitsSpecRunWhenSpektacularEnabled(t *testing.T) { - s, _, _ := covFInceptionServer(t) - s.contributeHub.persistTaskLedgers = false - s.deps.Config.Runs.Spektacular.Enabled = true - driveInceptionToScaffold(t, s) - - rec := doPost(s, "/api/inception/approve", map[string]interface{}{ - "issue_url": "https://github.com/myorg/repo1/issues/8290", - "title": "Inception follow-up", - }) - if rec.Code != http.StatusOK { - t.Fatalf("approve: %d body=%s", rec.Code, rec.Body.String()) - } - - stages, err := s.RunStageAccessor().PendingRunStages(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(stages) != 1 || stages[0].Repo != "myorg/repo1" || stages[0].Stage != StageSpec { - t.Fatalf("pending stages = %+v", stages) - } - foundAudit := false - for _, entry := range s.GetAudit().Recent(0) { - if entry.Action == "inception_run_admitted" && strings.Contains(entry.Detail, "repo=myorg/repo1") { - foundAudit = true - } - } - if !foundAudit { - t.Fatalf("inception_run_admitted audit entry not recorded: %+v", s.GetAudit().Recent(0)) - } -} - -func TestInceptionApproveSpektacularDisabledDoesNotAdmitRun(t *testing.T) { - s, _, _ := covFInceptionServer(t) - s.contributeHub.persistTaskLedgers = false - driveInceptionToScaffold(t, s) - - rec := doPost(s, "/api/inception/approve", map[string]interface{}{ - "issue_url": "https://github.com/myorg/repo1/issues/8290", - }) - if rec.Code != http.StatusOK { - t.Fatalf("approve: %d body=%s", rec.Code, rec.Body.String()) - } - if got := pendingRunStages(t, s); got != 0 { - t.Fatalf("pending stages = %d, want 0", got) - } -} - -func TestInceptionApproveTwiceAdmitsOneSpecRun(t *testing.T) { - s, _, _ := covFInceptionServer(t) - s.contributeHub.persistTaskLedgers = false - s.deps.Config.Runs.Spektacular.Enabled = true - driveInceptionToScaffold(t, s) - body := map[string]interface{}{ - "repo": "repo1", - "issue_number": 8290, - } - - if rec := doPost(s, "/api/inception/approve", body); rec.Code != http.StatusOK { - t.Fatalf("first approve: %d body=%s", rec.Code, rec.Body.String()) - } - if rec := doPost(s, "/api/inception/approve", body); rec.Code != http.StatusOK { - t.Fatalf("second approve: %d body=%s", rec.Code, rec.Body.String()) - } - if got := pendingRunStages(t, s); got != 1 { - t.Fatalf("pending stages = %d, want 1", got) - } -} - -func TestInceptionApproveRequiresExplicitRepoTarget(t *testing.T) { - s, _, _ := covFInceptionServer(t) - s.contributeHub.persistTaskLedgers = false - s.deps.Config.Runs.Spektacular.Enabled = true - driveInceptionToScaffold(t, s) - - if rec := doPost(s, "/api/inception/approve", map[string]interface{}{"issue_number": 8290}); rec.Code != http.StatusOK { - t.Fatalf("approve: %d body=%s", rec.Code, rec.Body.String()) - } - if got := pendingRunStages(t, s); got != 0 { - t.Fatalf("pending stages = %d, want 0", got) - } -} - -func TestInceptionApproveRejectsNonGitHubIssueURL(t *testing.T) { - s, _, _ := covFInceptionServer(t) - s.contributeHub.persistTaskLedgers = false - s.deps.Config.Runs.Spektacular.Enabled = true - driveInceptionToScaffold(t, s) - - rec := doPost(s, "/api/inception/approve", map[string]interface{}{ - "issue_url": "https://example.com/myorg/repo1/issues/8290", - }) - if rec.Code != http.StatusBadRequest { - t.Fatalf("approve: got %d body=%s, want 400", rec.Code, rec.Body.String()) - } - if got := pendingRunStages(t, s); got != 0 { - t.Fatalf("pending stages = %d, want 0", got) - } -} diff --git a/src/pkg/dashboard/inception_watcher.go b/src/pkg/dashboard/inception_watcher.go deleted file mode 100644 index c4e6da6e78..0000000000 --- a/src/pkg/dashboard/inception_watcher.go +++ /dev/null @@ -1,1478 +0,0 @@ -package dashboard - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "log/slog" - "os" - "strings" - "sync" - "time" - - "github.com/hivecommons/hive/crux" - "github.com/hivecommons/hive/crux/agentparse" - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/governor" - "github.com/hivecommons/hive/pkg/knowledge" -) - -const ( - inceptionBeadRefPrefix = "inception/" - minQuestionsForAdvance = 5 - minFactsForAdvance = 3 - targetFactCount = 8 - factEnrichmentGracePeriod = 15 * time.Second - autoFactFallbackTimeout = 60 * time.Second // minimum time before fact fallback can fire - autoQuestionFallbackTimeout = 60 * time.Second // minimum time before fallback can fire - agentIdleThreshold = 30 * time.Second // agent must be idle this long before fallback -) - -var ( - inceptionWatchIntervalS = 5 * time.Second - inceptionFastPollInterval = 2 * time.Second - plukSubscriberPollInterval = 500 * time.Millisecond - plukSubscriberSeekEnd = true - plukLogFile = func() string { return fmt.Sprintf("%s/hive-brainstorm.jsonl", plukLogDir) } -) - -type inceptionAgentManager interface { - GetBufferOutput(name string, lines int) ([]string, error) - SendKick(name string, message string) error - RestartWithBootstrap(ctx context.Context, name, prompt string) error -} - -// InceptionWatcher polls brainstorm beads and bridges them into the inception -// state machine. It detects question beads (capture → clarify) and fact beads -// (structure → scaffold), advancing phases automatically. -type InceptionWatcher struct { - beadStore *beads.Store - inception *knowledge.InceptionEngine - scheduler SchedulerControl - agentMgr inceptionAgentManager - governor *governor.Governor - logger *slog.Logger - - lastQuestionCount int - lastFactCount int - lastSlug string - lastKickRetry time.Time - kickRetryCount int - rateLimitedUntil time.Time - ctx context.Context - factGraceStart time.Time - captureSeenAt time.Time // when watcher first saw this inception in capture phase - structureSeenAt time.Time // when watcher first saw this inception in structure phase - - pollMu sync.Mutex - plukMu sync.Mutex - plukFactLines []string - plukIdleInStructure bool - plukLastActivity time.Time // last time pluk saw agent output - plukEventCount int // total pluk events processed - plukQuestions []knowledge.Question - plukBdCreateLines []string -} - -// NewInceptionWatcher creates a watcher that polls the brainstorm bead store. -func NewInceptionWatcher( - beadStore *beads.Store, - inception *knowledge.InceptionEngine, - sched SchedulerControl, - agentMgr crux.Runtime, - gov *governor.Governor, - logger *slog.Logger, -) *InceptionWatcher { - w := &InceptionWatcher{ - beadStore: beadStore, - inception: inception, - scheduler: sched, - governor: gov, - logger: logger, - } - if agentMgr != nil { - w.agentMgr = agentMgr - } - return w -} - -// Run starts the polling loop and event subscriber. Blocks until ctx is cancelled. -func (w *InceptionWatcher) Run(ctx context.Context) { - w.ctx = ctx - w.logger.Info("inception watcher started") - watchInterval := inceptionWatchIntervalS - fastPollInterval := inceptionFastPollInterval - plukLog := plukLogFile() - plukPollInterval := plukSubscriberPollInterval - plukSeekEnd := plukSubscriberSeekEnd - ticker := time.NewTicker(watchInterval) - defer ticker.Stop() - - // Start pluk event subscriber for brainstorm session - go w.runPlukSubscriberWithSettings(ctx, plukLog, watchInterval, plukPollInterval, plukSeekEnd) - - lastInterval := watchInterval - - for { - // Adaptive polling: 2s during capture/structure, 5s otherwise - state := w.inception.GetState() - var targetInterval time.Duration - if state != nil && (state.Phase == knowledge.PhaseCapture || state.Phase == knowledge.PhaseStructure) { - targetInterval = fastPollInterval - } else { - targetInterval = watchInterval - } - if targetInterval != lastInterval { - ticker.Reset(targetInterval) - lastInterval = targetInterval - } - - select { - case <-ctx.Done(): - w.logger.Info("inception watcher stopped") - return - case <-ticker.C: - w.poll(ctx) - } - } -} - -func (w *InceptionWatcher) poll(ctx context.Context) { - w.pollMu.Lock() - defer w.pollMu.Unlock() - - if w.inception == nil || w.beadStore == nil { - return - } - - if err := w.beadStore.Reload(); err != nil { - w.logger.Warn("inception watcher: bead store reload failed", "error", err) - } - - state := w.inception.GetState() - if state == nil { - w.lastQuestionCount = 0 - w.lastFactCount = 0 - w.lastSlug = "" - w.factGraceStart = time.Time{} - return - } - - if state.IdeaSlug != w.lastSlug { - w.lastQuestionCount = 0 - w.lastFactCount = 0 - w.kickRetryCount = 0 - w.lastKickRetry = time.Time{} - w.rateLimitedUntil = time.Time{} - w.factGraceStart = time.Time{} - w.captureSeenAt = time.Now() - w.structureSeenAt = time.Time{} - w.plukMu.Lock() - w.plukFactLines = nil - w.plukQuestions = nil - w.plukBdCreateLines = nil - w.plukIdleInStructure = false - w.plukLastActivity = time.Time{} - w.plukMu.Unlock() - if w.lastSlug != "" { - w.reapOldInceptionBeads(state.StartedAt) - } - w.lastSlug = state.IdeaSlug - } - - inceptionBeads := w.findInceptionBeads() - - switch state.Phase { - case knowledge.PhaseCapture: - if len(inceptionBeads) > 0 { - w.checkForQuestions(inceptionBeads) - } - // Parse questions from agent output — bd create commands and tables. - if state.Phase == knowledge.PhaseCapture && w.agentMgr != nil { - w.interceptQuestionsFromBuffer(state) - w.checkForQuestionsInOutput() - } - // Retry kick if agent is stuck. - if state.Phase == knowledge.PhaseCapture && w.agentMgr != nil { - w.retryKickIfStale(state) - } - // Fallback: auto-generate questions if the agent is idle. - // Only fires if: (1) minimum time has elapsed, AND (2) pluk shows - // no agent activity for agentIdleThreshold. This lets the agent - // take as long as it needs while actively working. - if state.Phase == knowledge.PhaseCapture { - if !w.captureSeenAt.IsZero() && time.Since(w.captureSeenAt) > autoQuestionFallbackTimeout { - w.plukMu.Lock() - lastActivity := w.plukLastActivity - w.plukMu.Unlock() - if lastActivity.IsZero() { - // No pluk events yet — agent still bootstrapping. - // Only fall back after 2x the timeout (agent never started). - if time.Since(w.captureSeenAt) > autoQuestionFallbackTimeout*2 { - w.logger.Info("question fallback: no pluk events (bootstrap timeout)", - "elapsed", time.Since(w.captureSeenAt).Round(time.Second), - "pluk_events", w.plukEventCount, - ) - w.autoGenerateQuestions(state) - } - } else if time.Since(lastActivity) > agentIdleThreshold { - // Agent was active but went idle — fall back. - w.logger.Info("question fallback: agent idle", - "idle_duration", time.Since(lastActivity).Round(time.Second), - "elapsed", time.Since(w.captureSeenAt).Round(time.Second), - "pluk_events", w.plukEventCount, - ) - w.autoGenerateQuestions(state) - } - // else: agent is actively producing output — keep waiting. - } - } - case knowledge.PhaseStructure: - // Check for fact beads — already filtered by StartedAt in - // findInceptionBeads. User answers gate the phase transition - // (SubmitAnswers advances to structure), so all beads created - // after StartedAt in the current inception are valid. - w.checkForFacts(ctx, inceptionBeads) - // Intercept fact-like content from buffer - if state.Phase == knowledge.PhaseStructure && w.agentMgr != nil { - w.interceptFactsFromBuffer(ctx, state) - } - // Retry kick if agent isn't creating facts. - if state.Phase == knowledge.PhaseStructure && w.agentMgr != nil { - w.retryKickIfStale(state) - } - // Fallback: auto-generate facts if the agent is idle. - // Same activity-based approach as questions — wait for minimum - // time, then only fall back if pluk shows no agent activity. - if state.Phase == knowledge.PhaseStructure { - if w.structureSeenAt.IsZero() { - w.structureSeenAt = time.Now() - } - if time.Since(w.structureSeenAt) > autoFactFallbackTimeout { - w.plukMu.Lock() - lastActivity := w.plukLastActivity - w.plukMu.Unlock() - if lastActivity.IsZero() { - if time.Since(w.structureSeenAt) > autoFactFallbackTimeout*2 { - w.autoGenerateFacts(ctx, state) - } - } else if time.Since(lastActivity) > agentIdleThreshold { - w.autoGenerateFacts(ctx, state) - } - } - } - } -} - -func (w *InceptionWatcher) reapOldInceptionBeads(beforeTime time.Time) { - open := beads.StatusOpen - actor := "brainstorm" - all := w.beadStore.List(beads.ListFilter{ - Status: &open, - Actor: &actor, - }) - - reaped := 0 - for _, b := range all { - if !strings.HasPrefix(b.ExternalRef, inceptionBeadRefPrefix) { - continue - } - if b.CreatedAt.Before(beforeTime) { - if err := w.beadStore.Close(b.ID); err == nil { - reaped++ - } - } - } - if reaped > 0 { - w.logger.Info("inception watcher: reaped old inception beads", "count", reaped) - } -} - -func inferFactType(title string) string { - lower := strings.ToLower(title) - if strings.HasPrefix(lower, "clarification:") { - return "" - } - switch { - case strings.Contains(lower, "vision") || strings.Contains(lower, "purpose") || strings.Contains(lower, "project goal"): - return "vision" - case strings.Contains(lower, "constitution") || strings.Contains(lower, "principles") || strings.Contains(lower, "code style") || strings.Contains(lower, "architecture"): - return "constitution" - case strings.Contains(lower, "constraint") || strings.Contains(lower, "boundary") || strings.Contains(lower, "limitation") || - strings.Contains(lower, "must not") || strings.Contains(lower, "should not") || strings.Contains(lower, "do not"): - return "constraint" - case strings.Contains(lower, "requirement") || containsWord(lower, "must") || strings.Contains(lower, "feature"): - return "requirement" - case strings.Contains(lower, "stakeholder") || containsWord(lower, "user") || strings.Contains(lower, "audience"): - return "stakeholder" - case strings.Contains(lower, "acceptance") || strings.Contains(lower, "success") || strings.Contains(lower, "criteria") || containsWord(lower, "test"): - return "acceptance" - } - return "" -} - -func (w *InceptionWatcher) findInceptionBeads() []*beads.Bead { - state := w.inception.GetState() - if state == nil { - return nil - } - - // List ALL beads from brainstorm OR inception actors. The agent - // sometimes uses --actor inception instead of --actor brainstorm, - // and may omit the inception/ external_ref prefix. - all := w.beadStore.List(beads.ListFilter{}) - - var inception []*beads.Bead - for _, b := range all { - if b.CreatedAt.Before(state.StartedAt) { - continue - } - // Match by actor: brainstorm or inception - if b.Actor != "brainstorm" && b.Actor != "inception" { - continue - } - // Accept beads matching any inception indicator. The agent uses - // inconsistent formats — cast a wide net. - hasInceptionRef := strings.HasPrefix(b.ExternalRef, inceptionBeadRefPrefix) - hasClarificationTitle := strings.Contains(strings.ToLower(b.Title), "clarif") || - strings.HasSuffix(strings.TrimSpace(b.Title), "?") - hasFactKeyword := strings.Contains(strings.ToLower(b.Title), "vision") || - strings.Contains(strings.ToLower(b.Title), "requirement") || - strings.Contains(strings.ToLower(b.Title), "constraint") - if hasInceptionRef || hasClarificationTitle || hasFactKeyword || b.Type == beads.TypeAdvisory { - inception = append(inception, b) - } - } - return inception -} - -func (w *InceptionWatcher) checkForQuestions(inceptionBeads []*beads.Bead) { - var questions []knowledge.Question - seenIDs := make(map[string]int) - for _, b := range inceptionBeads { - cat := b.Meta("category") - if cat == "" { - if strings.HasPrefix(b.Title, "Clarification:") || strings.HasPrefix(b.Title, "clarification:") { - cat = "general" - } else { - continue - } - } - qID := b.Meta("question_id") - if qID == "" { - qID = cat - } - seenIDs[qID]++ - if seenIDs[qID] > 1 { - qID = fmt.Sprintf("%s-%d", qID, seenIDs[qID]) - } - - title := b.Title - title = strings.TrimPrefix(title, "Clarification: ") - title = strings.TrimPrefix(title, "clarification: ") - - if !isUsableQuestionText(title) { - continue - } - - questions = append(questions, knowledge.Question{ - ID: qID, - Text: title, - Default: b.Meta("default"), - Category: cat, - }) - } - - // Deduplicate by ID — the agent output parser can produce duplicate IDs - seen := make(map[string]bool, len(questions)) - unique := make([]knowledge.Question, 0, len(questions)) - for _, q := range questions { - if !seen[q.ID] { - seen[q.ID] = true - unique = append(unique, q) - } - } - questions = unique - - if len(questions) < minQuestionsForAdvance { - return - } - if len(questions) == w.lastQuestionCount { - return - } - w.lastQuestionCount = len(questions) - - if err := w.inception.SetQuestions(questions); err != nil { - w.logger.Warn("inception watcher: failed to set questions", "error", err, "count", len(questions)) - return - } - - w.logger.Info("inception watcher: questions extracted, advancing to clarify", - "count", len(questions), - ) -} - -const ( - outputParseLineCount = 100 - interceptBufferLineCount = 500 - kickRetryDelayS = 20 * time.Second - kickRetryGracePeriodS = 15 * time.Second - maxKickRetries = 5 -) - -// retryKickIfStale re-sends the inception prompt via SendKick when the -// initial RestartWithBootstrap didn't deliver. Detects stale state by -// checking if the agent is reaping (default mode) instead of processing -// the inception idea. -// plukEvent represents a parsed pluk event from the JSONL stream. -type plukEvent struct { - Type string `json:"type"` - Session string `json:"session"` - Data map[string]string `json:"data"` -} - -const plukLogDir = "/var/run/pluk/logs" - -// runPlukSubscriber tails the brainstorm session's pluk JSONL event -// stream and takes immediate action on relevant events. This replaces 5s -// polling with real-time event-driven reactions. -func (w *InceptionWatcher) runPlukSubscriber(ctx context.Context) { - w.runPlukSubscriberWithSettings(ctx, plukLogFile(), inceptionWatchIntervalS, plukSubscriberPollInterval, plukSubscriberSeekEnd) -} - -func (w *InceptionWatcher) runPlukSubscriberWithSettings(ctx context.Context, logFile string, watchInterval, pollInterval time.Duration, seekEnd bool) { - // Wait for the log file to exist - for { - if _, err := os.Stat(logFile); err == nil { - break - } - select { - case <-ctx.Done(): - return - case <-time.After(watchInterval): - continue - } - } - - w.logger.Info("pluk subscriber started", "logFile", logFile) - - // Open file and seek to end (only new events) - f, err := os.Open(logFile) - if err != nil { - w.logger.Warn("pluk subscriber: cannot open log", "error", err) - return - } - defer func() { _ = f.Close() }() - - // Seek to end — we only care about new events - if seekEnd { - if _, err := f.Seek(0, 2); err != nil { - w.logger.Warn("pluk subscriber: cannot seek to end", "error", err) - } - } - - scanner := bufio.NewScanner(f) - const plukMaxLineBytes = 1 << 20 // 1 MiB — agent output can exceed 64KB default - scanner.Buffer(make([]byte, 0, plukMaxLineBytes), plukMaxLineBytes) - for { - select { - case <-ctx.Done(): - return - default: - } - - if scanner.Scan() { - line := scanner.Text() - if line == "" { - continue - } - - var event plukEvent - if err := json.Unmarshal([]byte(line), &event); err != nil { - continue - } - - w.handlePlukEvent(event) - } else { - // No new data — wait briefly then retry (tail -f behavior) - time.Sleep(pollInterval) - // Check if file was rotated by comparing inodes - openStat, err1 := f.Stat() - diskStat, err2 := os.Stat(logFile) - if err1 != nil || err2 != nil { - w.logger.Warn("pluk log disappeared, stopping subscriber") - return - } - if !os.SameFile(openStat, diskStat) { - w.logger.Info("pluk log rotated, restarting subscriber") - return - } - } - } -} - -// handlePlukEvent reacts to pluk events from the brainstorm session. -// Called from the Pluk subscriber goroutine — must hold plukMu for field access. -func (w *InceptionWatcher) handlePlukEvent(event plukEvent) { - w.plukMu.Lock() - defer w.plukMu.Unlock() - - // Track any agent activity for idle detection - w.plukLastActivity = time.Now() - w.plukEventCount++ - if w.plukEventCount%50 == 1 { - w.logger.Info("pluk event received", - "count", w.plukEventCount, - "type", event.Type, - ) - } - - state := w.inception.GetState() - if state == nil { - return - } - - switch event.Type { - case "state_change": - switch event.Data["state"] { - case "idle": - phase := state.Phase - - // Agent went idle during capture — if Pluk intercepted questions, apply them now - if phase == knowledge.PhaseCapture && len(w.plukQuestions) > 0 { - w.applyPlukQuestions(state) - return - } - - // Agent went idle during structure — try to extract facts from - // buffered Pluk output before falling back to auto-generation. - if phase == knowledge.PhaseStructure { - w.plukIdleInStructure = true - if len(w.plukFactLines) > 0 { - // plukMu is held for this whole function, so the core is - // called directly: the lock-acquiring wrapper would - // re-enter a non-reentrant mutex and wedge this goroutine - // permanently (#7151). - w.tryExtractFactsFromPlukLocked(w.ctx, state) - } else { - // No fact lines from Pluk — auto-generate immediately - w.autoGenerateFacts(w.ctx, state) - } - return - } - - if w.kickRetryCount < maxKickRetries { - elapsed := time.Since(state.StartedAt) - if elapsed > kickRetryGracePeriodS { - if phase == knowledge.PhaseCapture || phase == knowledge.PhaseStructure { - w.logger.Info("pluk: agent idle during inception — re-kicking", - "phase", phase, - "elapsed", elapsed.Round(time.Second), - ) - w.kickRetryCount++ - w.lastKickRetry = time.Now() - msg := w.buildInceptionKickMessage(state) - go func() { - if err := w.agentMgr.SendKick("brainstorm", msg); err != nil { - w.logger.Warn("pluk: re-kick failed", "error", err) - } - }() - } - } - } - case "working": - w.plukIdleInStructure = false - } - - case "rate_limit": - const rateLimitCooldown = 3 * time.Minute - w.rateLimitedUntil = time.Now().Add(rateLimitCooldown) - w.logger.Warn("pluk: brainstorm hit rate limit — suppressing retries", - "phase", state.Phase, - "cooldown", rateLimitCooldown, - "message", event.Data["message"], - ) - - case "error": - w.logger.Warn("pluk: brainstorm error during inception", - "phase", state.Phase, - "message", event.Data["message"], - ) - - case "tool_call_completed": - // bd create/update completed — trigger immediate poll to check for new beads - if state.Phase == knowledge.PhaseCapture || state.Phase == knowledge.PhaseStructure { - go w.poll(w.ctx) - } - - case "raw_output": - // #4285: pluk puts the pane text on "line" for raw_output, and only - // "line" — classifier.js builds the event as - // createEvent(..., 'raw_output', { line }). "message" is a real pluk key, - // but it belongs to rate_limit and error (handled above), which is - // evidently where this generalised from. Reading "message" here made the - // whole raw_output arm dead: every bd-create interception and every - // keyword re-poll below returned on the empty string. - // src/deploy/hive-panes.sh has always read data.line and was correct. - line := event.Data["line"] - if line == "" { - return - } - lower := strings.ToLower(line) - - // Buffer all bd create lines for parsing (capped to prevent unbounded growth) - const maxBdCreateLines = 200 - if strings.Contains(lower, "bd create") && strings.Contains(lower, "--title") && len(w.plukBdCreateLines) < maxBdCreateLines { - w.plukBdCreateLines = append(w.plukBdCreateLines, line) - } - - switch state.Phase { - case knowledge.PhaseCapture: - // Intercept bd create commands — parse question title directly - if strings.Contains(lower, "bd create") && strings.Contains(lower, "--title") { - if q := w.parseQuestionFromBdCreate(line); q != nil { - w.plukQuestions = append(w.plukQuestions, *q) - if len(w.plukQuestions) >= minQuestionsForAdvance { - w.applyPlukQuestions(state) - } - } - return - } - if strings.Contains(line, "│") { - for kw := range categoryKeywords { - if strings.Contains(lower, kw) { - go w.poll(w.ctx) - return - } - } - } - case knowledge.PhaseStructure: - // Intercept bd create with fact-like titles — extract directly - if strings.Contains(lower, "bd create") && strings.Contains(lower, "--title") { - go w.poll(w.ctx) - return - } - if strings.Contains(lower, "bd update") && - (strings.Contains(lower, "fact_type") || strings.Contains(lower, "fact_body")) { - go w.poll(w.ctx) - return - } - // Buffer lines containing fact-like content for extraction - // when the agent goes idle without creating beads - const maxPlukFactLines = 200 - if len(w.plukFactLines) < maxPlukFactLines { - if strings.Contains(lower, "vision") || strings.Contains(lower, "requirement") || - strings.Contains(lower, "constraint") || strings.Contains(lower, "constitution") || - strings.Contains(lower, "stakeholder") || strings.Contains(lower, "acceptance") || - strings.Contains(lower, "architecture") || strings.Contains(lower, "testing") || - strings.Contains(lower, "deployment") || containsWord(lower, "must") { - w.plukFactLines = append(w.plukFactLines, line) - } - } - } - } -} - -func (w *InceptionWatcher) retryKickIfStale(state *knowledge.InceptionState) { - if w.kickRetryCount >= maxKickRetries { - return - } - if time.Now().Before(w.rateLimitedUntil) { - return - } - if time.Since(state.StartedAt) < kickRetryGracePeriodS { - return - } - if time.Since(w.lastKickRetry) < kickRetryDelayS { - return - } - - // Check if agent is doing inception work or stuck in reaping. - // If the tmux session doesn't exist (on-demand agent not started), - // GetBufferOutput fails — fall through to RestartWithBootstrap. - noSession := false - lines, err := w.agentMgr.GetBufferOutput("brainstorm", outputParseLineCount) - if err != nil || len(lines) == 0 { - noSession = true - } - - isReaping := false - hasInceptionWork := false - for _, l := range lines { - lower := strings.ToLower(l) - if strings.Contains(lower, "reap:") || strings.Contains(lower, "close stale beads") { - isReaping = true - } - if strings.Contains(lower, "inception") || strings.Contains(lower, "clarif") || - strings.Contains(lower, "bd create") || strings.Contains(l, "Clarification:") || - strings.Contains(lower, "fact") || strings.Contains(lower, "structur") || - strings.Contains(lower, "extract") || strings.Contains(lower, "requirement") { - hasInceptionWork = true - } - } - - if hasInceptionWork { - return - } - if !noSession && !isReaping && time.Since(state.StartedAt) < 2*kickRetryGracePeriodS { - return - } - - w.kickRetryCount++ - w.lastKickRetry = time.Now() - - msg := w.buildInceptionKickMessage(state) - - // Try SendKick first (agent already running). If it fails (no session), - // fall back to RestartWithBootstrap which creates the tmux session. - if err := w.agentMgr.SendKick("brainstorm", msg); err != nil { - w.logger.Info("SendKick failed, trying RestartWithBootstrap", - "attempt", w.kickRetryCount, - "error", err, - ) - if err2 := w.agentMgr.RestartWithBootstrap(context.Background(), "brainstorm", msg); err2 != nil { - w.logger.Warn("inception retry kick failed (both methods)", - "attempt", w.kickRetryCount, - "sendKickErr", err, - "bootstrapErr", err2, - ) - } else { - w.logger.Info("inception retry via RestartWithBootstrap succeeded", - "attempt", w.kickRetryCount, - ) - } - } else { - w.logger.Info("inception retry kick sent", - "attempt", w.kickRetryCount, - "isReaping", isReaping, - ) - } -} - -func (w *InceptionWatcher) buildInceptionKickMessage(state *knowledge.InceptionState) string { - switch state.Phase { - case knowledge.PhaseCapture: - return fmt.Sprintf( - "INCEPTION TASK: You are in the capture phase for idea: %q\n"+ - "Generate at least %d clarification questions using `bd create`.\n"+ - "Each question bead must have external_ref starting with 'inception/'.\n"+ - "DO NOT close any beads with inception/ prefix.\n"+ - "DO NOT run spec-kit during capture phase.", - state.IdeaText, minQuestionsForAdvance, - ) - case knowledge.PhaseStructure: - var sb strings.Builder - sb.WriteString(fmt.Sprintf("INCEPTION TASK: Structure phase for idea: %q\n", state.IdeaText)) - sb.WriteString("The user answered your clarification questions. Create fact beads NOW.\n\n") - for _, q := range state.Questions { - ans := state.Answers[q.ID] - if ans != "" { - sb.WriteString(fmt.Sprintf("Q: %s\nA: %s\n\n", q.Text, ans)) - } - } - sb.WriteString("Create at least 3 fact beads. For EACH fact, run:\n\n") - sb.WriteString(fmt.Sprintf("bd create --title \"<fact title>\" --type advisory --priority 1 --actor brainstorm --external-ref \"inception/%s\"\n", state.IdeaSlug)) - sb.WriteString("bd update <bead-id> --set-metadata fact_type=\"<vision|constitution|requirement|constraint|stakeholder|acceptance>\"\n") - sb.WriteString("bd update <bead-id> --set-metadata fact_body=\"<detailed fact content>\"\n\n") - sb.WriteString("Required facts: 1 vision, 1 constitution, 2+ requirements. Start creating beads IMMEDIATELY.") - return sb.String() - default: - return w.scheduler.BuildAgentMessage("brainstorm", nil, w.scheduler.GetLastActionable()) - } -} - -// checkForQuestionsInOutput reads the brainstorm agent's tmux output buffer -// and parses question tables. The model always produces a formatted table of -// questions (with │ delimiters) even when bd create doesn't execute. This -// catches the ~30% of cases where beads aren't created but questions exist. -func (w *InceptionWatcher) checkForQuestionsInOutput() { - lines, err := w.agentMgr.GetBufferOutput("brainstorm", interceptBufferLineCount) - if err != nil || len(lines) == 0 { - return - } - - questions := parseQuestionTable(lines) - if len(questions) < minQuestionsForAdvance { - questions = parseNumberedQuestions(lines) - } - // Deduplicate by ID - { - seen := make(map[string]bool, len(questions)) - deduped := make([]knowledge.Question, 0, len(questions)) - for _, q := range questions { - if !seen[q.ID] { - seen[q.ID] = true - deduped = append(deduped, q) - } - } - questions = deduped - } - if len(questions) < minQuestionsForAdvance { - return - } - if len(questions) == w.lastQuestionCount { - return - } - w.lastQuestionCount = len(questions) - - if err := w.inception.SetQuestions(questions); err != nil { - w.logger.Warn("inception watcher: failed to set questions from output parse", "error", err, "count", len(questions)) - return - } - - w.logger.Info("inception watcher: questions extracted from agent output (table parse)", - "count", len(questions), - ) -} - -// categoryKeywords are the valid question categories the agent produces during -// Level-1 ideation. They are passed to the shared agentparse list-parsers. -var categoryKeywords = map[string]bool{ - "users": true, "features": true, "constraints": true, - "testing": true, "deployment": true, "storage": true, - "language": true, "general": true, -} - -// parseQuestionTable extracts questions from the agent's │-delimited table -// output. It filters template scaffolding from agentparse.ParseTable: -// the generic parser finds the category column and extracts title/default, and -// this adapter maps each Item into a knowledge.Question (ID == Category, as -// before). -func parseQuestionTable(lines []string) []knowledge.Question { - items := agentparse.ParseTable(lines, categoryKeywords) - questions := make([]knowledge.Question, 0, len(items)) - for _, it := range items { - if !isUsableQuestionText(it.Title) { - continue - } - questions = append(questions, knowledge.Question{ - ID: it.Category, - Text: it.Title, - Default: it.Default, - Category: it.Category, - }) - } - return questions -} - -// numberedQuestionRe is retained for callers in this file that strip list -// decoration from a single line; it is the same matcher agentparse uses. -var numberedQuestionRe = agentparse.NumberedListRe() - -// parseNumberedQuestions extracts questions from numbered or bulleted lists. -// Filters template scaffolding from agentparse.ParseNumberedList with the -// "general" fallback category, mapping each Item into a knowledge.Question. -func parseNumberedQuestions(lines []string) []knowledge.Question { - items := agentparse.ParseNumberedList(lines, categoryKeywords, "general") - questions := make([]knowledge.Question, 0, len(items)) - for _, it := range items { - if !isUsableQuestionText(it.Title) { - continue - } - questions = append(questions, knowledge.Question{ - ID: it.Category, - Text: it.Title, - Default: "", - Category: it.Category, - }) - } - return questions -} - -func (w *InceptionWatcher) checkForFacts(ctx context.Context, inceptionBeads []*beads.Bead) { - var facts []knowledge.IdeationFact - for _, b := range inceptionBeads { - factType := b.Meta("fact_type") - if factType == "" { - // Infer fact type from title when metadata is missing - factType = inferFactType(b.Title) - if factType == "" { - continue - } - } - - body := b.Meta("fact_body") - if body == "" { - body = b.Meta("detail") - } - if body == "" { - body = b.Notes - } - if body == "" { - body = b.Title - } - - var tags []string - if t := b.Meta("fact_tags"); t != "" { - tags = strings.Split(t, ",") - for i := range tags { - tags[i] = strings.TrimSpace(tags[i]) - } - } - - facts = append(facts, knowledge.IdeationFact{ - Title: b.Title, - Body: body, - Type: knowledge.FactType(factType), - Tags: tags, - }) - } - - if len(facts) < minFactsForAdvance { - return - } - - if len(facts) >= targetFactCount { - w.recordAndAdvanceFacts(ctx, facts) - return - } - - if w.factGraceStart.IsZero() { - w.factGraceStart = time.Now() - w.logger.Info("inception watcher: facts met minimum, starting enrichment grace period", - "count", len(facts), - "target", targetFactCount, - "grace_seconds", factEnrichmentGracePeriod.Seconds(), - ) - return - } - - if time.Since(w.factGraceStart) < factEnrichmentGracePeriod { - if len(facts) != w.lastFactCount { - w.lastFactCount = len(facts) - w.logger.Info("inception watcher: more facts arriving during grace period", - "count", len(facts), - "elapsed", time.Since(w.factGraceStart).Round(time.Second), - ) - } - return - } - - w.recordAndAdvanceFacts(ctx, facts) -} - -func (w *InceptionWatcher) recordAndAdvanceFacts(ctx context.Context, facts []knowledge.IdeationFact) { - state := w.inception.GetState() - if state != nil && len(state.Questions) > 0 && len(state.Answers) > 0 { - facts = w.supplementFactsFromQA(facts, state) - } - - if len(facts) == w.lastFactCount { - return - } - w.lastFactCount = len(facts) - w.factGraceStart = time.Time{} - - if err := w.inception.RecordFacts(ctx, facts); err != nil { - w.logger.Warn("inception watcher: failed to record facts", "error", err, "count", len(facts)) - return - } - - w.logger.Info("inception watcher: facts extracted, advancing to scaffold", - "count", len(facts), - ) -} - -func (w *InceptionWatcher) supplementFactsFromQA(existing []knowledge.IdeationFact, state *knowledge.InceptionState) []knowledge.IdeationFact { - originalCount := len(existing) - - existingTitles := make(map[string]bool) - hasVision := false - for _, f := range existing { - existingTitles[f.Title] = true - if f.Type == knowledge.FactVision { - hasVision = true - } - } - - categoryToFact := map[string]knowledge.FactType{ - "language": knowledge.FactConstitution, - "features": knowledge.FactRequirement, - "constraints": knowledge.FactConstraint, - "users": knowledge.FactStakeholder, - "testing": knowledge.FactAcceptance, - "deployment": knowledge.FactConstraint, - "storage": knowledge.FactRequirement, - } - - if !hasVision && state.IdeaText != "" { - existing = append(existing, knowledge.IdeationFact{ - Title: "Project Vision", - Body: state.IdeaText, - Type: knowledge.FactVision, - Tags: []string{"supplemented"}, - }) - } - - for _, q := range state.Questions { - answer, ok := state.Answers[q.ID] - if !ok || strings.TrimSpace(answer) == "" { - continue - } - if existingTitles[q.Text] { - continue - } - existingTitles[q.Text] = true - factType, mapped := categoryToFact[q.Category] - if !mapped { - factType = knowledge.FactRequirement - } - existing = append(existing, knowledge.IdeationFact{ - Title: q.Text, - Body: answer, - Type: factType, - Tags: []string{"supplemented"}, - }) - } - - supplemented := len(existing) - originalCount - if supplemented > 0 { - w.logger.Info("inception watcher: supplemented facts from Q&A", - "original", originalCount, - "supplemented", supplemented, - "total", len(existing), - ) - } - - return existing -} - -// autoGenerateFacts synthesizes facts from the inception Q&A when the -// brainstorm agent hasn't produced fact beads within the timeout. This -// is a fallback — the agent gets first shot during the timeout window. -func (w *InceptionWatcher) autoGenerateFacts(ctx context.Context, state *knowledge.InceptionState) { - if len(state.Questions) == 0 || len(state.Answers) == 0 { - return - } - - var facts []knowledge.IdeationFact - - // Vision fact from the idea text (greenfield) or repo URL (brownfield) - visionBody := state.IdeaText - if visionBody == "" && state.RepoURL != "" { - visionBody = "Brownfield project from " + state.RepoURL - } - if visionBody != "" { - facts = append(facts, knowledge.IdeationFact{ - Title: "Project Vision", - Body: visionBody, - Type: knowledge.FactVision, - Tags: []string{"auto-generated"}, - }) - } - - // Map question categories to fact types - categoryToFact := map[string]knowledge.FactType{ - "language": knowledge.FactConstitution, - "features": knowledge.FactRequirement, - "constraints": knowledge.FactConstraint, - "users": knowledge.FactStakeholder, - "testing": knowledge.FactAcceptance, - "deployment": knowledge.FactConstraint, - "storage": knowledge.FactRequirement, - } - - for _, q := range state.Questions { - answer, ok := state.Answers[q.ID] - if !ok || strings.TrimSpace(answer) == "" { - continue - } - - factType, mapped := categoryToFact[q.Category] - if !mapped { - factType = knowledge.FactRequirement - } - - facts = append(facts, knowledge.IdeationFact{ - Title: q.Text, - Body: answer, - Type: factType, - Tags: []string{"auto-generated"}, - }) - } - - if len(facts) < minFactsForAdvance { - return - } - - if err := w.inception.RecordFacts(ctx, facts); err != nil { - w.logger.Warn("inception watcher: auto-fact fallback failed", "error", err, "count", len(facts)) - return - } - - w.inception.IncrementAutoFactCount(len(facts)) - - w.logger.Info("inception watcher: auto-generated facts from Q&A (agent timeout fallback)", - "count", len(facts), - "timeout", autoFactFallbackTimeout, - ) -} - -// autoGenerateQuestions creates default clarification questions from the -// idea text when the brainstorm agent hasn't produced question beads -// within the timeout. Agent gets first shot during the timeout window. -func (w *InceptionWatcher) autoGenerateQuestions(state *knowledge.InceptionState) { - if len(state.Questions) >= minQuestionsForAdvance { - return - } - - // Infer default language from the idea text - langDefault := "Go" - ideaLower := strings.ToLower(state.IdeaText) - switch { - case containsWord(ideaLower, "java") && !strings.Contains(ideaLower, "javascript"): - langDefault = "Java" - case strings.Contains(ideaLower, "python"): - langDefault = "Python" - case containsWord(ideaLower, "rust"): - langDefault = "Rust" - case strings.Contains(ideaLower, "typescript"): - langDefault = "TypeScript" - case strings.Contains(ideaLower, "javascript"): - langDefault = "JavaScript" - case strings.Contains(ideaLower, "ruby"): - langDefault = "Ruby" - case containsWord(ideaLower, "shell") || containsWord(ideaLower, "bash"): - langDefault = "Shell/Bash" - } - - defaults := []knowledge.Question{ - {ID: "language", Text: "What programming language or runtime should this use?", Category: "language", Default: langDefault}, - {ID: "users", Text: "Who are the primary users and how will they interact with it?", Category: "users", Default: "Developers via CLI"}, - {ID: "features", Text: "What are the 2-3 must-have features?", Category: "features", Default: "Core functionality as described"}, - {ID: "constraints", Text: "What constraints or limitations should be respected?", Category: "constraints", Default: "Keep it simple and well-tested"}, - {ID: "testing", Text: "How will you know it is working correctly?", Category: "testing", Default: "Unit tests and integration tests"}, - {ID: "deployment", Text: "How and where will this be deployed?", Category: "deployment", Default: "Docker container"}, - } - - // Merge: keep agent-produced questions, fill remaining slots with defaults - existing := make(map[string]bool, len(state.Questions)) - for _, q := range state.Questions { - existing[q.ID] = true - } - questions := append([]knowledge.Question{}, state.Questions...) - for _, d := range defaults { - if !existing[d.ID] && len(questions) < minQuestionsForAdvance+1 { - questions = append(questions, d) - } - } - - if err := w.inception.SetQuestions(questions); err != nil { - w.logger.Warn("inception watcher: auto-question fallback failed", "error", err) - return - } - - w.inception.IncrementAutoQuestionCount(len(questions)) - - w.logger.Info("inception watcher: auto-generated questions (agent timeout fallback)", - "count", len(questions), - "timeout", autoQuestionFallbackTimeout, - ) -} - -// tryExtractFactsFromPluk attempts to extract structured facts from raw output -// lines buffered by the Pluk subscriber. Called when the agent goes idle during -// structure phase — the agent produced text about facts but didn't create -// beads. This is a Pluk-driven alternative to the 60s auto-fact fallback: -// it fires immediately on idle detection instead of waiting for a timeout. -// -// This is the variant for callers that do NOT already hold plukMu. Callers that -// do — handlePlukEvent is the only one — must use tryExtractFactsFromPlukLocked -// instead: plukMu is a sync.Mutex and is not reentrant, so acquiring it here -// while the caller holds it self-deadlocks the Pluk subscriber goroutine for -// the remaining life of the process (#7151). -func (w *InceptionWatcher) tryExtractFactsFromPluk(ctx context.Context, state *knowledge.InceptionState) { - w.plukMu.Lock() - defer w.plukMu.Unlock() - w.tryExtractFactsFromPlukLocked(ctx, state) -} - -// tryExtractFactsFromPlukLocked is the body of tryExtractFactsFromPluk. -// -// The caller MUST already hold w.plukMu; it is neither acquired nor released -// here. Both plukFactLines accesses below — the snapshot at the top and the -// clear at the bottom — are therefore unguarded reads/writes that are safe only -// under that precondition. -func (w *InceptionWatcher) tryExtractFactsFromPlukLocked(ctx context.Context, state *knowledge.InceptionState) { - factLines := append([]string{}, w.plukFactLines...) - - if len(factLines) == 0 || len(state.Answers) == 0 { - return - } - - var facts []knowledge.IdeationFact - - // Scan buffered lines for fact-type keywords and extract content - factTypeKeywords := map[string]knowledge.FactType{ - "vision": knowledge.FactVision, - "constitution": knowledge.FactConstitution, - "requirement": knowledge.FactRequirement, - "constraint": knowledge.FactConstraint, - "stakeholder": knowledge.FactStakeholder, - "acceptance": knowledge.FactAcceptance, - } - - seen := make(map[string]bool) - for _, line := range factLines { - lower := strings.ToLower(line) - for keyword, factType := range factTypeKeywords { - if strings.Contains(lower, keyword) && !seen[keyword] { - seen[keyword] = true - body := strings.TrimSpace(line) - if len(body) > 20 { - facts = append(facts, knowledge.IdeationFact{ - Title: strings.ToUpper(keyword[:1]) + keyword[1:] + " (from agent output)", - Body: body, - Type: factType, - Tags: []string{"pluk-extracted"}, - }) - } - break - } - } - } - - if len(facts) < minFactsForAdvance { - // Not enough facts from Pluk output — fall back to Q&A auto-generation - // but do it immediately instead of waiting for the 60s timeout - w.logger.Info("pluk: insufficient facts from output, using Q&A fallback", - "pluk_facts", len(facts), - "needed", minFactsForAdvance, - ) - w.autoGenerateFacts(ctx, state) - return - } - - if err := w.inception.RecordFacts(ctx, facts); err != nil { - w.logger.Warn("pluk: Pluk fact extraction failed", "error", err, "count", len(facts)) - return - } - - w.inception.IncrementAutoFactCount(len(facts)) - - w.logger.Info("pluk: extracted facts from agent output (no bead creation needed)", - "count", len(facts), - "source", "pluk-raw-output", - ) - w.plukFactLines = nil -} - -// interceptFactsFromBuffer reads the tmux buffer and buffers fact-like -// lines for extraction. If enough content is found and the agent has gone -// idle (no new lines since last poll), triggers fact extraction immediately. -func (w *InceptionWatcher) interceptFactsFromBuffer(ctx context.Context, state *knowledge.InceptionState) { - if len(state.FactSlugs) >= minFactsForAdvance { - return - } - - lines, err := w.agentMgr.GetBufferOutput("brainstorm", interceptBufferLineCount) - if err != nil || len(lines) == 0 { - return - } - - w.plukMu.Lock() - defer w.plukMu.Unlock() - - for _, line := range lines { - lower := strings.ToLower(line) - if strings.Contains(lower, "vision") || strings.Contains(lower, "requirement") || - strings.Contains(lower, "constraint") || strings.Contains(lower, "constitution") || - strings.Contains(lower, "stakeholder") || strings.Contains(lower, "acceptance") || - strings.Contains(lower, "architecture") || strings.Contains(lower, "testing") || - strings.Contains(lower, "deployment") { - found := false - for _, existing := range w.plukFactLines { - if existing == line { - found = true - break - } - } - if !found && len(w.plukFactLines) < 200 { - w.plukFactLines = append(w.plukFactLines, line) - } - } - } -} - -// interceptQuestionsFromBuffer reads the tmux output buffer directly and -// parses questions from multiple formats: bd create commands, tool call -// previews, numbered lists, and question-mark lines with category keywords. -func (w *InceptionWatcher) interceptQuestionsFromBuffer(state *knowledge.InceptionState) { - if len(state.Questions) >= minQuestionsForAdvance { - return - } - - lines, err := w.agentMgr.GetBufferOutput("brainstorm", interceptBufferLineCount) - if err != nil || len(lines) == 0 { - return - } - - w.plukMu.Lock() - defer w.plukMu.Unlock() - - for _, line := range lines { - lower := strings.ToLower(line) - var q *knowledge.Question - - switch { - case strings.Contains(lower, "bd create") && strings.Contains(lower, "--title"): - q = w.parseQuestionFromBdCreate(line) - - case strings.HasPrefix(strings.TrimSpace(line), "└") && strings.Contains(lower, "--title"): - q = w.parseQuestionFromBdCreate(line) - - case strings.HasSuffix(strings.TrimSpace(line), "?") && len(line) > 20: - for kw := range categoryKeywords { - if strings.Contains(lower, kw) { - text := strings.TrimSpace(line) - if m := numberedQuestionRe.FindStringSubmatch(text); m != nil { - text = strings.TrimSpace(m[2]) - } - q = &knowledge.Question{ - ID: kw + "-" + fmt.Sprintf("%d", len(w.plukQuestions)+1), - Text: text, - Category: kw, - Default: "Yes, use best practices", - } - break - } - } - } - - if q != nil && isUsableQuestionText(q.Text) { - found := false - for _, existing := range w.plukQuestions { - if existing.Text == q.Text { - found = true - break - } - } - if !found { - w.plukQuestions = append(w.plukQuestions, *q) - } - } - } - - if len(w.plukQuestions) >= minQuestionsForAdvance { - w.applyPlukQuestions(state) - } -} - -// isTemplatePlaceholder rejects placeholder titles that the agent outputs -// as part of showing a command template before filling in actual values. -// Thin, behavior-preserving adapter over agentparse.IsTemplatePlaceholder. -func isTemplatePlaceholder(title string) bool { - return agentparse.IsTemplatePlaceholder(title) -} - -// isUsableQuestionText rejects echoed kick scaffolding, including placeholders -// with trailing instructions caused by wrapped terminal output. Keep this guard -// inception-specific so other consumers of the shared parsers are unaffected. -func isUsableQuestionText(text string) bool { - text = strings.TrimSpace(text) - if len(text) >= len("Clarification:") && strings.EqualFold(text[:len("Clarification:")], "Clarification:") { - text = strings.TrimSpace(text[len("Clarification:"):]) - } - return text != "" && !isTemplatePlaceholder(text) && - !(strings.HasPrefix(text, "<") && strings.Contains(text, ">")) -} - -// parseQuestionFromBdCreate extracts a question from a bd create command -// in the agent's raw output. Works regardless of --type, --actor, or -// --external-ref values — the title IS the question. Title extraction and -// placeholder rejection are delegated to agentparse.TitleFromBdCreate; category -// inference and prefix handling stay here (inception-specific). -func (w *InceptionWatcher) parseQuestionFromBdCreate(line string) *knowledge.Question { - title, ok := agentparse.TitleFromBdCreate(line) - if !ok || !isUsableQuestionText(title) { - return nil - } - - // Infer category from title or known keywords - lower := strings.ToLower(title) - cat := "general" - for kw := range categoryKeywords { - if strings.Contains(lower, kw) { - cat = kw - break - } - } - - // Remove "Clarification: " prefix if present - title = strings.TrimPrefix(title, "Clarification: ") - title = strings.TrimPrefix(title, "clarification: ") - - qID := cat + "-" + fmt.Sprintf("%d", len(w.plukQuestions)+1) - - w.logger.Info("pluk: intercepted question from bd create", - "title", title, - "category", cat, - ) - - return &knowledge.Question{ - ID: qID, - Text: title, - Category: cat, - Default: "Yes, use best practices", - } -} - -// applyPlukQuestions sets intercepted questions on the inception engine, -// bypassing the bead store entirely. Called when Pluk has captured enough -// questions from the agent's bd create output. -func (w *InceptionWatcher) applyPlukQuestions(state *knowledge.InceptionState) { - if len(w.plukQuestions) < minQuestionsForAdvance { - return - } - if len(state.Questions) >= minQuestionsForAdvance { - return - } - - // Deduplicate by text - seen := make(map[string]bool) - var unique []knowledge.Question - for _, q := range w.plukQuestions { - if isUsableQuestionText(q.Text) && !seen[q.Text] { - seen[q.Text] = true - unique = append(unique, q) - } - } - - if len(unique) < minQuestionsForAdvance { - return - } - - if err := w.inception.SetQuestions(unique); err != nil { - w.logger.Warn("pluk: failed to apply intercepted questions", "error", err, "count", len(unique)) - return - } - - w.logger.Info("pluk: applied intercepted questions — bypassed bead store", - "count", len(unique), - "source", "pluk-bd-create-intercept", - ) - w.plukQuestions = nil -} - -func containsWord(text, word string) bool { - idx := 0 - for { - pos := strings.Index(text[idx:], word) - if pos < 0 { - return false - } - absPos := idx + pos - endPos := absPos + len(word) - atStart := absPos == 0 || !isAlpha(text[absPos-1]) - atEnd := endPos >= len(text) || !isAlpha(text[endPos]) - if atStart && atEnd { - return true - } - idx = absPos + 1 - } -} - -func isAlpha(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') -} diff --git a/src/pkg/dashboard/inception_watcher_coverage_test.go b/src/pkg/dashboard/inception_watcher_coverage_test.go deleted file mode 100644 index c284c1e783..0000000000 --- a/src/pkg/dashboard/inception_watcher_coverage_test.go +++ /dev/null @@ -1,344 +0,0 @@ -package dashboard - -import ( - "context" - "io" - "log/slog" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/beads" - "github.com/hivecommons/hive/pkg/knowledge" -) - -func covFWatcherLogger() *slog.Logger { - return slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})) -} - -// covFWatcher builds an InceptionWatcher backed by a real bead store + engine -// so the bead-scanning and phase-advancing helpers can be exercised directly. -func covFWatcher(t *testing.T) (*InceptionWatcher, *knowledge.InceptionEngine, *beads.Store) { - t.Helper() - logger := covFWatcherLogger() - store, err := beads.NewStore(t.TempDir()) - if err != nil { - t.Fatalf("beads.NewStore: %v", err) - } - kapi := knowledge.NewKnowledgeAPI(nil, knowledge.KnowledgeConfig{}, logger) - eng := knowledge.NewInceptionEngine(t.TempDir(), kapi, logger) - // scheduler/agentMgr/governor left nil — the helpers we drive guard on them. - w := NewInceptionWatcher(store, eng, nil, nil, nil, logger) - w.ctx = context.Background() - return w, eng, store -} - -func TestCovF_NewInceptionWatcher(t *testing.T) { - w, _, _ := covFWatcher(t) - if w == nil { - t.Fatal("nil watcher") - } -} - -func TestCovF_ParseQuestionFromBdCreate(t *testing.T) { - w, _, _ := covFWatcher(t) - - // Valid bd create with a title. - q := w.parseQuestionFromBdCreate(`bd create --title "What database should we use?" --type advisory`) - if q == nil || q.Text != "What database should we use?" { - t.Fatalf("expected parsed question, got %+v", q) - } - - // Category inference from a keyword. - q = w.parseQuestionFromBdCreate(`bd create --title "Who are the primary users?" --actor brainstorm`) - if q == nil || q.Category != "users" { - t.Fatalf("expected category users, got %+v", q) - } - - // Clarification prefix stripped. - q = w.parseQuestionFromBdCreate(`bd create --title "Clarification: What language?"`) - if q == nil || q.Text != "What language?" { - t.Fatalf("expected prefix stripped, got %+v", q) - } - - // No --title match -> nil. - if got := w.parseQuestionFromBdCreate(`bd create --type advisory`); got != nil { - t.Fatalf("expected nil for no title, got %+v", got) - } - - // Template placeholder -> nil. - if got := w.parseQuestionFromBdCreate(`bd create --title "<fact title>"`); got != nil { - t.Fatalf("expected nil for placeholder, got %+v", got) - } - // Empty title -> nil. - if got := w.parseQuestionFromBdCreate(`bd create --title ""`); got != nil { - t.Fatalf("expected nil for empty title, got %+v", got) - } -} - -func TestCovF_IsTemplatePlaceholder(t *testing.T) { - cases := map[string]bool{ - "<anything>": true, - "<fact title>": true, - "your question here": true, - "Real question?": false, - "": false, - } - for in, want := range cases { - if got := isTemplatePlaceholder(in); got != want { - t.Errorf("isTemplatePlaceholder(%q)=%v want %v", in, got, want) - } - } -} - -func TestCovF_ContainsWordAndIsAlpha(t *testing.T) { - if !containsWord("this must work", "must") { - t.Error("expected containsWord to find whole word") - } - if containsWord("mustard is tasty", "must") { - t.Error("expected containsWord to reject substring inside a word") - } - if containsWord("nothing here", "xyz") { - t.Error("expected false for absent word") - } - if !isAlpha('a') || !isAlpha('Z') || isAlpha('1') || isAlpha(' ') { - t.Error("isAlpha misbehaving") - } -} - -func TestCovF_BuildInceptionKickMessage(t *testing.T) { - w, _, _ := covFWatcher(t) - - capture := &knowledge.InceptionState{Phase: knowledge.PhaseCapture, IdeaText: "capture idea"} - if msg := w.buildInceptionKickMessage(capture); msg == "" { - t.Fatal("empty capture kick message") - } - - structure := &knowledge.InceptionState{ - Phase: knowledge.PhaseStructure, - IdeaText: "structure idea", - IdeaSlug: "structure-idea", - Questions: []knowledge.Question{{ID: "q1", Text: "lang?"}}, - Answers: map[string]string{"q1": "Go"}, - } - if msg := w.buildInceptionKickMessage(structure); msg == "" { - t.Fatal("empty structure kick message") - } -} - -func TestCovF_FindAndCheckInceptionBeads(t *testing.T) { - w, eng, store := covFWatcher(t) - - // Start an inception so GetState() is non-nil (StartedAt in the past). - if _, err := eng.Start("a beadful idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - // Give StartedAt a small backdate so freshly-created beads count as "after". - time.Sleep(10 * time.Millisecond) - - // Create >=5 clarification question beads from the brainstorm actor. - for i := 0; i < 6; i++ { - b, err := store.Create("Clarification: question "+string(rune('A'+i)), beads.TypeAdvisory, beads.PriorityHigh, "brainstorm", "inception/idea") - if err != nil { - t.Fatalf("create bead: %v", err) - } - _ = store.SetMetadata(b.ID, "category", "general") - _ = store.SetMetadata(b.ID, "question_id", "q"+string(rune('A'+i))) - } - - found := w.findInceptionBeads() - if len(found) < 6 { - t.Fatalf("expected >=6 inception beads, got %d", len(found)) - } - - // checkForQuestions should extract >=5 and advance the engine to clarify. - w.checkForQuestions(found) - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseClarify { - t.Fatalf("expected clarify phase after checkForQuestions, got %+v", st) - } -} - -func TestCovF_CheckForFactsAdvances(t *testing.T) { - w, eng, store := covFWatcher(t) - - // Advance the engine to structure phase. - if _, err := eng.Start("a factful idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - if err := eng.SetQuestions([]knowledge.Question{{ID: "q1", Text: "lang?", Category: "language"}}); err != nil { - t.Fatalf("SetQuestions: %v", err) - } - if _, err := eng.SubmitAnswers(map[string]string{"q1": "Go"}); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - time.Sleep(10 * time.Millisecond) - - // Create >= targetFactCount fact beads so checkForFacts records + advances. - factTitles := []string{"Vision statement", "Constitution principles", "Requirement one", - "Requirement two", "Constraint one", "Stakeholder one", "Acceptance one", "Requirement three"} - for i, title := range factTitles { - b, err := store.Create(title, beads.TypeAdvisory, beads.PriorityHigh, "brainstorm", "inception/idea") - if err != nil { - t.Fatalf("create fact bead: %v", err) - } - ft := []string{"vision", "constitution", "requirement", "requirement", "constraint", "stakeholder", "acceptance", "requirement"}[i] - _ = store.SetMetadata(b.ID, "fact_type", ft) - _ = store.SetMetadata(b.ID, "fact_body", "body for "+title) - } - - found := w.findInceptionBeads() - w.checkForFacts(context.Background(), found) - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold phase after checkForFacts, got %+v", st) - } -} - -func TestCovF_ReapOldInceptionBeads(t *testing.T) { - w, eng, store := covFWatcher(t) - if _, err := eng.Start("reap idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - // Create a bead with the inception ref. - if _, err := store.Create("Clarification: old q", beads.TypeAdvisory, beads.PriorityHigh, "brainstorm", "inception/old"); err != nil { - t.Fatalf("create: %v", err) - } - // Reap everything created before "now + 1h" — should close the bead. - w.reapOldInceptionBeads(time.Now().Add(time.Hour)) -} - -func TestCovF_SupplementFactsFromQA(t *testing.T) { - w, _, _ := covFWatcher(t) - state := &knowledge.InceptionState{ - IdeaText: "supplement idea", - Questions: []knowledge.Question{ - {ID: "features", Text: "What features?", Category: "features"}, - {ID: "users", Text: "Who?", Category: "users"}, - }, - Answers: map[string]string{"features": "todo list", "users": "devs"}, - } - // No existing facts + no vision -> supplements a vision + one per answered Q. - out := w.supplementFactsFromQA(nil, state) - if len(out) < 3 { - t.Fatalf("expected supplemented facts, got %d", len(out)) - } -} - -func TestCovF_AutoGenerateQuestionsAndFacts(t *testing.T) { - w, eng, _ := covFWatcher(t) - - // autoGenerateQuestions: engine in capture with too few questions. - if _, err := eng.Start("build a python data tool"); err != nil { - t.Fatalf("Start: %v", err) - } - state := eng.GetState() - w.autoGenerateQuestions(state) - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseClarify { - t.Fatalf("expected clarify after autoGenerateQuestions, got %+v", st) - } - - // autoGenerateFacts: advance to structure, then auto-generate from Q&A. - if _, err := eng.SubmitAnswers(map[string]string{ - "language": "Python", "users": "analysts", "features": "charts", - "constraints": "fast", "testing": "pytest", - }); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - st := eng.GetState() - w.autoGenerateFacts(context.Background(), st) - if got := eng.GetState(); got == nil || got.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold after autoGenerateFacts, got %+v", got) - } -} - -func TestCovF_TryExtractFactsFromPluk(t *testing.T) { - w, eng, _ := covFWatcher(t) - // Advance to structure with answers so the fallback path has Q&A available. - if _, err := eng.Start("pluk extract idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - _ = eng.SetQuestions([]knowledge.Question{ - {ID: "language", Text: "lang?", Category: "language"}, - {ID: "features", Text: "features?", Category: "features"}, - }) - _, _ = eng.SubmitAnswers(map[string]string{"language": "Go", "features": "cli"}) - st := eng.GetState() - - // Seed buffered pluk fact lines with recognizable fact keywords. - w.plukMu.Lock() - w.plukFactLines = []string{ - "The vision is to build a fast todo CLI for developers", - "A key requirement is offline support for all commands", - "An important constraint is zero external dependencies here", - "Constitution: prefer the standard library over frameworks", - } - w.plukMu.Unlock() - - w.tryExtractFactsFromPluk(context.Background(), st) - // Either it extracted enough facts and advanced, or fell back to Q&A - // auto-generation (which also advances). Assert it left capture/structure. - if got := eng.GetState(); got == nil { - t.Fatal("nil state after tryExtractFactsFromPluk") - } -} - -func TestCovF_HandlePlukEvent(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("pluk event idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - - // raw_output during capture with a bd create question line -> buffered. - // #4285: the payload key is "line". This case used to pass "message", which - // the handler also read, so the arm ran on an empty string and this test - // covered the line without exercising anything. - w.handlePlukEvent(plukEvent{ - Type: "raw_output", - Data: map[string]string{"line": `bd create --title "Who are the users?" --actor brainstorm`}, - }) - - // state_change to working then idle. - w.handlePlukEvent(plukEvent{Type: "state_change", Data: map[string]string{"state": "working"}}) - w.handlePlukEvent(plukEvent{Type: "state_change", Data: map[string]string{"state": "idle"}}) - - // rate_limit + error + tool_call_completed events. - w.handlePlukEvent(plukEvent{Type: "rate_limit", Data: map[string]string{"message": "slow down"}}) - w.handlePlukEvent(plukEvent{Type: "error", Data: map[string]string{"message": "boom"}}) - w.handlePlukEvent(plukEvent{Type: "tool_call_completed"}) - time.Sleep(30 * time.Millisecond) // let any spawned poll goroutines run - - _ = eng -} - -func TestCovF_ApplyPlukQuestions(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("apply pluk questions idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - state := eng.GetState() - - // Fewer than the minimum -> no-op (early return). - w.plukMu.Lock() - w.plukQuestions = []knowledge.Question{{ID: "a", Text: "one?"}} - w.plukMu.Unlock() - w.applyPlukQuestions(state) - if st := eng.GetState(); st.Phase != knowledge.PhaseCapture { - t.Fatalf("expected still capture with too-few questions, got %s", st.Phase) - } - - // Enough unique questions -> advances to clarify. - w.plukMu.Lock() - w.plukQuestions = []knowledge.Question{ - {ID: "a", Text: "one?"}, {ID: "b", Text: "two?"}, {ID: "c", Text: "three?"}, - {ID: "d", Text: "four?"}, {ID: "e", Text: "five?"}, - } - w.plukMu.Unlock() - w.applyPlukQuestions(state) - if st := eng.GetState(); st.Phase != knowledge.PhaseClarify { - t.Fatalf("expected clarify after applyPlukQuestions, got %s", st.Phase) - } -} - -func TestCovF_PollNoState(t *testing.T) { - w, _, _ := covFWatcher(t) - // No inception started -> GetState nil -> poll resets counters and returns. - w.poll(context.Background()) -} diff --git a/src/pkg/dashboard/inception_watcher_loops_test.go b/src/pkg/dashboard/inception_watcher_loops_test.go deleted file mode 100644 index d0b1714d75..0000000000 --- a/src/pkg/dashboard/inception_watcher_loops_test.go +++ /dev/null @@ -1,217 +0,0 @@ -package dashboard - -import ( - "context" - "errors" - "os" - "path/filepath" - "strings" - "sync/atomic" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -type fakeInceptionAgentManager struct { - buffer []string - bufferErr error - sendErr error - restartErr error - sendCount atomic.Int64 - restartCount atomic.Int64 - lastKick string -} - -func (m *fakeInceptionAgentManager) GetBufferOutput(string, int) ([]string, error) { - return append([]string{}, m.buffer...), m.bufferErr -} - -func (m *fakeInceptionAgentManager) SendKick(_ string, message string) error { - m.sendCount.Add(1) - m.lastKick = message - return m.sendErr -} - -func (m *fakeInceptionAgentManager) RestartWithBootstrap(context.Context, string, string) error { - m.restartCount.Add(1) - return m.restartErr -} - -func withFastInceptionLoops(t *testing.T) { - t.Helper() - oldWatch, oldFast, oldPoll, oldSeek, oldLog := inceptionWatchIntervalS, inceptionFastPollInterval, plukSubscriberPollInterval, plukSubscriberSeekEnd, plukLogFile - inceptionWatchIntervalS = 10 * time.Millisecond - inceptionFastPollInterval = 10 * time.Millisecond - plukSubscriberPollInterval = 5 * time.Millisecond - plukSubscriberSeekEnd = false - plukLogFile = func() string { return filepath.Join(t.TempDir(), "missing.jsonl") } - t.Cleanup(func() { - inceptionWatchIntervalS, inceptionFastPollInterval, plukSubscriberPollInterval, plukSubscriberSeekEnd, plukLogFile = oldWatch, oldFast, oldPoll, oldSeek, oldLog - }) -} - -func TestInceptionWatcherRunPollsAndStopsOnCancel(t *testing.T) { - withFastInceptionLoops(t) - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("watcher loop idea"); err != nil { - t.Fatalf("Start: %v", err) - } - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - w.Run(ctx) - close(done) - }() - - deadline := time.Now().Add(time.Second) - for time.Now().Before(deadline) { - w.pollMu.Lock() - gotSlug := w.lastSlug != "" - w.pollMu.Unlock() - if gotSlug { - break - } - time.Sleep(5 * time.Millisecond) - } - cancel() - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("Run did not stop after context cancellation") - } - w.pollMu.Lock() - gotSlug := w.lastSlug - w.pollMu.Unlock() - if gotSlug == "" { - t.Fatal("Run never reached poll loop") - } -} - -func TestRunPlukSubscriberReadsConfiguredLogAndHandlesEvent(t *testing.T) { - withFastInceptionLoops(t) - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("pluk subscriber idea"); err != nil { - t.Fatalf("Start: %v", err) - } - logPath := filepath.Join(t.TempDir(), "brainstorm.jsonl") - line := `{"type":"raw_output","data":{"line":"bd create --title \"What language should we use?\""}}` + "\n" - if err := os.WriteFile(logPath, []byte(line), 0o644); err != nil { - t.Fatalf("write pluk log: %v", err) - } - plukLogFile = func() string { return logPath } - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - w.runPlukSubscriber(ctx) - close(done) - }() - - deadline := time.Now().Add(time.Second) - for time.Now().Before(deadline) { - w.plukMu.Lock() - gotEvent := w.plukEventCount > 0 - w.plukMu.Unlock() - if gotEvent { - break - } - time.Sleep(5 * time.Millisecond) - } - cancel() - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("runPlukSubscriber did not stop after context cancellation") - } - w.plukMu.Lock() - eventCount := w.plukEventCount - questions := append([]knowledge.Question(nil), w.plukQuestions...) - w.plukMu.Unlock() - if eventCount != 1 { - t.Fatalf("expected one handled pluk event, got %d", eventCount) - } - if len(questions) != 1 || !strings.Contains(questions[0].Text, "language") { - t.Fatalf("expected raw_output bd create question to be captured, got %+v", questions) - } -} - -func TestRetryKickIfStaleSendsKickWhenBrainstormIsReaping(t *testing.T) { - w, _, _ := covFWatcher(t) - fake := &fakeInceptionAgentManager{buffer: []string{"reap: close stale beads"}} - w.agentMgr = fake - state := &knowledge.InceptionState{ - Phase: knowledge.PhaseCapture, - IdeaText: "recover stale kick", - IdeaSlug: "recover-stale-kick", - StartedAt: time.Now().Add(-2 * kickRetryGracePeriodS), - } - w.lastKickRetry = time.Now().Add(-2 * kickRetryDelayS) - - w.retryKickIfStale(state) - - if fake.sendCount.Load() != 1 { - t.Fatalf("expected SendKick once, got %d", fake.sendCount.Load()) - } - if fake.restartCount.Load() != 0 { - t.Fatalf("unexpected RestartWithBootstrap calls: %d", fake.restartCount.Load()) - } - if w.kickRetryCount != 1 { - t.Fatalf("kickRetryCount = %d, want 1", w.kickRetryCount) - } - if !strings.Contains(fake.lastKick, "recover stale kick") { - t.Fatalf("kick message did not include idea text: %q", fake.lastKick) - } -} - -func TestRetryKickIfStaleFallsBackToBootstrapWhenSendKickFails(t *testing.T) { - w, _, _ := covFWatcher(t) - fake := &fakeInceptionAgentManager{ - bufferErr: errors.New("no session"), - sendErr: errors.New("send failed"), - } - w.agentMgr = fake - state := &knowledge.InceptionState{ - Phase: knowledge.PhaseStructure, - IdeaText: "recover missing session", - IdeaSlug: "recover-missing-session", - StartedAt: time.Now().Add(-2 * kickRetryGracePeriodS), - Questions: []knowledge.Question{{ID: "q1", Text: "language?", Category: "language"}}, - Answers: map[string]string{"q1": "Go"}, - } - w.lastKickRetry = time.Now().Add(-2 * kickRetryDelayS) - - w.retryKickIfStale(state) - - if fake.sendCount.Load() != 1 { - t.Fatalf("expected SendKick once, got %d", fake.sendCount.Load()) - } - if fake.restartCount.Load() != 1 { - t.Fatalf("expected RestartWithBootstrap once, got %d", fake.restartCount.Load()) - } -} - -func TestRetryKickIfStaleSuppressesWhileWorkingOrRateLimited(t *testing.T) { - w, _, _ := covFWatcher(t) - fake := &fakeInceptionAgentManager{buffer: []string{"extract requirements for inception"}} - w.agentMgr = fake - state := &knowledge.InceptionState{ - Phase: knowledge.PhaseCapture, - IdeaText: "do not kick", - StartedAt: time.Now().Add(-2 * kickRetryGracePeriodS), - } - w.lastKickRetry = time.Now().Add(-2 * kickRetryDelayS) - - w.retryKickIfStale(state) - if fake.sendCount.Load() != 0 { - t.Fatalf("working output should suppress kicks, got %d", fake.sendCount.Load()) - } - - fake.buffer = []string{"reap: close stale beads"} - w.rateLimitedUntil = time.Now().Add(time.Minute) - w.retryKickIfStale(state) - if fake.sendCount.Load() != 0 { - t.Fatalf("rate limit should suppress kicks, got %d", fake.sendCount.Load()) - } -} diff --git a/src/pkg/dashboard/inception_watcher_pluk_idle_test.go b/src/pkg/dashboard/inception_watcher_pluk_idle_test.go deleted file mode 100644 index 69b3d14481..0000000000 --- a/src/pkg/dashboard/inception_watcher_pluk_idle_test.go +++ /dev/null @@ -1,370 +0,0 @@ -package dashboard - -import ( - "context" - "encoding/json" - "errors" - "os" - "path/filepath" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// inception_watcher_pluk_idle_test.go covers the previously-untested arms of -// InceptionWatcher.handlePlukEvent: the nil-state early return, the -// idle-during-structure fallback to autoGenerateFacts, and the idle kick-retry -// path (success, SendKick failure, and the maxKickRetries cap). -// -// Deliberately NOT covered here: the idle-during-structure branch with -// buffered plukFactLines. handlePlukEvent holds plukMu when it calls -// tryExtractFactsFromPluk, which re-locks the same non-reentrant plukMu — -// a test driving that branch self-deadlocks. That defect is tracked in its -// own issue; a test pinning the fixed behaviour belongs with the fix. -// -// UPDATE (#7151): that deadlock is fixed — handlePlukEvent now calls -// tryExtractFactsFromPlukLocked — and the branch IS covered below, by -// TestPlukIdleInStructureExtractsBufferedFactLines. - -// plukIdleEvent is the state_change/idle event every retry-path test sends. -func plukIdleEvent() plukEvent { - return plukEvent{Type: "state_change", Data: map[string]string{"state": "idle"}} -} - -// fakeInceptionAgentMgr satisfies inceptionAgentManager and records SendKick -// calls on a channel so tests can join the re-kick goroutine without sleeps. -type fakeInceptionAgentMgr struct { - kickErr error - kicks chan string // receives the agent name per SendKick call -} - -func newFakeInceptionAgentMgr(kickErr error) *fakeInceptionAgentMgr { - return &fakeInceptionAgentMgr{kickErr: kickErr, kicks: make(chan string, 4)} -} - -func (f *fakeInceptionAgentMgr) GetBufferOutput(string, int) ([]string, error) { return nil, nil } -func (f *fakeInceptionAgentMgr) SendKick(name string, _ string) error { - f.kicks <- name - return f.kickErr -} -func (f *fakeInceptionAgentMgr) RestartWithBootstrap(context.Context, string, string) error { - return nil -} - -// structurePhaseWatcher builds a watcher whose engine is in the structure -// phase with the given questions answered, ready to drive the idle-in-structure -// branch of handlePlukEvent. -func structurePhaseWatcher(t *testing.T, questionCount int) (*InceptionWatcher, *knowledge.InceptionEngine) { - t.Helper() - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("structure idle fallback idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - questions := make([]knowledge.Question, 0, questionCount) - answers := make(map[string]string, questionCount) - for i := 0; i < questionCount; i++ { - id := string(rune('a' + i)) - questions = append(questions, knowledge.Question{ID: id, Text: "Question " + id + "?"}) - answers[id] = "Answer " + id - } - if err := eng.SetQuestions(questions); err != nil { - t.Fatalf("SetQuestions: %v", err) - } - if _, err := eng.SubmitAnswers(answers); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseStructure { - t.Fatalf("engine not in structure phase, state=%+v", eng.GetState()) - } - return w, eng -} - -// agedCaptureWatcher builds a watcher whose engine sits in the capture phase -// with StartedAt pushed past kickRetryGracePeriodS, by rewriting the persisted -// state file and reloading it through a fresh engine — the only supported way -// to age an inception, since GetState returns copies. -func agedCaptureWatcher(t *testing.T, mgr inceptionAgentManager) *InceptionWatcher { - t.Helper() - logger := covFWatcherLogger() - dataDir := t.TempDir() - kapi := knowledge.NewKnowledgeAPI(nil, knowledge.KnowledgeConfig{}, logger) - eng := knowledge.NewInceptionEngine(dataDir, kapi, logger) - if _, err := eng.Start("kick retry idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - - statePath := filepath.Join(dataDir, "inception", "state.json") - raw, err := os.ReadFile(statePath) - if err != nil { - t.Fatalf("reading persisted inception state: %v", err) - } - var st map[string]any - if err := json.Unmarshal(raw, &st); err != nil { - t.Fatalf("unmarshaling inception state: %v", err) - } - st["started_at"] = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) - aged, err := json.Marshal(st) - if err != nil { - t.Fatalf("marshaling aged state: %v", err) - } - if err := os.WriteFile(statePath, aged, 0o644); err != nil { - t.Fatalf("writing aged state: %v", err) - } - - agedEng := knowledge.NewInceptionEngine(dataDir, kapi, logger) - got := agedEng.GetState() - if got == nil || got.Phase != knowledge.PhaseCapture { - t.Fatalf("aged engine state = %+v, want capture phase", got) - } - if time.Since(got.StartedAt) <= kickRetryGracePeriodS { - t.Fatalf("aged StartedAt %v is still inside the %v grace period", got.StartedAt, kickRetryGracePeriodS) - } - - return &InceptionWatcher{ - inception: agedEng, - agentMgr: mgr, - logger: logger, - ctx: context.Background(), - } -} - -// TestPlukEventNilStateReturnsEarly pins the guard at the top of -// handlePlukEvent: with no inception in progress the event still counts as -// activity, but nothing below the guard runs — not even raw_output buffering. -func TestPlukEventNilStateReturnsEarly(t *testing.T) { - w, eng, _ := covFWatcher(t) - if st := eng.GetState(); st != nil { - t.Fatalf("expected nil inception state, got %+v", st) - } - - w.handlePlukEvent(plukEvent{ - Type: "raw_output", - Data: map[string]string{"line": `bd create --title "Should not be buffered" --actor brainstorm`}, - }) - - w.plukMu.Lock() - events, buffered := w.plukEventCount, len(w.plukBdCreateLines) - activity := w.plukLastActivity - w.plukMu.Unlock() - - if events != 1 { - t.Fatalf("plukEventCount = %d, want 1 — activity must be tracked before the state guard", events) - } - if activity.IsZero() { - t.Fatal("plukLastActivity not set — idle detection loses its signal when state is nil") - } - if buffered != 0 { - t.Fatalf("buffered %d bd create lines with nil state, want 0 — the nil-state guard did not return", buffered) - } -} - -// TestPlukIdleInStructureFallsBackToAutoFacts drives the idle-during-structure -// arm with no buffered fact lines: the watcher must mark plukIdleInStructure -// and immediately auto-generate facts from Q&A, which RecordFacts turns into a -// scaffold-phase advance (vision + 3 answered questions ≥ minFactsForAdvance). -func TestPlukIdleInStructureFallsBackToAutoFacts(t *testing.T) { - w, eng := structurePhaseWatcher(t, 3) - - w.handlePlukEvent(plukIdleEvent()) - - w.plukMu.Lock() - idleInStructure := w.plukIdleInStructure - w.plukMu.Unlock() - if !idleInStructure { - t.Fatal("plukIdleInStructure not set by an idle event during structure phase") - } - - st := eng.GetState() - if st == nil { - t.Fatal("inception state vanished") - } - if st.Phase != knowledge.PhaseScaffold { - t.Fatalf("phase = %s, want %s — autoGenerateFacts fallback did not record facts", st.Phase, knowledge.PhaseScaffold) - } - if st.AutoFactCount == 0 { - t.Fatal("AutoFactCount = 0, want > 0 — fallback facts were not counted as auto-generated") - } -} - -// TestPlukIdleInStructureExtractsBufferedFactLines pins the branch that used to -// self-deadlock (#7151): idle during structure phase WITH buffered fact lines. -// -// handlePlukEvent holds plukMu for its whole body and used to call -// tryExtractFactsFromPluk, which re-locked the same non-reentrant plukMu. The -// Pluk subscriber goroutine wedged permanently, taking idle detection, -// rate-limit tracking and bd-create interception down with it for the rest of -// the process. -// -// The call is made on its own goroutine and joined with a timeout so a -// regression fails this test in seconds with a clear message, rather than -// hanging the package until the go test binary's global timeout fires and -// dumps every goroutine in the process. -func TestPlukIdleInStructureExtractsBufferedFactLines(t *testing.T) { - w, eng := structurePhaseWatcher(t, 3) - - // Six distinct fact-type keywords, each over the 20-character minimum, so - // extraction clears minFactsForAdvance and takes the RecordFacts path - // rather than the insufficient-facts fallback to autoGenerateFacts. - w.plukMu.Lock() - w.plukFactLines = []string{ - "Vision: deliver a coherent knowledge base for the team", - "Constitution: every decision is written down and reviewable", - "Requirement: the watcher must survive an agent going idle", - "Constraint: no external services beyond the existing forge", - "Stakeholder: the on-call engineer who reads these facts first", - "Acceptance: the inception advances without manual intervention", - } - w.plukMu.Unlock() - - done := make(chan struct{}) - go func() { - defer close(done) - w.handlePlukEvent(plukIdleEvent()) - }() - - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("handlePlukEvent did not return within 10s — it self-deadlocked re-locking plukMu (#7151)") - } - - w.plukMu.Lock() - idleInStructure := w.plukIdleInStructure - remaining := w.plukFactLines - w.plukMu.Unlock() - - if !idleInStructure { - t.Fatal("plukIdleInStructure not set by an idle event during structure phase") - } - if remaining != nil { - t.Errorf("plukFactLines = %v, want nil — consumed lines must be cleared so they are not re-extracted", remaining) - } - - st := eng.GetState() - if st == nil { - t.Fatal("inception state vanished") - } - if st.AutoFactCount == 0 { - t.Fatal("AutoFactCount = 0, want > 0 — no facts were recorded from the buffered lines") - } -} - -// TestTryExtractFactsFromPlukWrapperTakesTheLock pins the other half of the -// #7151 split: the exported-style wrapper must still be safe for a caller that -// does NOT hold plukMu, since removing its locking entirely would trade a -// deadlock for a data race. -func TestTryExtractFactsFromPlukWrapperTakesTheLock(t *testing.T) { - w, _ := structurePhaseWatcher(t, 3) - - w.plukMu.Lock() - w.plukFactLines = []string{ - "Vision: deliver a coherent knowledge base for the team", - "Constitution: every decision is written down and reviewable", - "Requirement: the watcher must survive an agent going idle", - "Constraint: no external services beyond the existing forge", - "Stakeholder: the on-call engineer who reads these facts first", - "Acceptance: the inception advances without manual intervention", - } - w.plukMu.Unlock() - - done := make(chan struct{}) - go func() { - defer close(done) - // Called WITHOUT holding plukMu, as the coverage test does. - w.tryExtractFactsFromPluk(context.Background(), w.inception.GetState()) - }() - - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("tryExtractFactsFromPluk did not return within 10s") - } - - w.plukMu.Lock() - remaining := w.plukFactLines - w.plukMu.Unlock() - if remaining != nil { - t.Errorf("plukFactLines = %v, want nil — the wrapper must clear consumed lines too", remaining) - } -} -func TestPlukIdleKickRetriesAfterGracePeriod(t *testing.T) { - mgr := newFakeInceptionAgentMgr(nil) - w := agedCaptureWatcher(t, mgr) - - w.handlePlukEvent(plukIdleEvent()) - - select { - case name := <-mgr.kicks: - if name != "brainstorm" { - t.Fatalf("SendKick target = %q, want %q", name, "brainstorm") - } - case <-time.After(5 * time.Second): - t.Fatal("idle past the grace period in capture phase never re-kicked the agent") - } - - w.plukMu.Lock() - retries, lastRetry := w.kickRetryCount, w.lastKickRetry - w.plukMu.Unlock() - if retries != 1 { - t.Fatalf("kickRetryCount = %d, want 1", retries) - } - if lastRetry.IsZero() { - t.Fatal("lastKickRetry not stamped") - } -} - -// TestPlukIdleKickRetrySendFailureIsNonFatal pins the goroutine's error arm: -// a failing SendKick is logged and swallowed — the retry still counts, and the -// watcher keeps functioning for the next event. -func TestPlukIdleKickRetrySendFailureIsNonFatal(t *testing.T) { - mgr := newFakeInceptionAgentMgr(errors.New("tmux pane gone")) - w := agedCaptureWatcher(t, mgr) - - w.handlePlukEvent(plukIdleEvent()) - - select { - case <-mgr.kicks: - case <-time.After(5 * time.Second): - t.Fatal("re-kick goroutine never called SendKick") - } - - w.plukMu.Lock() - retries := w.kickRetryCount - w.plukMu.Unlock() - if retries != 1 { - t.Fatalf("kickRetryCount = %d, want 1 — a failed kick must still consume a retry", retries) - } - - // The watcher must survive the failure: the next idle event retries again. - w.handlePlukEvent(plukIdleEvent()) - select { - case <-mgr.kicks: - case <-time.After(5 * time.Second): - t.Fatal("watcher stopped retrying after a SendKick failure") - } -} - -// TestPlukIdleKickRetryStopsAtMaxRetries pins the retry cap: once -// kickRetryCount reaches maxKickRetries, an idle event must not kick again. -func TestPlukIdleKickRetryStopsAtMaxRetries(t *testing.T) { - mgr := newFakeInceptionAgentMgr(nil) - w := agedCaptureWatcher(t, mgr) - w.plukMu.Lock() - w.kickRetryCount = maxKickRetries - w.plukMu.Unlock() - - w.handlePlukEvent(plukIdleEvent()) - - w.plukMu.Lock() - retries := w.kickRetryCount - w.plukMu.Unlock() - if retries != maxKickRetries { - t.Fatalf("kickRetryCount = %d, want %d — the cap was ignored", retries, maxKickRetries) - } - select { - case <-mgr.kicks: - t.Fatal("SendKick called past maxKickRetries") - default: - } -} diff --git a/src/pkg/dashboard/inception_watcher_poll_fallback_test.go b/src/pkg/dashboard/inception_watcher_poll_fallback_test.go deleted file mode 100644 index a23a7f91a2..0000000000 --- a/src/pkg/dashboard/inception_watcher_poll_fallback_test.go +++ /dev/null @@ -1,217 +0,0 @@ -package dashboard - -import ( - "context" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// These tests pin the timing/fallback wiring inside InceptionWatcher.poll — -// the branches that decide WHEN autoGenerateQuestions/autoGenerateFacts fire. -// The helpers themselves are covered elsewhere; here we drive poll() with the -// watcher's timing fields set to each side of the thresholds. - -// pollWatcherInCapture starts an inception and aligns lastSlug so poll skips -// the slug-change reset (which would clobber the timing fields under test). -func pollWatcherInCapture(t *testing.T) (*InceptionWatcher, *knowledge.InceptionEngine) { - t.Helper() - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("build a python data tool"); err != nil { - t.Fatalf("Start: %v", err) - } - w.lastSlug = eng.GetState().IdeaSlug - return w, eng -} - -// pollWatcherInStructure advances the inception to the structure phase with -// enough answered questions for autoGenerateFacts to produce facts. -func pollWatcherInStructure(t *testing.T) (*InceptionWatcher, *knowledge.InceptionEngine) { - t.Helper() - w, eng := pollWatcherInCapture(t) - if err := eng.SetQuestions([]knowledge.Question{ - {ID: "language", Text: "lang?", Category: "language"}, - {ID: "users", Text: "who?", Category: "users"}, - {ID: "features", Text: "features?", Category: "features"}, - {ID: "constraints", Text: "constraints?", Category: "constraints"}, - {ID: "testing", Text: "testing?", Category: "testing"}, - }); err != nil { - t.Fatalf("SetQuestions: %v", err) - } - if _, err := eng.SubmitAnswers(map[string]string{ - "language": "Python", "users": "analysts", "features": "charts", - "constraints": "fast", "testing": "pytest", - }); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseStructure { - t.Fatalf("expected structure phase, got %+v", eng.GetState()) - } - return w, eng -} - -func setPlukLastActivity(w *InceptionWatcher, at time.Time) { - w.plukMu.Lock() - w.plukLastActivity = at - w.plukMu.Unlock() -} - -func TestPoll_NilEngineReturnsEarly(t *testing.T) { - w, _, _ := covFWatcher(t) - w.inception = nil - w.lastQuestionCount = 7 - w.poll(context.Background()) - if w.lastQuestionCount != 7 { - t.Fatal("nil-engine poll must not touch watcher state") - } -} - -func TestPoll_SlugChangeResetsTrackingState(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("slug change idea"); err != nil { - t.Fatalf("Start: %v", err) - } - - // Simulate a previous inception's residue. - w.lastSlug = "previous-inception" - w.lastQuestionCount = 9 - w.lastFactCount = 4 - w.kickRetryCount = 3 - w.plukMu.Lock() - w.plukFactLines = []string{"stale"} - w.plukLastActivity = time.Now().Add(-time.Hour) - w.plukMu.Unlock() - - w.poll(context.Background()) - - if w.lastSlug != eng.GetState().IdeaSlug { - t.Fatalf("lastSlug not adopted: %q", w.lastSlug) - } - if w.lastQuestionCount != 0 || w.lastFactCount != 0 || w.kickRetryCount != 0 { - t.Fatalf("counters not reset: q=%d f=%d retry=%d", - w.lastQuestionCount, w.lastFactCount, w.kickRetryCount) - } - if w.captureSeenAt.IsZero() { - t.Fatal("captureSeenAt must start on slug change") - } - w.plukMu.Lock() - defer w.plukMu.Unlock() - if w.plukFactLines != nil || !w.plukLastActivity.IsZero() { - t.Fatal("pluk buffers not cleared on slug change") - } -} - -func TestPoll_CaptureBootstrapTimeoutGeneratesQuestions(t *testing.T) { - w, eng := pollWatcherInCapture(t) - // Past 2x the fallback timeout with zero pluk activity: the agent never - // started, so the bootstrap branch must fire the question fallback. - w.captureSeenAt = time.Now().Add(-2*autoQuestionFallbackTimeout - time.Minute) - - w.poll(context.Background()) - - st := eng.GetState() - if st == nil || st.Phase != knowledge.PhaseClarify { - t.Fatalf("expected clarify after bootstrap fallback, got %+v", st) - } - if len(st.Questions) < minQuestionsForAdvance { - t.Fatalf("expected >=%d auto questions, got %d", minQuestionsForAdvance, len(st.Questions)) - } -} - -func TestPoll_CaptureBootstrapWithinGraceDefers(t *testing.T) { - w, eng := pollWatcherInCapture(t) - // Past the fallback timeout but NOT past 2x, with no pluk events yet: - // the agent may still be bootstrapping, so nothing fires. - w.captureSeenAt = time.Now().Add(-autoQuestionFallbackTimeout - 10*time.Second) - - w.poll(context.Background()) - - st := eng.GetState() - if st == nil || st.Phase != knowledge.PhaseCapture || len(st.Questions) != 0 { - t.Fatalf("expected capture with no questions, got %+v", st) - } -} - -func TestPoll_CaptureIdleAgentGeneratesQuestions(t *testing.T) { - w, eng := pollWatcherInCapture(t) - w.captureSeenAt = time.Now().Add(-autoQuestionFallbackTimeout - 10*time.Second) - // Agent produced output once, then went idle past the threshold. - setPlukLastActivity(w, time.Now().Add(-agentIdleThreshold-10*time.Second)) - - w.poll(context.Background()) - - st := eng.GetState() - if st == nil || st.Phase != knowledge.PhaseClarify { - t.Fatalf("expected clarify after idle fallback, got %+v", st) - } -} - -func TestPoll_CaptureActiveAgentDefers(t *testing.T) { - w, eng := pollWatcherInCapture(t) - w.captureSeenAt = time.Now().Add(-autoQuestionFallbackTimeout - 10*time.Second) - // Agent is actively producing output: fallback must keep waiting. - setPlukLastActivity(w, time.Now().Add(-time.Second)) - - w.poll(context.Background()) - - st := eng.GetState() - if st == nil || st.Phase != knowledge.PhaseCapture || len(st.Questions) != 0 { - t.Fatalf("expected capture with no questions, got %+v", st) - } -} - -func TestPoll_StructureFirstSightStampsSeenAt(t *testing.T) { - w, eng := pollWatcherInStructure(t) - if !w.structureSeenAt.IsZero() { - t.Fatal("precondition: structureSeenAt should start zero") - } - - w.poll(context.Background()) - - if w.structureSeenAt.IsZero() { - t.Fatal("first structure poll must stamp structureSeenAt") - } - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseStructure { - t.Fatalf("first sight must not generate facts yet, got %+v", st) - } -} - -func TestPoll_StructureBootstrapTimeoutGeneratesFacts(t *testing.T) { - w, eng := pollWatcherInStructure(t) - w.structureSeenAt = time.Now().Add(-2*autoFactFallbackTimeout - time.Minute) - - w.poll(context.Background()) - - st := eng.GetState() - if st == nil || st.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold after fact fallback, got %+v", st) - } - if len(st.FactSlugs) == 0 { - t.Fatal("expected auto-generated fact slugs") - } -} - -func TestPoll_StructureIdleAgentGeneratesFacts(t *testing.T) { - w, eng := pollWatcherInStructure(t) - w.structureSeenAt = time.Now().Add(-autoFactFallbackTimeout - 10*time.Second) - setPlukLastActivity(w, time.Now().Add(-agentIdleThreshold-10*time.Second)) - - w.poll(context.Background()) - - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseScaffold { - t.Fatalf("expected scaffold after idle fact fallback, got %+v", st) - } -} - -func TestPoll_StructureActiveAgentDefers(t *testing.T) { - w, eng := pollWatcherInStructure(t) - w.structureSeenAt = time.Now().Add(-autoFactFallbackTimeout - 10*time.Second) - setPlukLastActivity(w, time.Now().Add(-time.Second)) - - w.poll(context.Background()) - - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseStructure { - t.Fatalf("active agent must defer fact fallback, got %+v", st) - } -} diff --git a/src/pkg/dashboard/inception_watcher_test.go b/src/pkg/dashboard/inception_watcher_test.go deleted file mode 100644 index 5bf019b9ca..0000000000 --- a/src/pkg/dashboard/inception_watcher_test.go +++ /dev/null @@ -1,151 +0,0 @@ -package dashboard - -import ( - "testing" -) - -func TestInferFactType(t *testing.T) { - tests := []struct { - title string - want string - }{ - {"Project Vision Statement", "vision"}, - {"Core Purpose", "vision"}, - {"Project Goal", "vision"}, - {"Architecture Constitution", "constitution"}, - {"Code style principles", "constitution"}, - {"Key Requirement: Fast startup", "requirement"}, - {"Must support HTTPS", "requirement"}, - {"New Feature: Dashboard", "requirement"}, - {"Constraint: No external deps", "constraint"}, - {"System Boundary", "constraint"}, - {"Limitation on memory", "constraint"}, - {"Primary Stakeholder", "stakeholder"}, - {"Target User group", "stakeholder"}, - {"Target Audience", "stakeholder"}, - {"Acceptance Criteria", "acceptance"}, - {"Success Metric", "acceptance"}, - {"Test Coverage Target", "acceptance"}, - {"Some random title", ""}, - {"Clarification: this is just a question", ""}, - } - for _, tt := range tests { - got := inferFactType(tt.title) - if got != tt.want { - t.Errorf("inferFactType(%q) = %q, want %q", tt.title, got, tt.want) - } - } -} - -func TestParseQuestionTable(t *testing.T) { - lines := []string{ - "┌──────────┬──────────────────────────────┬─────────────┐", - "│ Category │ Question │ Default │", - "├──────────┼──────────────────────────────┼─────────────┤", - "│ language │ What language will you use? │ Go │", - "│ users │ Who are the primary users? │ developers │", - "│ features │ What must it do? │ │", - "└──────────┴──────────────────────────────┴─────────────┘", - } - - questions := parseQuestionTable(lines) - if len(questions) != 3 { - t.Fatalf("expected 3 questions, got %d", len(questions)) - } - if questions[0].Category != "language" { - t.Errorf("q0 category = %q", questions[0].Category) - } - if questions[0].Text != "What language will you use?" { - t.Errorf("q0 text = %q", questions[0].Text) - } - if questions[0].Default != "Go" { - t.Errorf("q0 default = %q", questions[0].Default) - } -} - -func TestParseQuestionTableEmpty(t *testing.T) { - questions := parseQuestionTable(nil) - if len(questions) != 0 { - t.Error("nil lines should return empty") - } -} - -func TestParseQuestionTableNoPipes(t *testing.T) { - lines := []string{ - "This is just regular text", - "No table formatting here", - } - questions := parseQuestionTable(lines) - if len(questions) != 0 { - t.Errorf("non-table lines should return empty, got %d", len(questions)) - } -} - -func TestParseQuestionTableDedup(t *testing.T) { - lines := []string{ - "│ language │ What language? │ Go │", - "│ language │ What language? │ Go │", - } - questions := parseQuestionTable(lines) - if len(questions) != 1 { - t.Errorf("duplicate questions should be deduped, got %d", len(questions)) - } -} - -func TestParseNumberedQuestions(t *testing.T) { - lines := []string{ - "1. Primary users — who will use this and how?", - "2. Must-have features — the 2-3 things it must do", - "3. Language — what programming language?", - "This is not a question", - "4. Testing — how should we verify it works?", - } - - questions := parseNumberedQuestions(lines) - if len(questions) < 3 { - t.Fatalf("expected at least 3 questions, got %d", len(questions)) - } -} - -func TestParseNumberedQuestionsBullets(t *testing.T) { - lines := []string{ - "- Primary users: who will use this?", - "- Features: what must it do?", - "* Language: what language?", - } - - questions := parseNumberedQuestions(lines) - if len(questions) < 2 { - t.Fatalf("expected at least 2 questions, got %d", len(questions)) - } -} - -func TestParseNumberedQuestionsEmpty(t *testing.T) { - questions := parseNumberedQuestions(nil) - if len(questions) != 0 { - t.Error("nil lines should return empty") - } -} - -func TestParseNumberedQuestionsDedup(t *testing.T) { - lines := []string{ - "1. Users — who uses this?", - "2. Users — who uses this?", - } - questions := parseNumberedQuestions(lines) - if len(questions) != 1 { - t.Errorf("duplicates should be deduped, got %d", len(questions)) - } -} - -func TestParseNumberedQuestionsBold(t *testing.T) { - lines := []string{ - "1. **Primary users** — who will use this?", - "2. **Features** — what must it do?", - } - - questions := parseNumberedQuestions(lines) - if len(questions) < 2 { - t.Fatalf("expected at least 2 bold questions, got %d", len(questions)) - } -} diff --git a/src/pkg/dashboard/kick_brainstorm_test.go b/src/pkg/dashboard/kick_brainstorm_test.go deleted file mode 100644 index fe3019b5ec..0000000000 --- a/src/pkg/dashboard/kick_brainstorm_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package dashboard - -import ( - "context" - "errors" - "log/slog" - "os" - "testing" - "time" - - "github.com/hivecommons/hive/pkg/scheduler" -) - -func TestKickBrainstormSendKickSuccessPath(t *testing.T) { - s, deps := apiServer(t) - deps.Scheduler = scheduler.New(deps.Config, deps.Logger) - done := make(chan struct{}) - var sent []string - s.kickBrainstormDoneFn = func() { close(done) } - s.kickBrainstormSendKickFn = func(name, msg string) error { - if name != "brainstorm" { - t.Fatalf("name = %q, want brainstorm", name) - } - sent = append(sent, msg) - return nil - } - - origDelay := kickBrainstormClearDelay - kickBrainstormClearDelay = 0 - t.Cleanup(func() { kickBrainstormClearDelay = origDelay }) - - s.kickBrainstorm() - waitForKickBrainstorm(t, done) - - if len(sent) != 2 { - t.Fatalf("sent %d messages, want clear plus kick: %#v", len(sent), sent) - } - if sent[0] != "/clear" { - t.Fatalf("first message = %q, want /clear", sent[0]) - } - if sent[1] == "" { - t.Fatal("second message is empty") - } -} - -func TestKickBrainstormFallsBackToRestart(t *testing.T) { - s, deps := apiServer(t) - deps.Scheduler = scheduler.New(deps.Config, deps.Logger) - done := make(chan struct{}) - restarted := make(chan string, 1) - s.kickBrainstormDoneFn = func() { close(done) } - s.kickBrainstormSendKickFn = func(name, msg string) error { - return errors.New("no running session") - } - s.kickBrainstormRestartFn = func(ctx context.Context, name, prompt string) error { - if name != "brainstorm" { - t.Fatalf("restart name = %q, want brainstorm", name) - } - restarted <- prompt - return nil - } - - s.kickBrainstorm() - waitForKickBrainstorm(t, done) - - select { - case prompt := <-restarted: - if prompt == "" { - t.Fatal("restart prompt is empty") - } - default: - t.Fatal("expected RestartWithBootstrap fallback") - } -} - -func TestKickBrainstormRecoversPanics(t *testing.T) { - s, deps := apiServer(t) - deps.Scheduler = scheduler.New(deps.Config, deps.Logger) - done := make(chan struct{}) - s.kickBrainstormDoneFn = func() { close(done) } - s.kickBrainstormSendKickFn = func(name, msg string) error { - panic("send failed hard") - } - s.logger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - - s.kickBrainstorm() - waitForKickBrainstorm(t, done) -} - -func waitForKickBrainstorm(t *testing.T, done <-chan struct{}) { - t.Helper() - const timeout = 2 * time.Second - select { - case <-done: - case <-time.After(timeout): - t.Fatal("kickBrainstorm goroutine did not finish") - } -} diff --git a/src/pkg/dashboard/minimal_server_test.go b/src/pkg/dashboard/minimal_server_test.go new file mode 100644 index 0000000000..33146175c9 --- /dev/null +++ b/src/pkg/dashboard/minimal_server_test.go @@ -0,0 +1,30 @@ +package dashboard + +import ( + "context" + "log/slog" + "testing" + + "github.com/hivecommons/hive/pkg/config" +) + +// newMinimalServer builds a Server with just enough Dependencies to register +// the API. (It used to live in the retired inception handler tests.) +func newMinimalServer(t *testing.T) *Server { + t.Helper() + cfg := &config.Config{ + Project: config.ProjectConfig{Org: "testorg", Name: "test", PrimaryRepo: "testrepo"}, + AgentRuntimeConfig: config.AgentRuntimeConfig{ + Agents: map[string]config.AgentConfig{}, + }, + } + srv := NewServer(0, slog.Default()) + srv.deps = &Dependencies{ + Config: cfg, + Logger: slog.Default(), + Ctx: context.Background(), + } + srv.RegisterAPI(srv.deps) + t.Cleanup(srv.CloseContributeHub) + return srv +} diff --git a/src/pkg/dashboard/owner_only_handlers_deny_test.go b/src/pkg/dashboard/owner_only_handlers_deny_test.go index 2dc33ccc7b..42f11d4c57 100644 --- a/src/pkg/dashboard/owner_only_handlers_deny_test.go +++ b/src/pkg/dashboard/owner_only_handlers_deny_test.go @@ -88,15 +88,6 @@ func TestV4OwnerOnlyHandlerGapsRejectUnverifiedOwners(t *testing.T) { {"governor thresholds", http.MethodPut, "/api/config/governor/thresholds", srv.handleGovernorThresholds}, {"governor trajectory", http.MethodPut, "/api/config/governor/trajectory", srv.handleGovernorTrajectory}, {"hive id set", http.MethodPut, "/api/hive-id", srv.handleHiveIDSet}, - {"inception answer", http.MethodPost, "/api/inception/answer", srv.handleInceptionAnswer}, - {"inception approve", http.MethodPost, "/api/inception/approve", srv.handleInceptionApprove}, - {"inception import", http.MethodPost, "/api/inception/import", srv.handleInceptionImport}, - {"inception record facts", http.MethodPost, "/api/inception/facts", srv.handleInceptionRecordFacts}, - {"inception rename wiki", http.MethodPost, "/api/inception/rename-wiki", srv.handleInceptionRenameWiki}, - {"inception reset", http.MethodPost, "/api/inception/reset", srv.handleInceptionReset}, - {"inception scan", http.MethodPost, "/api/inception/scan", srv.handleInceptionScan}, - {"inception set questions", http.MethodPost, "/api/inception/questions", srv.handleInceptionSetQuestions}, - {"inception start", http.MethodPost, "/api/inception/start", srv.handleInceptionStart}, {"knowledge agent scopes put", http.MethodPut, "/api/config/knowledge/agent-scopes", srv.handleKnowledgeAgentScopesPut}, {"knowledge connectors put", http.MethodPut, "/api/config/knowledge/connectors", srv.handleKnowledgeConnectorsPut}, {"knowledge pipeline get", http.MethodGet, "/api/config/knowledge/pipeline", srv.handleKnowledgePipelineGet}, diff --git a/src/pkg/dashboard/pluk_raw_output_key_test.go b/src/pkg/dashboard/pluk_raw_output_key_test.go deleted file mode 100644 index bed41a170c..0000000000 --- a/src/pkg/dashboard/pluk_raw_output_key_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package dashboard - -import ( - "testing" - - "github.com/hivecommons/hive/pkg/knowledge" -) - -// pluk_raw_output_key_test.go covers the third defect in kubestellar/hive#4285: -// handlePlukEvent read the raw_output text from data["message"], but pluk puts -// it on data["line"] and only there — classifier.js builds the event as -// createEvent(..., 'raw_output', { line }). "message" is a real pluk key, but it -// belongs to rate_limit and error. -// -// The consequence was total rather than partial: line came back "" for every -// raw_output event, the handler returned immediately, and every bd-create -// interception and keyword re-poll underneath it was unreachable. - -// TestPlukRawOutputReadsLineKey is the regression. A bd create line arriving on -// the key pluk actually uses must reach the buffer the capture phase parses. -func TestPlukRawOutputReadsLineKey(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("raw output key idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - - const bdCreate = `bd create --title "Who are the users?" --actor brainstorm` - w.handlePlukEvent(plukEvent{ - Type: "raw_output", - Data: map[string]string{"line": bdCreate}, - }) - - w.plukMu.Lock() - buffered := append([]string(nil), w.plukBdCreateLines...) - w.plukMu.Unlock() - - if len(buffered) == 0 { - t.Fatalf("#4285: a raw_output event carrying %q on the \"line\" key was dropped — "+ - "the handler is reading a key pluk does not set for this event type", bdCreate) - } - if buffered[0] != bdCreate { - t.Fatalf("buffered line = %q, want %q", buffered[0], bdCreate) - } -} - -// TestPlukRawOutputIgnoresMessageKey is the other half, and the one that keeps -// the fix from being quietly reverted into "read both keys". pluk never puts -// raw_output text on "message"; treating it as an alias would mean acting on -// rate_limit and error prose as though it were pane output — those events carry -// human-readable provider text, and "bd create --title" appearing inside an -// error message is not a bd create the agent ran. -func TestPlukRawOutputIgnoresMessageKey(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("message key idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - - w.handlePlukEvent(plukEvent{ - Type: "raw_output", - Data: map[string]string{"message": `bd create --title "Should not be read" --actor brainstorm`}, - }) - - w.plukMu.Lock() - buffered := len(w.plukBdCreateLines) - w.plukMu.Unlock() - - if buffered != 0 { - t.Fatalf("#4285: raw_output text was read from \"message\"; pluk only ever sets " + - "\"line\" for this event, and \"message\" belongs to rate_limit/error") - } -} - -// TestPlukRawOutputParsesQuestionsThroughTheLineKey walks the path end to end: -// enough bd create lines on the real key must actually populate the question -// list, which is the behaviour the capture phase depends on and which had been -// unreachable since the key mismatch was introduced. -func TestPlukRawOutputParsesQuestionsThroughTheLineKey(t *testing.T) { - w, eng, _ := covFWatcher(t) - if _, err := eng.Start("question parsing idea in go"); err != nil { - t.Fatalf("Start: %v", err) - } - if st := eng.GetState(); st == nil || st.Phase != knowledge.PhaseCapture { - t.Skipf("inception did not start in capture phase; nothing to drive") - } - - for _, title := range []string{ - "Who are the users?", - "What is the deployment target?", - "Which data must persist?", - } { - w.handlePlukEvent(plukEvent{ - Type: "raw_output", - Data: map[string]string{"line": `bd create --title "` + title + `" --actor brainstorm`}, - }) - } - - w.plukMu.Lock() - questions := len(w.plukQuestions) - buffered := len(w.plukBdCreateLines) - w.plukMu.Unlock() - - if buffered != 3 { - t.Fatalf("buffered %d bd create lines, want 3", buffered) - } - if questions == 0 { - t.Fatalf("#4285: no questions were parsed from bd create lines delivered on the " + - "\"line\" key — the capture-phase interception is still unreachable") - } -} diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index c2676bc7a1..1ece16290d 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -305,10 +305,6 @@ type Server struct { // terminal (job_terminal.go); zero values take in-cluster defaults. jobTerminal jobTerminalDeps - kickBrainstormSendKickFn func(name, msg string) error - kickBrainstormRestartFn func(ctx context.Context, name, prompt string) error - kickBrainstormDoneFn func() - // Sparkline histories, all backed by the generic timeSeries ring buffer // (see timeseries.go). Lazily constructed via the tokenSeries()/factSeries() // /costSeries() accessors so the zero-value Server needs no constructor diff --git a/src/pkg/dashboard/static-src/html/faq.html b/src/pkg/dashboard/static-src/html/faq.html index 09ad0b0e09..7886400b62 100644 --- a/src/pkg/dashboard/static-src/html/faq.html +++ b/src/pkg/dashboard/static-src/html/faq.html @@ -19,7 +19,7 @@ <h3 class="faq-group-title">Getting started (L1–L2)</h3> <details class="faq-q" id="faq-l1-l2"> <summary>What are L1 and L2 for?</summary> - <p><strong>L1 is inception; L2 is calibration.</strong> At L1 the <strong>brainstorm</strong> agent can turn a raw idea or existing repo into structured facts and a scaffold through the <code>/api/inception</code> workflow; it asks clarifying questions and stops when you approve. In the dashboard, the <strong>Inception (spek)</strong> section is where you work an idea interactively in a shared CLI-agent session. At L2 the hive watches your repo and records what it finds, but it does not open ordinary issues or PRs. See <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md" target="_blank" rel="noopener noreferrer">Inception</a> and the <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/acmm-policy-matrix.md" target="_blank" rel="noopener noreferrer">ACMM policy matrix</a>.</p> + <p><strong>L1 is inception; L2 is calibration.</strong> At L1 you work an idea interactively in the dashboard's <strong>Inception (spek)</strong> section, a shared CLI-agent session; the old <code>/api/inception</code> workflow was retired and now answers 410 Gone. The <strong>brainstorm</strong> agent proposes ideas as advisory beads. At L2 the hive watches your repo and records what it finds, but it does not open ordinary issues or PRs. See <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md" target="_blank" rel="noopener noreferrer">Inception</a> and the <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/acmm-policy-matrix.md" target="_blank" rel="noopener noreferrer">ACMM policy matrix</a>.</p> <p>The job at L2 is not to fix everything in the ledger. It is to decide whether you believe the hive's judgement: point your own local agent — <code>claude</code>, <code>bob</code>, or <code>copilot</code> — at the 🐝 Hive Advisory Report and ask whether the findings hold up before you give Hive more authority.</p> </details> diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 55b30aeeb8..1001b94aa4 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -9499,7 +9499,7 @@ <h3 class="faq-group-title">Getting started (L1–L2)</h3> <details class="faq-q" id="faq-l1-l2"> <summary>What are L1 and L2 for?</summary> - <p><strong>L1 is inception; L2 is calibration.</strong> At L1 the <strong>brainstorm</strong> agent can turn a raw idea or existing repo into structured facts and a scaffold through the <code>/api/inception</code> workflow; it asks clarifying questions and stops when you approve. In the dashboard, the <strong>Inception (spek)</strong> section is where you work an idea interactively in a shared CLI-agent session. At L2 the hive watches your repo and records what it finds, but it does not open ordinary issues or PRs. See <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md" target="_blank" rel="noopener noreferrer">Inception</a> and the <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/acmm-policy-matrix.md" target="_blank" rel="noopener noreferrer">ACMM policy matrix</a>.</p> + <p><strong>L1 is inception; L2 is calibration.</strong> At L1 you work an idea interactively in the dashboard's <strong>Inception (spek)</strong> section, a shared CLI-agent session; the old <code>/api/inception</code> workflow was retired and now answers 410 Gone. The <strong>brainstorm</strong> agent proposes ideas as advisory beads. At L2 the hive watches your repo and records what it finds, but it does not open ordinary issues or PRs. See <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/inception.md" target="_blank" rel="noopener noreferrer">Inception</a> and the <a href="https://github.com/hivecommons/hive/blob/v5/src/docs/acmm-policy-matrix.md" target="_blank" rel="noopener noreferrer">ACMM policy matrix</a>.</p> <p>The job at L2 is not to fix everything in the ledger. It is to decide whether you believe the hive's judgement: point your own local agent — <code>claude</code>, <code>bob</code>, or <code>copilot</code> — at the 🐝 Hive Advisory Report and ask whether the findings hold up before you give Hive more authority.</p> </details> diff --git a/src/pkg/hub/journey.go b/src/pkg/hub/journey.go index bb3e37380e..9e2e3e9d25 100644 --- a/src/pkg/hub/journey.go +++ b/src/pkg/hub/journey.go @@ -169,7 +169,7 @@ type acmmLevelInfo struct { // acmmLevels maps a level number to its name and a one-line summary of what // moving there entails. Kept in sync with src/pkg/config/packs/level-*.yaml. var acmmLevels = map[int]acmmLevelInfo{ - 1: {"Inception", "an interactive brainstorm agent turns ideas into structured facts and scaffolding, with every action human-approved"}, + 1: {"Inception", "Inception (spek) sessions turn ideas into specs and a starting project, with every action human-approved"}, 2: {"Advisory", "five agents publish advisory findings — still no GitHub writes"}, 3: {"Quality-Gated", "the quality agent starts opening issues and hold-gated PRs about testing gaps, and ci-maintainer joins to watch build health — nothing merges without you"}, 4: {"Security-Aware", "delivery agents file GitHub issues in their lanes and sec-check joins for vulnerabilities"}, diff --git a/src/pkg/knowledge/inception.go b/src/pkg/knowledge/inception.go deleted file mode 100644 index 89448a06da..0000000000 --- a/src/pkg/knowledge/inception.go +++ /dev/null @@ -1,3326 +0,0 @@ -package knowledge - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "log/slog" - "os" - "path/filepath" - "sort" - "strings" - "sync" - "time" -) - -const ( - inceptionStateFile = "inception/state.json" - ideaDefaultConf = 0.3 - visionDefaultConf = 0.6 - constDefaultConf = 0.9 - reqDefaultConf = 0.6 - constraintDefaultConf = 0.7 - stakeholderDefaultConf = 0.7 - acceptanceDefaultConf = 0.6 - brownfieldConfBoost = 0.15 - - maxSlugLen = 30 -) - -// InceptionEngine manages the Level 1 ideation workflow — from raw idea to -// structured KB facts and scaffold output. Supports both greenfield (new -// project) and brownfield (existing repo) modes. -type InceptionEngine struct { - dataDir string - api *KnowledgeAPI - mu sync.Mutex - state *InceptionState - logger *slog.Logger -} - -// NewInceptionEngine creates an engine that persists state under dataDir. -func NewInceptionEngine(dataDir string, api *KnowledgeAPI, logger *slog.Logger) *InceptionEngine { - if logger == nil { - logger = slog.New(slog.NewTextHandler(io.Discard, nil)) - } - e := &InceptionEngine{ - dataDir: dataDir, - api: api, - logger: logger, - } - e.loadState() - e.connectExistingVault() - return e -} - -// Start begins a greenfield inception — the user has an idea but no repo. -func (e *InceptionEngine) Start(rawIdea string) (*InceptionState, error) { - e.mu.Lock() - defer e.mu.Unlock() - - rawIdea = strings.TrimSpace(rawIdea) - if rawIdea == "" { - return nil, fmt.Errorf("idea text is required") - } - const maxIdeaLen = 4000 - if len(rawIdea) > maxIdeaLen { - return nil, fmt.Errorf("idea text must be at most %d characters", maxIdeaLen) - } - - if e.state != nil && e.state.Phase != PhaseComplete { - return nil, fmt.Errorf("inception already in progress (phase: %s) — reset first", e.state.Phase) - } - - slug := slugify("idea-" + truncateSlug(rawIdea)) - if len(slug) < 8 { - slug = slug + "-" + fmt.Sprintf("%d", time.Now().UnixMilli()%100000) - } - - // The local inception wiki works without an optional remote project layer. - if e.api != nil && e.api.clientForLayer(LayerProject) != nil { - ctx := context.Background() - err := e.api.CreateFact(ctx, CreateFactRequest{ - Title: rawIdea, - Body: rawIdea, - Type: string(FactIdea), - Tags: []string{"inception", "seed"}, - Layer: string(LayerProject), - Confidence: ideaDefaultConf, - }) - if err != nil { - e.logger.Warn("could not persist idea fact to KB layer (knowledge may not be configured)", "error", err) - } - } - - e.clearWikiVault() - - wikiName := slugify(truncateSlug(rawIdea)) + "-wiki" - - e.state = &InceptionState{ - Phase: PhaseCapture, - Mode: InceptionGreenfield, - IdeaText: rawIdea, - IdeaSlug: slug, - WikiName: wikiName, - FactSlugs: []string{slug}, - Questions: []Question{}, - Answers: make(map[string]string), - StartedAt: time.Now(), - } - - if err := e.saveState(); err != nil { - return nil, fmt.Errorf("persisting state: %w", err) - } - - e.logger.Info("inception started", - "mode", "greenfield", - "slug", slug, - ) - - return e.state, nil -} - -// StartBrownfield begins an inception against an existing repo. The guide -// agent will scan the repo and extract initial facts. -func (e *InceptionEngine) StartBrownfield(repoURL string) (*InceptionState, error) { - e.mu.Lock() - defer e.mu.Unlock() - - repoURL = strings.TrimSpace(repoURL) - if repoURL == "" { - return nil, fmt.Errorf("repo URL is required") - } - const maxRepoURLLen = 2000 - if len(repoURL) > maxRepoURLLen { - return nil, fmt.Errorf("repo URL must be at most %d characters", maxRepoURLLen) - } - if !strings.HasPrefix(repoURL, "https://") && !strings.HasPrefix(repoURL, "http://") { - return nil, fmt.Errorf("repo URL must start with https:// or http://") - } - - if e.state != nil && e.state.Phase != PhaseComplete { - return nil, fmt.Errorf("inception already in progress (phase: %s) — reset first", e.state.Phase) - } - - slug := slugify("scan-" + repoBaseName(repoURL)) - - e.clearWikiVault() - - wikiName := slugify(repoBaseName(repoURL)) + "-wiki" - - e.state = &InceptionState{ - Phase: PhaseCapture, - Mode: InceptionBrownfield, - IdeaText: "Brownfield scan: " + repoURL, - IdeaSlug: slug, - RepoURL: repoURL, - WikiName: wikiName, - FactSlugs: []string{}, - Questions: []Question{}, - Answers: make(map[string]string), - StartedAt: time.Now(), - } - - if err := e.saveState(); err != nil { - return nil, fmt.Errorf("persisting state: %w", err) - } - - e.logger.Info("inception started", - "mode", "brownfield", - "repo", repoURL, - "slug", slug, - ) - - return e.state, nil -} - -// SetQuestions records the clarification questions generated by the guide agent -// and advances the state to the clarify phase. -func (e *InceptionEngine) SetQuestions(questions []Question) error { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return fmt.Errorf("no inception in progress") - } - if e.state.Phase != PhaseCapture { - return fmt.Errorf("cannot set questions in phase %s — must be in capture phase", e.state.Phase) - } - - if len(questions) == 0 { - return fmt.Errorf("at least one question is required") - } - - seen := make(map[string]bool, len(questions)) - for _, q := range questions { - if q.ID == "" { - return fmt.Errorf("question ID is required") - } - if q.Text == "" { - return fmt.Errorf("question text is required for %q", q.ID) - } - if seen[q.ID] { - return fmt.Errorf("duplicate question ID: %q", q.ID) - } - seen[q.ID] = true - } - - e.state.Questions = questions - e.state.Phase = PhaseClarify - now := time.Now() - e.state.PhaseChangedAt = &now - - return e.saveState() -} - -// SubmitAnswers records user responses to clarification questions and advances -// to the structure phase. The scheduler will re-kick the guide agent with -// the answers injected. -func (e *InceptionEngine) SubmitAnswers(answers map[string]string) (*InceptionState, error) { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return nil, fmt.Errorf("no inception in progress") - } - // Accept answers in clarify or structure phase — the brainstorm agent - // can advance past clarify before the user submits, but the answers - // are still valuable context for the next kick. - if e.state.Phase != PhaseClarify && e.state.Phase != PhaseStructure { - return nil, fmt.Errorf("cannot submit answers in phase %s", e.state.Phase) - } - if len(answers) == 0 { - return nil, fmt.Errorf("at least one answer is required") - } - - // Validate answer keys match known question IDs - if len(e.state.Questions) > 0 { - qIDs := make(map[string]bool, len(e.state.Questions)) - for _, q := range e.state.Questions { - qIDs[q.ID] = true - } - for id, val := range answers { - if !qIDs[id] { - return nil, fmt.Errorf("answer key %q does not match any question ID", id) - } - if strings.TrimSpace(val) == "" { - return nil, fmt.Errorf("answer for %q is empty", id) - } - } - } - - for k, v := range answers { - e.state.Answers[k] = v - } - if e.state.Phase == PhaseClarify { - e.state.Phase = PhaseStructure - now := time.Now() - e.state.PhaseChangedAt = &now - } - - if err := e.saveState(); err != nil { - return nil, fmt.Errorf("persisting state: %w", err) - } - - e.logger.Info("inception answers submitted", - "answer_count", len(answers), - "mode", e.state.Mode, - ) - - return e.state, nil -} - -// RecordFacts records structured facts produced by the guide agent during the -// structure phase. Each fact is ingested into the project KB layer. -func (e *InceptionEngine) RecordFacts(ctx context.Context, facts []IdeationFact) error { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return fmt.Errorf("no inception in progress") - } - if e.state.Phase != PhaseStructure { - return fmt.Errorf("facts already recorded (phase: %s)", e.state.Phase) - } - - if len(facts) == 0 { - return fmt.Errorf("at least one fact is required") - } - - for _, f := range facts { - if !f.Type.IsIdeation() { - return fmt.Errorf("invalid ideation fact type: %q", f.Type) - } - if f.Title == "" { - return fmt.Errorf("fact title is required") - } - if f.Body == "" { - return fmt.Errorf("fact body is required for type %q", f.Type) - } - conf := defaultConfidence(f.Type) - if e.state.Mode == InceptionBrownfield { - conf += brownfieldConfBoost - if conf > 1.0 { - conf = 1.0 - } - } - - // Facts are also persisted to the local wiki below. Mirror remotely only - // when a project endpoint is configured. - if e.api == nil || e.api.clientForLayer(LayerProject) == nil { - slug := slugify(string(f.Type) + "-" + truncateSlug(f.Title)) - e.state.FactSlugs = append(e.state.FactSlugs, slug) - continue - } - - tags := make([]string, len(f.Tags)+1) - copy(tags, f.Tags) - tags[len(f.Tags)] = "inception" - err := e.api.CreateFact(ctx, CreateFactRequest{ - Title: f.Title, - Body: f.Body, - Type: string(f.Type), - Tags: tags, - Layer: string(LayerProject), - Confidence: conf, - }) - if err != nil { - e.logger.Warn("failed to record ideation fact", - "title", f.Title, - "type", f.Type, - "error", err, - ) - } - - slug := slugify(string(f.Type) + "-" + truncateSlug(f.Title)) - e.state.FactSlugs = append(e.state.FactSlugs, slug) - } - - e.state.Phase = PhaseScaffold - now := time.Now() - e.state.PhaseChangedAt = &now - - e.writeFactsToVault(facts) - - return e.saveState() -} - -const inceptionWikiDir = "inception-wiki" - -func (e *InceptionEngine) clearWikiVault() { - vaultDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(vaultDir) - if err != nil { - return - } - for _, entry := range entries { - _ = os.Remove(filepath.Join(vaultDir, entry.Name())) // best-effort; a leftover stale file is harmless, it gets overwritten or reindexed next write - } - if len(entries) > 0 { - e.logger.Info("inception wiki cleared on new start", "files", len(entries)) - if e.api != nil { - if err := e.api.ReindexVault(vaultDir); err != nil { - e.logger.Debug("reindex after wiki clear", "error", err) - } - } - } -} - -// writeFactsToVault writes each fact as a markdown file with YAML frontmatter -// into a local directory, then connects it as a KB vault so facts are available -// to all agents via ${KNOWLEDGE} priming. -func (e *InceptionEngine) writeFactsToVault(facts []IdeationFact) { - vaultDir := filepath.Join(e.dataDir, inceptionWikiDir) - if err := os.MkdirAll(vaultDir, 0o755); err != nil { - e.logger.Warn("failed to create inception wiki dir", "error", err) - return - } - - // Remove stale wiki files from previous inception before writing new ones. - if len(facts) > 0 { - if entries, err := os.ReadDir(vaultDir); err == nil && len(entries) > 0 { - for _, entry := range entries { - _ = os.Remove(filepath.Join(vaultDir, entry.Name())) // best-effort; a leftover stale file is harmless, it gets overwritten below - } - e.logger.Info("inception wiki cleared before write", "files", len(entries), "new_facts", len(facts)) - } - } - - usedSlugs := make(map[string]int) - for _, f := range facts { - slug := slugify(string(f.Type) + "-" + truncateSlug(f.Title)) - usedSlugs[slug]++ - if usedSlugs[slug] > 1 { - slug = fmt.Sprintf("%s-%d", slug, usedSlugs[slug]) - } - filename := slug + ".md" - - conf := defaultConfidence(f.Type) - tags := make([]string, len(f.Tags)+2) - copy(tags, f.Tags) - tags[len(f.Tags)] = "inception" - tags[len(f.Tags)+1] = string(f.Type) - - var content strings.Builder - content.WriteString("---\n") - fmt.Fprintf(&content, "title: \"%s\"\n", strings.ReplaceAll(singleLine(f.Title), `"`, `\"`)) - fmt.Fprintf(&content, "type: %s\n", string(f.Type)) - fmt.Fprintf(&content, "confidence: %.2f\n", conf) - if len(tags) > 0 { - quoted := make([]string, len(tags)) - for i, t := range tags { - quoted[i] = fmt.Sprintf("%q", t) - } - fmt.Fprintf(&content, "tags: [%s]\n", strings.Join(quoted, ", ")) - } - content.WriteString("---\n\n") - content.WriteString(f.Body) - - path := filepath.Join(vaultDir, filename) - tmpWiki := path + ".tmp" - if err := os.WriteFile(tmpWiki, []byte(content.String()), 0o644); err != nil { - e.logger.Warn("failed to write inception fact file", "path", path, "error", err) - continue - } - if err := os.Rename(tmpWiki, path); err != nil { - e.logger.Warn("failed to rename inception fact file", "path", path, "error", err) - } - } - - if e.api != nil { - if err := e.api.ConnectVault(vaultDir, "inception-wiki"); err != nil { - if strings.Contains(err.Error(), "already connected") { - // Vault exists — reindex to pick up new files - if err := e.api.ReindexVault(vaultDir); err != nil { - e.logger.Warn("failed to reindex inception wiki", "error", err) - } else { - e.logger.Info("inception wiki reindexed", "dir", vaultDir, "facts", len(facts)) - } - } else { - e.logger.Warn("failed to connect inception wiki", "error", err) - } - } else { - e.logger.Info("inception wiki connected as knowledge source", - "dir", vaultDir, - "facts", len(facts), - ) - } - } -} - -// connectExistingVault checks if inception facts were previously written to disk -// and reconnects the vault on startup (survives container restarts). -func (e *InceptionEngine) connectExistingVault() { - if e.api == nil { - return - } - vaultDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(vaultDir) - if err != nil || len(entries) == 0 { - return - } - wikiName := "inception-wiki" - if e.state != nil && e.state.WikiName != "" { - wikiName = e.state.WikiName - } - if err := e.api.ConnectVault(vaultDir, wikiName); err != nil { - if !strings.Contains(err.Error(), "already connected") { - e.logger.Warn("failed to reconnect inception wiki on startup", "error", err) - } - } else { - e.logger.Info("inception wiki reconnected on startup", - "dir", vaultDir, - "name", wikiName, - "files", len(entries), - ) - } -} - -// IdeationFact is the input for recording a new ideation fact from the guide agent. -type IdeationFact struct { - Title string `json:"title"` - Body string `json:"body"` - Type FactType `json:"type"` - Tags []string `json:"tags"` -} - -// ProduceScaffold generates bootstrap files from the structured facts. For -// greenfield, this is a full project skeleton. For brownfield, only missing -// files are generated. -func (e *InceptionEngine) ProduceScaffold(ctx context.Context) (*ScaffoldResult, error) { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return nil, fmt.Errorf("no inception in progress") - } - - facts := e.gatherFacts(ctx) - - factTypes := make(map[string]int) - for _, f := range facts { - factTypes[string(f.Type)]++ - } - e.logger.Info("ProduceScaffold called", - "phase", e.state.Phase, - "facts_gathered", len(facts), - "fact_slugs", len(e.state.FactSlugs), - "fact_types", factTypes, - "idea", e.state.IdeaText[:min(40, len(e.state.IdeaText))], - ) - - result := &ScaffoldResult{} - - vision := findFactByType(facts, FactVision) - constitution := findFactByType(facts, FactConstitution) - requirements := filterFactsByType(facts, FactRequirement) - constraints := filterFactsByType(facts, FactConstraint) - acceptance := filterFactsByType(facts, FactAcceptance) - stakeholders := filterFactsByType(facts, FactStakeholder) - - lang := inferLanguage(constitution) - // Cross-check: if the idea text explicitly names a language and the - // constitution disagrees, trust the idea text — the agent may have - // produced a constitution that doesn't match the user's intent. - if e.state != nil && e.state.IdeaText != "" { - ideaLang := inferLanguageFromText(e.state.IdeaText) - if ideaLang != "" && ideaLang != lang { - e.logger.Info("scaffold language cross-check override", "idea_lang", ideaLang, "constitution_lang", lang, "idea", e.state.IdeaText[:min(50, len(e.state.IdeaText))]) - lang = ideaLang - } - } - projectName := inferProjectName(vision, e.state) - - // Core documentation - result.Files = append(result.Files, ScaffoldFile{ - Path: "README.md", - Content: buildReadme(projectName, lang, e.state.IdeaText, vision, constitution, requirements, constraints, stakeholders), - Purpose: "readme", - IsNew: true, - }) - - result.Files = append(result.Files, ScaffoldFile{ - Path: "AGENTS.md", - Content: buildAgentsMD(constitution, constraints, requirements, vision), - Purpose: "agents_md", - IsNew: true, - }) - - result.Files = append(result.Files, ScaffoldFile{ - Path: "CONTRIBUTING.md", - Content: buildContributing(projectName, lang, constitution), - Purpose: "contributing", - IsNew: true, - }) - - result.Files = append(result.Files, ScaffoldFile{ - Path: "CLAUDE.md", - Content: buildClaudeMD(lang, constitution, constraints), - Purpose: "claude_md", - IsNew: true, - }) - - // CI/CD — multi-tiered: PR checks, nightly full suite - result.Files = append(result.Files, ScaffoldFile{ - Path: ".github/workflows/ci.yml", - Content: buildCIConfig(lang), - Purpose: "ci", - IsNew: true, - }) - result.Files = append(result.Files, ScaffoldFile{ - Path: ".github/workflows/nightly.yml", - Content: buildNightlyCI(lang), - Purpose: "nightly_ci", - IsNew: true, - }) - - // Git - result.Files = append(result.Files, ScaffoldFile{ - Path: ".gitignore", - Content: buildGitignore(lang), - Purpose: "gitignore", - IsNew: true, - }) - - // Language-specific project files + code stubs - switch lang { - case "go": - result.Files = append(result.Files, - ScaffoldFile{Path: "go.mod", Content: buildGoMod(projectName), Purpose: "go_mod", IsNew: true}, - ScaffoldFile{Path: "main.go", Content: buildGoMain(projectName, vision), Purpose: "main", IsNew: true}, - ScaffoldFile{Path: "cmd/root.go", Content: buildGoCmdRoot(projectName, vision), Purpose: "cmd", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "main_test.go", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "python": - result.Files = append(result.Files, - ScaffoldFile{Path: "pyproject.toml", Content: buildPyprojectToml(projectName, vision), Purpose: "pyproject", IsNew: true}, - ScaffoldFile{Path: "src/" + pyPackageName(projectName) + "/__init__.py", Content: buildPyInit(projectName, vision), Purpose: "main", IsNew: true}, - ScaffoldFile{Path: "src/" + pyPackageName(projectName) + "/cli.py", Content: buildPyCLI(projectName, vision), Purpose: "cmd", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "tests/test_acceptance.py", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "typescript": - result.Files = append(result.Files, - ScaffoldFile{Path: "package.json", Content: buildPackageJSON(projectName, vision), Purpose: "package_json", IsNew: true}, - ScaffoldFile{Path: "tsconfig.json", Content: buildTSConfig(), Purpose: "tsconfig", IsNew: true}, - ScaffoldFile{Path: "src/index.ts", Content: buildTSIndex(projectName, vision), Purpose: "main", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "src/__tests__/acceptance.test.ts", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "javascript": - result.Files = append(result.Files, - ScaffoldFile{Path: "package.json", Content: buildJSPackageJSON(projectName, vision), Purpose: "package_json", IsNew: true}, - ScaffoldFile{Path: "src/index.js", Content: buildJSIndex(projectName, vision), Purpose: "main", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "src/__tests__/acceptance.test.js", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "rust": - result.Files = append(result.Files, - ScaffoldFile{Path: "Cargo.toml", Content: buildCargoToml(projectName, vision), Purpose: "cargo_toml", IsNew: true}, - ScaffoldFile{Path: "src/main.rs", Content: buildRustMain(projectName, vision), Purpose: "main", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "tests/acceptance.rs", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "java": - result.Files = append(result.Files, - ScaffoldFile{Path: "pom.xml", Content: buildPomXml(projectName, vision), Purpose: "pom", IsNew: true}, - ScaffoldFile{Path: "src/main/java/App.java", Content: buildJavaMain(projectName, vision), Purpose: "main", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "src/test/java/AppTest.java", Content: buildTestStubs(acceptance, lang), Purpose: "test_stub", IsNew: true, - }) - } - case "shell": - result.Files = append(result.Files, - ScaffoldFile{Path: projectName + ".sh", Content: buildShellMain(projectName, vision), Purpose: "main", IsNew: true}, - ) - if len(acceptance) > 0 { - result.Files = append(result.Files, ScaffoldFile{ - Path: "test.sh", Content: buildShellTestStubs(deduplicateFactTitles(acceptance)), Purpose: "test_stub", IsNew: true, - }) - } - } - - projectType := inferProjectType(constitution, requirements, vision) - - // Makefile - result.Files = append(result.Files, ScaffoldFile{ - Path: "Makefile", - Content: buildMakefile(lang, projectName, projectType), - Purpose: "makefile", - IsNew: true, - }) - - // Project-type-specific files - if projectType == "container" || projectType == "kubernetes" { - result.Files = append(result.Files, ScaffoldFile{ - Path: "Dockerfile", Content: buildDockerfile(lang, projectName), Purpose: "dockerfile", IsNew: true, - }) - } - - if projectType == "ui" { - i18nIdx, i18nPath := buildI18nIndexForLang(lang) - result.Files = append(result.Files, - ScaffoldFile{Path: "src/i18n/en.json", Content: buildI18nFile("en", projectName), Purpose: "i18n", IsNew: true}, - ScaffoldFile{Path: "src/i18n/es.json", Content: buildI18nFile("es", projectName), Purpose: "i18n", IsNew: true}, - ScaffoldFile{Path: i18nPath, Content: i18nIdx, Purpose: "i18n", IsNew: true}, - ) - } - - if projectType == "kubernetes" { - result.Files = append(result.Files, - ScaffoldFile{Path: "deploy/kustomization.yaml", Content: buildKustomization(), Purpose: "kustomize", IsNew: true}, - ScaffoldFile{Path: "deploy/base/deployment.yaml", Content: buildK8sDeployment(projectName), Purpose: "k8s_deployment", IsNew: true}, - ScaffoldFile{Path: "deploy/base/service.yaml", Content: buildK8sService(projectName), Purpose: "k8s_service", IsNew: true}, - ScaffoldFile{Path: "deploy/base/configmap.yaml", Content: buildK8sConfigMap(projectName), Purpose: "k8s_configmap", IsNew: true}, - ScaffoldFile{Path: "deploy/base/secret.yaml", Content: buildK8sSecret(projectName), Purpose: "k8s_secret", IsNew: true}, - ScaffoldFile{Path: "deploy/base/kustomization.yaml", Content: buildK8sBaseKustomization(), Purpose: "kustomize_base", IsNew: true}, - ScaffoldFile{Path: "deploy/overlays/dev/kustomization.yaml", Content: buildK8sOverlayKustomization(projectName, "dev"), Purpose: "kustomize_dev", IsNew: true}, - ScaffoldFile{Path: "deploy/overlays/prod/kustomization.yaml", Content: buildK8sOverlayKustomization(projectName, "prod"), Purpose: "kustomize_prod", IsNew: true}, - ) - } - - e.logger.Info("ProduceScaffold complete", - "files", len(result.Files), - "lang", lang, - "project_type", inferProjectType(constitution, requirements, vision), - ) - return result, nil -} - -// AdvanceToComplete marks the inception as complete (scaffold approved). -func (e *InceptionEngine) AdvanceToComplete() error { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return fmt.Errorf("no inception in progress") - } - if e.state.Phase != PhaseScaffold && e.state.Phase != PhaseComplete { - return fmt.Errorf("cannot approve in phase %s — must be in scaffold phase", e.state.Phase) - } - - e.state.Phase = PhaseComplete - now := time.Now() - e.state.PhaseChangedAt = &now - e.logger.Info("inception complete", - "mode", e.state.Mode, - "facts", len(e.state.FactSlugs), - ) - return e.saveState() -} - -// GetState returns the current inception state, or nil if none is in progress. -func (e *InceptionEngine) GetState() *InceptionState { - e.mu.Lock() - defer e.mu.Unlock() - if e.state == nil { - return nil - } - cp := *e.state - if e.state.Questions != nil { - cp.Questions = append([]Question{}, e.state.Questions...) - } - if e.state.FactSlugs != nil { - cp.FactSlugs = append([]string{}, e.state.FactSlugs...) - } else { - cp.FactSlugs = []string{} - } - cp.Answers = make(map[string]string, len(e.state.Answers)) - for k, v := range e.state.Answers { - cp.Answers[k] = v - } - if e.state.PhaseChangedAt != nil { - t := *e.state.PhaseChangedAt - cp.PhaseChangedAt = &t - } - return &cp -} - -// InceptionCampaignArchive is the durable snapshot created before an inception -// reset so New Inception never discards the session that just finished. -type InceptionCampaignArchive struct { - ID string `json:"id"` - Title string `json:"title,omitempty"` - Source string `json:"source,omitempty"` - Repos []string `json:"repos,omitempty"` - Engine string `json:"engine"` - Type string `json:"type"` - RevisionOf string `json:"revision_of,omitempty"` - Revision int `json:"revision,omitempty"` - // RecheckInterval is the per-campaign continuous-convergence override. - RecheckInterval time.Duration `json:"recheck_interval,omitempty"` - Recheck *CampaignRecheck `json:"recheck,omitempty"` - Drift *CampaignDrift `json:"drift,omitempty"` - Lease *CampaignLease `json:"lease,omitempty"` - ArchivedAt time.Time `json:"archived_at"` - State *InceptionState `json:"state"` - WikiFiles []string `json:"wiki_files,omitempty"` -} - -// CampaignRecheck records continuous-convergence cadence state for a campaign. -type CampaignRecheck struct { - Enabled bool `json:"enabled"` - Interval time.Duration `json:"interval,omitempty"` - LastAt time.Time `json:"last_at,omitempty"` - LastDeltaCount int `json:"last_delta_count,omitempty"` -} - -// CampaignDriftSource is a bounded, untrusted discovery snapshot, not an instruction. -type CampaignDriftSource struct { - Name string `json:"name"` - Kind string `json:"kind"` - URL string `json:"url"` - SHA256 string `json:"sha256,omitempty"` - Evidence string `json:"evidence,omitempty"` - Error string `json:"error,omitempty"` -} - -// CampaignDrift records the evidence attached to a Spek recheck revision. -type CampaignDrift struct { - DriftSource []CampaignDriftSource `json:"drift_source,omitempty"` - CodebaseChanged bool `json:"codebase_changed"` - PriorHeadSHA string `json:"prior_head_sha,omitempty"` - CurrentHeadSHA string `json:"current_head_sha,omitempty"` - PriorRevision string `json:"prior_revision,omitempty"` - DeltaCount int `json:"delta_count"` - RecheckReason string `json:"recheck_reason,omitempty"` - External []CampaignExternalEvidence `json:"external,omitempty"` - ExternalCount int `json:"external_count,omitempty"` - SourcesFailed []CampaignSourceFailure `json:"sources_failed,omitempty"` -} - -type CampaignExternalEvidence struct { - Source string `json:"source"` - Kind string `json:"kind"` - Title string `json:"title"` - URL string `json:"url,omitempty"` - PublishedAt time.Time `json:"published_at,omitempty"` - Summary string `json:"summary,omitempty"` -} - -type CampaignSourceFailure struct { - Name string `json:"name"` - Reason string `json:"reason"` -} - -// CampaignLease is the dashboard-level lock that prevents two operators from -// resuming the same durable campaign at once. -type CampaignLease struct { - Owner string `json:"owner"` - Surface string `json:"surface,omitempty"` - AcquiredAt time.Time `json:"acquired_at"` - ExpiresAt time.Time `json:"expires_at"` -} - -const ( - inceptionCampaignsDir = "inception/campaigns" - inceptionArchiveState = "state.json" - inceptionArchiveWiki = "wiki" - campaignLeaseTTL = 24 * time.Hour -) - -var ( - ErrCampaignLeaseHeld = errors.New("campaign lease held by another user") - ErrCampaignNoLease = errors.New("campaign has no active lease") -) - -// ArchiveCurrentCampaign snapshots the current inception state and wiki files -// under a stable campaign id (the inception idea/spec slug). A nil current -// state is a no-op. -func (e *InceptionEngine) ArchiveCurrentCampaign() (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - if e.state == nil { - return nil, nil - } - archive := e.archiveFromStateLocked(time.Now()) - if err := e.writeArchiveLocked(archive); err != nil { - return nil, err - } - e.logger.Info("inception campaign archived", "campaign", archive.ID, "phase", archive.State.Phase) - return archive, nil -} - -// ListCampaignArchives returns all archived inception campaign snapshots. -func (e *InceptionEngine) ListCampaignArchives() ([]InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - root := filepath.Join(e.dataDir, inceptionCampaignsDir) - entries, err := os.ReadDir(root) - if err != nil { - if os.IsNotExist(err) { - return []InceptionCampaignArchive{}, nil - } - return nil, err - } - archives := make([]InceptionCampaignArchive, 0, len(entries)) - for _, entry := range entries { - if !entry.IsDir() { - continue - } - archive, err := e.readArchiveLocked(entry.Name()) - if err != nil { - e.logger.Warn("skipping corrupt inception campaign archive", "campaign", entry.Name(), "error", err) - continue - } - archives = append(archives, archive) - } - sort.Slice(archives, func(i, j int) bool { return archives[i].ArchivedAt.After(archives[j].ArchivedAt) }) - return archives, nil -} - -// LoadCampaignArchive returns one archived inception campaign snapshot. -func (e *InceptionEngine) LoadCampaignArchive(id string) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - return &archive, nil -} - -// LeaseCampaignArchive records a resumable campaign lease for owner. The same -// owner may refresh their lease; another owner must wait until release/expiry. -func (e *InceptionEngine) LeaseCampaignArchive(id, owner, surface string, now time.Time) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - owner = strings.TrimSpace(owner) - if owner == "" { - owner = "local" - } - if now.IsZero() { - now = time.Now() - } - if archive.Lease != nil && archive.Lease.Owner != "" && archive.Lease.Owner != owner && now.Before(archive.Lease.ExpiresAt) { - return nil, fmt.Errorf("%w: %s", ErrCampaignLeaseHeld, archive.Lease.Owner) - } - archive.Lease = &CampaignLease{Owner: owner, Surface: strings.TrimSpace(surface), AcquiredAt: now, ExpiresAt: now.Add(campaignLeaseTTL)} - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return &archive, nil -} - -// ReleaseCampaignArchive clears owner’s active campaign lease. -func (e *InceptionEngine) ReleaseCampaignArchive(id, owner string, now time.Time) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - owner = strings.TrimSpace(owner) - if owner == "" { - owner = "local" - } - if now.IsZero() { - now = time.Now() - } - if archive.Lease == nil || archive.Lease.Owner == "" || now.After(archive.Lease.ExpiresAt) { - archive.Lease = nil - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return nil, ErrCampaignNoLease - } - if archive.Lease.Owner != owner { - return nil, fmt.Errorf("%w: %s", ErrCampaignLeaseHeld, archive.Lease.Owner) - } - archive.Lease = nil - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return &archive, nil -} - -// ReviseCampaignArchive branches a shipped/parked campaign into a new revision -// linked to the previous campaign instead of starting from a blank session. -func (e *InceptionEngine) ReviseCampaignArchive(id, owner string, now time.Time) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - base, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - if now.IsZero() { - now = time.Now() - } - rootID := strings.TrimSpace(base.RevisionOf) - if rootID == "" { - rootID = base.ID - } - next := base.Revision + 1 - if next <= 1 { - next = 2 - } - var revisionID string - for { - revisionID = slugify(fmt.Sprintf("%s-rev-%d", rootID, next)) - if _, err := e.readArchiveLocked(revisionID); err != nil { - break - } - next++ - } - revision := base - revision.ID = revisionID - revision.RevisionOf = base.ID - revision.Revision = next - revision.ArchivedAt = now - revision.Lease = &CampaignLease{Owner: campaignOwner(owner), Surface: "revise", AcquiredAt: now, ExpiresAt: now.Add(campaignLeaseTTL)} - if revision.State != nil { - revision.State = copyInceptionState(revision.State) - revision.State.IdeaSlug = revisionID - revision.State.Phase = PhaseCapture - revision.State.PhaseChangedAt = &now - } - if err := e.copyArchiveWikiLocked(base.ID, revision.ID); err != nil { - return nil, err - } - if err := e.writeArchiveStateLocked(&revision); err != nil { - return nil, err - } - return &revision, nil -} - -// ReviseExternalCampaign records a new durable revision for a non-Inception -// campaign whose artifacts live in an external Spektacular backend. -func (e *InceptionEngine) ReviseExternalCampaign(id, title, source, engine, campaignType, owner string, repos []string, now time.Time) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - id = slugify(strings.TrimSpace(id)) - if id == "" { - return nil, fmt.Errorf("campaign id required") - } - if now.IsZero() { - now = time.Now() - } - next := 2 - for { - revisionID := slugify(fmt.Sprintf("%s-rev-%d", id, next)) - if _, err := e.readArchiveLocked(revisionID); err != nil { - archive := &InceptionCampaignArchive{ - ID: revisionID, Title: strings.TrimSpace(title), Source: strings.TrimSpace(source), Repos: repos, - Engine: strings.TrimSpace(engine), Type: strings.TrimSpace(campaignType), RevisionOf: id, Revision: next, - ArchivedAt: now, Lease: &CampaignLease{Owner: campaignOwner(owner), Surface: "revise", AcquiredAt: now, ExpiresAt: now.Add(campaignLeaseTTL)}, - } - if archive.Engine == "" { - archive.Engine = "Spektacular" - } - if archive.Type == "" { - archive.Type = "spektacular" - } - if err := e.writeArchiveStateLocked(archive); err != nil { - return nil, err - } - return archive, nil - } - next++ - } -} - -// UpsertExternalCampaign records metadata for a non-Inception campaign without -// creating a revision. Existing archives keep their revision linkage and lease. -func (e *InceptionEngine) UpsertExternalCampaign(id, title, source, engine, campaignType string, repos []string, now time.Time) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - id = slugify(strings.TrimSpace(id)) - if id == "" { - return nil, fmt.Errorf("campaign id required") - } - if now.IsZero() { - now = time.Now() - } - archive, err := e.readArchiveLocked(id) - if err != nil { - archive = InceptionCampaignArchive{ID: id, ArchivedAt: now} - } - archive.Title = strings.TrimSpace(title) - archive.Source = strings.TrimSpace(source) - archive.Repos = repos - archive.Engine = strings.TrimSpace(engine) - archive.Type = strings.TrimSpace(campaignType) - if archive.Engine == "" { - archive.Engine = "Spektacular" - } - if archive.Type == "" { - archive.Type = "spektacular" - } - if archive.ArchivedAt.IsZero() { - archive.ArchivedAt = now - } - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return &archive, nil -} - -// SetCampaignRecheck records continuous-convergence cadence state for a -// retained campaign. -func (e *InceptionEngine) SetCampaignRecheck(id string, recheck *CampaignRecheck) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - archive.Recheck = recheck - if recheck != nil && recheck.Interval > 0 { - archive.RecheckInterval = recheck.Interval - } - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return &archive, nil -} - -// SetCampaignDrift attaches recheck evidence to a retained campaign revision. -func (e *InceptionEngine) SetCampaignDrift(id string, drift *CampaignDrift) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - archive.Drift = drift - if err := e.writeArchiveStateLocked(&archive); err != nil { - return nil, err - } - return &archive, nil -} - -// DeleteCampaignArchive removes a campaign's archive directory (saved state -// plus the wiki snapshot copy). KB facts, Jam threads and anything already -// scaffolded to the repo are untouched. When the campaign is also the active -// L1 session its live state is cleared so the dashboard does not resurrect it -// on the next refresh. Other revisions in the same chain are left alone; the -// deleted id simply stops resolving. -func (e *InceptionEngine) DeleteCampaignArchive(id string) (*InceptionCampaignArchive, error) { - e.mu.Lock() - defer e.mu.Unlock() - slug := slugify(strings.TrimSpace(id)) - if slug == "" { - return nil, fmt.Errorf("campaign id required") - } - archive, err := e.readArchiveLocked(slug) - activeMatches := e.state != nil && slugify(strings.TrimSpace(e.state.IdeaSlug)) == slug - if err != nil { - if !activeMatches { - return nil, err - } - archive = InceptionCampaignArchive{ID: slug, Engine: "Spec Kit", Type: "inception", State: copyInceptionState(e.state)} - } - root := filepath.Join(e.dataDir, inceptionCampaignsDir, slug) - if err := os.RemoveAll(root); err != nil { - return nil, fmt.Errorf("removing campaign archive: %w", err) - } - if activeMatches { - e.state = nil - if err := os.Remove(filepath.Join(e.dataDir, inceptionStateFile)); err != nil && !os.IsNotExist(err) { - return nil, fmt.Errorf("removing state file: %w", err) - } - } - e.logger.Info("inception campaign deleted", "campaign", slug, "was_active", activeMatches) - return &archive, nil -} - -// RestoreCampaignArchive makes an archived inception campaign the active L1 -// session again and restores its working wiki files. -func (e *InceptionEngine) RestoreCampaignArchive(id string) (*InceptionState, error) { - e.mu.Lock() - defer e.mu.Unlock() - archive, err := e.readArchiveLocked(id) - if err != nil { - return nil, err - } - if archive.State == nil { - return nil, fmt.Errorf("campaign %q has no inception state", id) - } - e.state = copyInceptionState(archive.State) - if err := e.saveState(); err != nil { - return nil, err - } - if err := e.restoreArchiveWikiLocked(archive.ID); err != nil { - return nil, err - } - if e.api != nil { - e.connectExistingVault() - } - cp := copyInceptionState(e.state) - e.logger.Info("inception campaign restored", "campaign", archive.ID, "phase", cp.Phase) - return cp, nil -} - -func (e *InceptionEngine) archiveFromStateLocked(now time.Time) *InceptionCampaignArchive { - state := copyInceptionState(e.state) - id := strings.TrimSpace(state.IdeaSlug) - if id == "" { - id = slugify("inception-" + truncateSlug(state.IdeaText)) - } - if id == "" { - id = fmt.Sprintf("inception-%d", now.Unix()) - } - return &InceptionCampaignArchive{ID: id, Engine: "Spec Kit", Type: "inception", ArchivedAt: now, State: state} -} - -func (e *InceptionEngine) writeArchiveLocked(archive *InceptionCampaignArchive) error { - if archive == nil || archive.State == nil { - return nil - } - root := filepath.Join(e.dataDir, inceptionCampaignsDir, slugify(archive.ID)) - if err := os.MkdirAll(root, 0o755); err != nil { - return fmt.Errorf("creating campaign archive: %w", err) - } - wikiFiles, err := e.copyWikiToArchiveLocked(root) - if err != nil { - return err - } - archive.WikiFiles = wikiFiles - if existing, err := e.readArchiveLocked(archive.ID); err == nil { - archive.Lease = existing.Lease - if archive.RevisionOf == "" { - archive.RevisionOf = existing.RevisionOf - } - if archive.Revision == 0 { - archive.Revision = existing.Revision - } - if archive.Title == "" { - archive.Title = existing.Title - } - if archive.Source == "" { - archive.Source = existing.Source - } - if len(archive.Repos) == 0 { - archive.Repos = existing.Repos - } - } - return e.writeArchiveStateLocked(archive) -} - -func (e *InceptionEngine) writeArchiveStateLocked(archive *InceptionCampaignArchive) error { - if archive == nil { - return nil - } - root := filepath.Join(e.dataDir, inceptionCampaignsDir, slugify(archive.ID)) - if err := os.MkdirAll(root, 0o755); err != nil { - return fmt.Errorf("creating campaign archive: %w", err) - } - data, err := json.MarshalIndent(archive, "", " ") - if err != nil { - return fmt.Errorf("marshaling campaign archive: %w", err) - } - tmp := filepath.Join(root, inceptionArchiveState+".tmp") - if err := os.WriteFile(tmp, data, 0o644); err != nil { - return fmt.Errorf("writing campaign archive: %w", err) - } - return os.Rename(tmp, filepath.Join(root, inceptionArchiveState)) -} - -func (e *InceptionEngine) copyArchiveWikiLocked(fromID, toID string) error { - from := filepath.Join(e.dataDir, inceptionCampaignsDir, slugify(fromID), inceptionArchiveWiki) - toRoot := filepath.Join(e.dataDir, inceptionCampaignsDir, slugify(toID)) - to := filepath.Join(toRoot, inceptionArchiveWiki) - if err := os.MkdirAll(toRoot, 0o755); err != nil { - return fmt.Errorf("creating campaign archive: %w", err) - } - entries, err := os.ReadDir(from) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return fmt.Errorf("reading campaign wiki archive: %w", err) - } - if err := os.RemoveAll(to); err != nil { - return fmt.Errorf("clearing campaign revision wiki: %w", err) - } - if err := os.MkdirAll(to, 0o755); err != nil { - return fmt.Errorf("creating campaign revision wiki: %w", err) - } - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") { - continue - } - name := filepath.Base(entry.Name()) - data, err := os.ReadFile(filepath.Join(from, name)) - if err != nil { - return fmt.Errorf("reading campaign wiki file %s: %w", name, err) - } - if err := os.WriteFile(filepath.Join(to, name), data, 0o644); err != nil { - return fmt.Errorf("writing campaign revision wiki file %s: %w", name, err) - } - } - return nil -} - -func campaignOwner(owner string) string { - owner = strings.TrimSpace(owner) - if owner == "" { - return "local" - } - return owner -} - -func (e *InceptionEngine) copyWikiToArchiveLocked(root string) ([]string, error) { - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(wikiDir) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, fmt.Errorf("reading inception wiki: %w", err) - } - archiveWiki := filepath.Join(root, inceptionArchiveWiki) - if err := os.RemoveAll(archiveWiki); err != nil { - return nil, fmt.Errorf("clearing campaign wiki archive: %w", err) - } - if err := os.MkdirAll(archiveWiki, 0o755); err != nil { - return nil, fmt.Errorf("creating campaign wiki archive: %w", err) - } - files := []string{} - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") { - continue - } - name := filepath.Base(entry.Name()) - data, err := os.ReadFile(filepath.Join(wikiDir, name)) - if err != nil { - return nil, fmt.Errorf("reading inception wiki file %s: %w", name, err) - } - if err := os.WriteFile(filepath.Join(archiveWiki, name), data, 0o644); err != nil { - return nil, fmt.Errorf("writing campaign wiki file %s: %w", name, err) - } - files = append(files, name) - } - sort.Strings(files) - return files, nil -} - -func (e *InceptionEngine) readArchiveLocked(id string) (InceptionCampaignArchive, error) { - id = slugify(strings.TrimSpace(id)) - if id == "" { - return InceptionCampaignArchive{}, fmt.Errorf("campaign id required") - } - data, err := os.ReadFile(filepath.Join(e.dataDir, inceptionCampaignsDir, id, inceptionArchiveState)) - if err != nil { - if os.IsNotExist(err) { - return InceptionCampaignArchive{}, fmt.Errorf("campaign %q not found", id) - } - return InceptionCampaignArchive{}, err - } - var archive InceptionCampaignArchive - if err := json.Unmarshal(data, &archive); err != nil { - return InceptionCampaignArchive{}, err - } - if archive.ID == "" { - archive.ID = id - } - return archive, nil -} - -func (e *InceptionEngine) restoreArchiveWikiLocked(id string) error { - archiveWiki := filepath.Join(e.dataDir, inceptionCampaignsDir, slugify(id), inceptionArchiveWiki) - entries, err := os.ReadDir(archiveWiki) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return fmt.Errorf("reading campaign wiki archive: %w", err) - } - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - return fmt.Errorf("creating inception wiki dir: %w", err) - } - if current, err := os.ReadDir(wikiDir); err == nil { - for _, entry := range current { - if strings.HasSuffix(entry.Name(), ".md") { - _ = os.Remove(filepath.Join(wikiDir, entry.Name())) - } - } - } - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") { - continue - } - name := filepath.Base(entry.Name()) - data, err := os.ReadFile(filepath.Join(archiveWiki, name)) - if err != nil { - return fmt.Errorf("reading campaign wiki file %s: %w", name, err) - } - if err := os.WriteFile(filepath.Join(wikiDir, name), data, 0o644); err != nil { - return fmt.Errorf("restoring campaign wiki file %s: %w", name, err) - } - } - return nil -} - -func copyInceptionState(state *InceptionState) *InceptionState { - if state == nil { - return nil - } - cp := *state - cp.Questions = append([]Question(nil), state.Questions...) - cp.FactSlugs = append([]string(nil), state.FactSlugs...) - cp.Answers = make(map[string]string, len(state.Answers)) - for k, v := range state.Answers { - cp.Answers[k] = v - } - if state.PhaseChangedAt != nil { - t := *state.PhaseChangedAt - cp.PhaseChangedAt = &t - } - return &cp -} - -// ReadIdeaFact returns the seed idea fact for the current inception. -func (e *InceptionEngine) ReadIdeaFact(ctx context.Context) (*Fact, error) { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil { - return nil, fmt.Errorf("no inception in progress") - } - if e.api == nil { - return nil, nil - } - return e.api.ReadFact(ctx, e.state.IdeaSlug) -} - -// SetWikiName persists a vanity name for the inception wiki. -func (e *InceptionEngine) SetWikiName(name string) { - e.mu.Lock() - defer e.mu.Unlock() - if e.state != nil { - e.state.WikiName = name - if err := e.saveState(); err != nil { - e.logger.Warn("failed to persist wiki name", "name", name, "error", err) - } - } -} - -func (e *InceptionEngine) IncrementAutoFactCount(count int) { - e.mu.Lock() - defer e.mu.Unlock() - if e.state != nil { - e.state.AutoFactCount += count - if err := e.saveState(); err != nil { - e.logger.Warn("failed to persist auto fact count", "count", count, "error", err) - } - } -} - -func (e *InceptionEngine) IncrementAutoQuestionCount(count int) { - e.mu.Lock() - defer e.mu.Unlock() - if e.state != nil { - e.state.AutoQuestionCount += count - if err := e.saveState(); err != nil { - e.logger.Warn("failed to persist auto question count", "count", count, "error", err) - } - } -} - -// HasWikiFiles returns true if the inception wiki has any files from a previous run. -func (e *InceptionEngine) WikiDir() string { - return filepath.Join(e.dataDir, inceptionWikiDir) -} - -func (e *InceptionEngine) HasWikiFiles() bool { - e.mu.Lock() - defer e.mu.Unlock() - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(wikiDir) - if err != nil { - return false - } - for _, entry := range entries { - if strings.HasSuffix(entry.Name(), ".md") { - return true - } - } - return false -} - -func (e *InceptionEngine) Reset() error { - e.mu.Lock() - defer e.mu.Unlock() - - e.state = nil - path := filepath.Join(e.dataDir, inceptionStateFile) - if err := os.Remove(path); err != nil && !os.IsNotExist(err) { - return fmt.Errorf("removing state file: %w", err) - } - - // Don't clear wiki on reset — keep last inception's facts visible - // in the KB until a new inception writes new facts (writeFactsToVault - // clears before writing). - - e.logger.Info("inception reset") - return nil -} - -// FormatAnswersForPrompt renders user answers as markdown for injection into -// the guide agent's kick template via ${INCEPTION_ANSWERS}. -func (e *InceptionEngine) FormatAnswersForPrompt() string { - e.mu.Lock() - defer e.mu.Unlock() - - if e.state == nil || len(e.state.Answers) == 0 { - return "" - } - - var b strings.Builder - b.WriteString("# User Answers\n\n") - for _, q := range e.state.Questions { - answer, ok := e.state.Answers[q.ID] - if !ok { - continue - } - fmt.Fprintf(&b, "**%s**\n%s\n\n", q.Text, answer) - } - return b.String() -} - -// --- persistence --- - -func (e *InceptionEngine) loadState() { - path := filepath.Join(e.dataDir, inceptionStateFile) - data, err := os.ReadFile(path) - if err != nil { - return - } - var state InceptionState - if err := json.Unmarshal(data, &state); err != nil { - e.logger.Warn("corrupt inception state", "path", path, "error", err) - return - } - if state.Answers == nil { - state.Answers = make(map[string]string) - } - if state.FactSlugs == nil { - state.FactSlugs = []string{} - } - e.state = &state - e.logger.Info("inception state loaded", - "phase", state.Phase, - "mode", state.Mode, - ) -} - -func (e *InceptionEngine) saveState() error { - path := filepath.Join(e.dataDir, inceptionStateFile) - dir := filepath.Dir(path) - if err := os.MkdirAll(dir, 0o755); err != nil { - return fmt.Errorf("creating state dir: %w", err) - } - - data, err := json.MarshalIndent(e.state, "", " ") - if err != nil { - return fmt.Errorf("marshaling state: %w", err) - } - - tmpPath := path + ".tmp" - if err := os.WriteFile(tmpPath, data, 0o644); err != nil { - return fmt.Errorf("writing state: %w", err) - } - return os.Rename(tmpPath, path) -} - -// --- fact helpers --- - -// GatherFactsPublic exposes gatherFacts for the API layer when the KB project -// layer has no ideation facts (e.g. api was nil during RecordFacts). -func (e *InceptionEngine) GatherFactsPublic(ctx context.Context) []Fact { - e.mu.Lock() - defer e.mu.Unlock() - return e.gatherFacts(ctx) -} - -func (e *InceptionEngine) gatherFacts(ctx context.Context) []Fact { - // Read facts from the inception wiki vault files directly - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(wikiDir) - if err != nil || len(entries) == 0 { - // Fallback to KB layer if no wiki files - if e.api != nil { - return e.api.LayerFacts(ctx, LayerProject, "") - } - return nil - } - - var facts []Fact - for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") { - continue - } - data, err := os.ReadFile(filepath.Join(wikiDir, entry.Name())) - if err != nil { - continue - } - content := string(data) - - // Parse YAML frontmatter - title, body, factType, conf := parseInceptionFactFile(content, entry.Name()) - facts = append(facts, Fact{ - Slug: strings.TrimSuffix(entry.Name(), ".md"), - Title: title, - Type: FactType(factType), - Body: body, - Confidence: conf, - Layer: LayerProject, - }) - } - return facts -} - -func parseInceptionFactFile(content, filename string) (title, body, factType string, confidence float64) { - confidence = 0.6 - title = strings.TrimSuffix(filename, ".md") - - if !strings.HasPrefix(content, "---\n") { - body = content - return - } - - endIdx := strings.Index(content[4:], "\n---") - if endIdx < 0 { - body = content - return - } - - frontmatter := content[4 : 4+endIdx] - body = strings.TrimSpace(content[4+endIdx+4:]) - - for _, line := range strings.Split(frontmatter, "\n") { - line = strings.TrimSpace(line) - if strings.HasPrefix(line, "title:") { - title = strings.TrimSpace(strings.TrimPrefix(line, "title:")) - title = strings.Trim(title, `"`) - title = strings.ReplaceAll(title, `\"`, `"`) - } - if strings.HasPrefix(line, "type:") { - factType = strings.TrimSpace(strings.TrimPrefix(line, "type:")) - } - if strings.HasPrefix(line, "confidence:") { - // Malformed input leaves confidence at its 0.6 default (Sscanf does not - // write to the destination on a parse failure), the same fallback as - // when the field is absent entirely. - _, _ = fmt.Sscanf(strings.TrimPrefix(line, "confidence:"), "%f", &confidence) - } - } - return -} - -func findFactByType(facts []Fact, ft FactType) *Fact { - for _, f := range facts { - if f.Type == ft { - return &f - } - } - return nil -} - -func filterFactsByType(facts []Fact, ft FactType) []Fact { - var result []Fact - for _, f := range facts { - if f.Type == ft { - result = append(result, f) - } - } - return result -} - -func defaultConfidence(ft FactType) float64 { - switch ft { - case FactIdea: - return ideaDefaultConf - case FactVision: - return visionDefaultConf - case FactConstitution: - return constDefaultConf - case FactRequirement: - return reqDefaultConf - case FactConstraint: - return constraintDefaultConf - case FactStakeholder: - return stakeholderDefaultConf - case FactAcceptance: - return acceptanceDefaultConf - default: - return 0.5 - } -} - -// --- scaffold builders --- - -func buildReadme(projectName, lang, ideaText string, vision, constitution *Fact, reqs, constraints, stakeholders []Fact) string { - var b strings.Builder - - title := "Project" - if vision != nil { - title = vision.Title - } - - fmt.Fprintf(&b, "# %s\n\n", title) - - if vision != nil { - b.WriteString("## Overview\n\n") - b.WriteString(vision.Body) - b.WriteString("\n\n") - } - - if ideaText != "" && (vision == nil || len(vision.Body) < 100) { - b.WriteString("## About This Project\n\n") - fmt.Fprintf(&b, "This project was conceived from the idea: *%s*\n\n", ideaText) - } - - if constitution != nil { - b.WriteString("## Architecture & Principles\n\n") - b.WriteString(constitution.Body) - b.WriteString("\n\n") - } - - if len(stakeholders) > 0 { - b.WriteString("## Who Is This For\n\n") - for _, s := range stakeholders { - fmt.Fprintf(&b, "- **%s** — %s\n", s.Title, s.Body) - } - b.WriteString("\n") - } - - if len(reqs) > 0 { - b.WriteString("## Features\n\n") - for _, r := range reqs { - if r.Body != "" && r.Body != r.Title { - fmt.Fprintf(&b, "- **%s** — %s\n", r.Title, r.Body) - } else { - fmt.Fprintf(&b, "- %s\n", r.Title) - } - } - b.WriteString("\n") - } - - if len(constraints) > 0 { - b.WriteString("## Constraints\n\n") - for _, c := range constraints { - if c.Body != "" && c.Body != c.Title { - fmt.Fprintf(&b, "- **%s** — %s\n", c.Title, c.Body) - } else { - fmt.Fprintf(&b, "- %s\n", c.Title) - } - } - b.WriteString("\n") - } - - b.WriteString("## Getting Started\n\n") - if constitution != nil { - switch lang { - case "go": - fmt.Fprintf(&b, "```bash\ngo build -o bin/ .\n./bin/%s\n```\n\n", projectName) - case "python": - fmt.Fprintf(&b, "```bash\npip install -e .\npython -m %s\n```\n\n", pyPackageName(projectName)) - case "typescript": - b.WriteString("```bash\nnpm install\nnpm run dev\n```\n\n") - case "javascript": - b.WriteString("```bash\nnpm install\nnpm start\n```\n\n") - case "rust": - fmt.Fprintf(&b, "```bash\ncargo build --release\n./target/release/%s\n```\n\n", projectName) - case "java": - fmt.Fprintf(&b, "```bash\nmvn package\njava -jar target/%s-0.1.0.jar\n```\n\n", projectName) - case "shell": - fmt.Fprintf(&b, "```bash\nchmod +x *.sh\n./%s.sh\n```\n\n", projectName) - default: - b.WriteString("TODO: Add setup instructions.\n\n") - } - } else { - b.WriteString("TODO: Add setup instructions.\n\n") - } - - b.WriteString("## License\n\n") - b.WriteString("TODO: Choose a license.\n") - - return b.String() -} - -func buildClaudeMD(lang string, constitution *Fact, constraints []Fact) string { - var b strings.Builder - - b.WriteString("# Project Guidelines\n\n") - b.WriteString("## Build & Test\n\n") - switch lang { - case "go": - b.WriteString("```bash\ngo build ./...\ngo test ./...\ngo vet ./...\n```\n\n") - case "python": - b.WriteString("```bash\npip install -e '.[dev]'\npytest\nruff check .\n```\n\n") - case "typescript": - b.WriteString("```bash\nnpm install\nnpm run build\nnpm test\nnpm run lint\n```\n\n") - case "javascript": - b.WriteString("```bash\nnpm install\nnpm test\nnpm run lint\n```\n\n") - case "rust": - b.WriteString("```bash\ncargo build\ncargo test\ncargo clippy -- -D warnings\n```\n\n") - case "java": - b.WriteString("```bash\nmvn compile\nmvn test\n```\n\n") - case "shell": - b.WriteString("```bash\nbash test.sh\nshellcheck *.sh\n```\n\n") - } - - if constitution != nil { - b.WriteString("## Principles\n\n") - b.WriteString(constitution.Body) - b.WriteString("\n\n") - } - - if len(constraints) > 0 { - b.WriteString("## Constraints\n\n") - for _, c := range constraints { - fmt.Fprintf(&b, "- %s\n", c.Title) - } - b.WriteString("\n") - } - - b.WriteString("## Code Quality\n\n") - b.WriteString("- No magic numbers — use named constants\n") - b.WriteString("- All commits must be signed with DCO\n") - b.WriteString("- Run tests before committing\n") - - return b.String() -} - -func buildTestStubs(acceptance []Fact, lang string) string { - acceptance = deduplicateFactTitles(acceptance) - - switch lang { - case "go": - return buildGoTestStubs(acceptance) - case "typescript", "javascript": - return buildTSTestStubs(acceptance) - case "python": - return buildPythonTestStubs(acceptance) - case "rust": - return buildRustTestStubs(acceptance) - case "java": - return buildJavaTestStubs(acceptance) - default: - return buildGoTestStubs(acceptance) - } -} - -func deduplicateFactTitles(facts []Fact) []Fact { - seen := make(map[string]int) - var result []Fact - for _, f := range facts { - key := toSnakeCase(f.Title) - seen[key]++ - if seen[key] > 1 { - f.Title = fmt.Sprintf("%s (%d)", f.Title, seen[key]) - } - result = append(result, f) - } - return result -} - -func buildGoTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("package main\n\nimport \"testing\"\n\n") - for _, a := range acceptance { - title := singleLine(a.Title) - funcName := "Test" + toPascalCase(title) - fmt.Fprintf(&b, "func %s(t *testing.T) {\n", funcName) - escaped := strings.ReplaceAll(title, `\`, `\\`) - escaped = strings.ReplaceAll(escaped, `"`, `\"`) - fmt.Fprintf(&b, "\tt.Skip(\"TODO: %s\")\n", escaped) - b.WriteString("}\n\n") - } - return b.String() -} - -func buildTSTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("import { describe, it } from 'vitest';\n\n") - b.WriteString("describe('acceptance criteria', () => {\n") - for _, a := range acceptance { - tsEsc := strings.ReplaceAll(singleLine(a.Title), `\`, `\\`) - tsEsc = strings.ReplaceAll(tsEsc, "'", "\\'") - fmt.Fprintf(&b, " it.todo('%s');\n", tsEsc) - } - b.WriteString("});\n") - return b.String() -} - -func buildPythonTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("import pytest\n\n") - for _, a := range acceptance { - title := singleLine(a.Title) - funcName := "test_" + toSnakeCase(title) - pyEsc := strings.ReplaceAll(title, `\`, `\\`) - pyEsc = strings.ReplaceAll(pyEsc, `"`, `\"`) - fmt.Fprintf(&b, "@pytest.mark.skip(reason=\"TODO: %s\")\n", pyEsc) - fmt.Fprintf(&b, "def %s():\n pass\n\n", funcName) - } - return b.String() -} - -func buildRustTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("#[cfg(test)]\nmod tests {\n\n") - for _, a := range acceptance { - title := singleLine(a.Title) - funcName := toSnakeCase(title) - rsEsc := strings.ReplaceAll(title, `\`, `\\`) - rsEsc = strings.ReplaceAll(rsEsc, `"`, `\"`) - fmt.Fprintf(&b, " #[test]\n #[ignore = \"TODO: %s\"]\n", rsEsc) - fmt.Fprintf(&b, " fn %s() {\n todo!()\n }\n\n", funcName) - } - b.WriteString("}\n") - return b.String() -} - -func buildJavaTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("import org.junit.jupiter.api.Disabled;\nimport org.junit.jupiter.api.Test;\n\n") - b.WriteString("class AppTest {\n\n") - for _, a := range acceptance { - title := singleLine(a.Title) - funcName := "test" + toPascalCase(title) - jvEsc := strings.ReplaceAll(title, `\`, `\\`) - jvEsc = strings.ReplaceAll(jvEsc, `"`, `\"`) - fmt.Fprintf(&b, " @Test\n @Disabled(\"TODO: %s\")\n", jvEsc) - fmt.Fprintf(&b, " void %s() {\n // TODO: implement\n }\n\n", funcName) - } - b.WriteString("}\n") - return b.String() -} - -func buildShellMain(name string, vision *Fact) string { - desc := singleLine(name) - if vision != nil && vision.Title != "" { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`#!/usr/bin/env bash -set -euo pipefail - -# %s - -main() { - echo "Starting %s..." - # TODO: implement -} - -main "$@" -`, desc, name) -} - -func buildShellTestStubs(acceptance []Fact) string { - var b strings.Builder - b.WriteString("#!/usr/bin/env bash\nset -euo pipefail\n\n") - b.WriteString("PASS=0\nFAIL=0\n\n") - for _, a := range acceptance { - title := singleLine(a.Title) - funcName := toSnakeCase(title) - fmt.Fprintf(&b, "test_%s() {\n", funcName) - safeTitle := strings.NewReplacer(`\`, `\\`, `"`, `\"`, `$`, `\$`, "`", "\\`").Replace(title) - fmt.Fprintf(&b, " echo \"SKIP: %s\"\n", safeTitle) - b.WriteString(" PASS=$((PASS+1))\n}\n\n") - } - b.WriteString("# Run all tests\n") - for _, a := range acceptance { - fmt.Fprintf(&b, "test_%s\n", toSnakeCase(singleLine(a.Title))) - } - b.WriteString("\necho \"$PASS passed, $FAIL failed\"\n") - return b.String() -} - -func buildContributing(projectName, lang string, constitution *Fact) string { - var b strings.Builder - b.WriteString("# Contributing\n\n") - b.WriteString("Thank you for your interest in contributing!\n\n") - b.WriteString("## Development Setup\n\n") - if constitution != nil { - switch lang { - case "go": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\ngo mod download\ngo build ./...\ngo test ./...\n```\n\n", projectName) - case "python": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\npython -m venv .venv && source .venv/bin/activate\npip install -e '.[dev]'\npytest\n```\n\n", projectName) - case "typescript", "javascript": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\nnpm install\nnpm test\n```\n\n", projectName) - case "rust": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\ncargo build\ncargo test\n```\n\n", projectName) - case "java": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\nmvn compile\nmvn test\n```\n\n", projectName) - case "shell": - fmt.Fprintf(&b, "```bash\ngit clone <repo-url>\ncd %s\nchmod +x *.sh\nbash test.sh\n```\n\n", projectName) - default: - b.WriteString("TODO: Add development setup instructions.\n\n") - } - } else { - b.WriteString("TODO: Add development setup instructions.\n\n") - } - b.WriteString("## Pull Request Process\n\n") - b.WriteString("1. Fork the repository and create your branch from `main`\n") - b.WriteString("2. Ensure tests pass before submitting\n") - b.WriteString("3. Sign all commits with DCO (`git commit -s`)\n") - b.WriteString("4. Open a PR with a clear description of the change\n\n") - - if constitution != nil { - b.WriteString("## Code Style\n\n") - b.WriteString(constitution.Body) - b.WriteString("\n") - } - - return b.String() -} - -func buildCIConfig(lang string) string { - switch lang { - case "go": - return goCI() - case "typescript": - return tsCI() - case "javascript": - return jsCI() - case "python": - return pythonCI() - case "rust": - return rustCI() - case "java": - return javaCI() - case "shell": - return shellCI() - default: - return goCI() - } -} - -func goCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version: stable - - run: go build ./... - - run: go test ./... - - run: go vet ./... -` -} - -func tsCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: npm ci - - run: npm run build - - run: npm run lint - - run: npm test -` -} - -func jsCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: npm ci - - run: npm run lint - - run: npm test -` -} - -func pythonCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - run: pip install -e ".[dev]" - - run: ruff check . - - run: pytest -` -} - -func rustCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - run: cargo build --release - - run: cargo test - - run: cargo clippy -- -D warnings -` -} - -func javaCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - run: mvn compile - - run: mvn test -` -} - -func shellCI() string { - return `name: CI -on: - push: - branches: [main] - pull_request: - branches: [main] - -jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Install shellcheck - run: sudo apt-get install -y shellcheck - - run: shellcheck *.sh - - run: bash test.sh -` -} - -func inferProjectName(vision *Fact, state *InceptionState) string { - if vision != nil { - words := strings.Fields(strings.ToLower(vision.Title)) - var name []string - for _, w := range words { - w = strings.Map(func(r rune) rune { - if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') { - return r - } - return -1 - }, w) - if w != "" && w != "a" && w != "the" && w != "for" && w != "and" && w != "that" { - name = append(name, w) - if len(name) >= 3 { - break - } - } - } - if len(name) > 0 { - return strings.Join(name, "-") - } - } - if state != nil && state.IdeaSlug != "" { - slug := strings.TrimPrefix(state.IdeaSlug, "idea-") - if len(slug) > maxSlugLen { - slug = slug[:maxSlugLen] - } - return slug - } - return "myproject" -} - -func buildAgentsMD(constitution *Fact, constraints []Fact, requirements []Fact, vision *Fact) string { - var b strings.Builder - b.WriteString("# AI Agent Instructions\n\n") - b.WriteString("This file provides instructions for AI coding agents (Claude, Copilot, Cursor, etc.) working on this project.\n\n") - - if vision != nil { - b.WriteString("## Project Purpose\n\n") - b.WriteString(vision.Body) - b.WriteString("\n\n") - } - - if constitution != nil { - b.WriteString("## Architecture & Principles\n\n") - b.WriteString(constitution.Body) - b.WriteString("\n\n") - } - - if len(requirements) > 0 { - b.WriteString("## Key Requirements\n\n") - for _, r := range requirements { - fmt.Fprintf(&b, "- **%s**: %s\n", r.Title, r.Body) - } - b.WriteString("\n") - } - - if len(constraints) > 0 { - b.WriteString("## Constraints\n\n") - for _, c := range constraints { - fmt.Fprintf(&b, "- %s\n", c.Title) - if c.Body != c.Title { - fmt.Fprintf(&b, " %s\n", c.Body) - } - } - b.WriteString("\n") - } - - b.WriteString("## Code Quality Rules\n\n") - b.WriteString("- No magic numbers — use named constants\n") - b.WriteString("- All commits must be signed with DCO (`git commit -s`)\n") - b.WriteString("- Run tests before committing\n") - b.WriteString("- Prefer editing existing files over creating new ones\n") - b.WriteString("- No comments unless the WHY is non-obvious\n") - - return b.String() -} - -func buildGitignore(lang string) string { - common := "# OS\n.DS_Store\nThumbs.db\n\n# IDE\n.idea/\n.vscode/\n*.swp\n*.swo\n\n# Secrets\n.env\n.env.*\n*.pem\n*.key\n\n" - switch lang { - case "go": - return common + "# Go\n/bin/\n*.exe\ncoverage.out\n" - case "python": - return common + "# Python\n__pycache__/\n*.pyc\n*.egg-info/\ndist/\nbuild/\n.venv/\nvenv/\n.pytest_cache/\n.ruff_cache/\n" - case "typescript": - return common + "# Node\nnode_modules/\ndist/\ncoverage/\n*.tsbuildinfo\n" - case "javascript": - return common + "# Node\nnode_modules/\ncoverage/\n" - case "rust": - return common + "# Rust\n/target/\n" - case "java": - return common + "# Java\ntarget/\n*.class\n*.jar\n.gradle/\nbuild/\n" - case "shell": - return common + "# Shell\n*.log\n" - default: - return common - } -} - -func buildGoMod(name string) string { - return fmt.Sprintf(`module %s - -go 1.23 - -require github.com/spf13/cobra v1.8.1 -`, name) -} - -func buildGoMain(name string, vision *Fact) string { - desc := singleLine(name) - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`package main - -import "%s/cmd" - -// %s -func main() { - cmd.Execute() -} -`, name, desc) -} - -func buildGoCmdRoot(name string, vision *Fact) string { - desc := singleLine(name) - if vision != nil { - desc = singleLine(vision.Title) - } - escapedDesc := strings.ReplaceAll(desc, `"`, `\"`) - return fmt.Sprintf(`package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" -) - -var rootCmd = &cobra.Command{ - Use: "%s", - Short: "%s", - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("TODO: implement main logic") - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -`, name, escapedDesc) -} - -func buildCargoToml(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`[package] -name = "%s" -version = "0.1.0" -edition = "2021" -description = "%s" - -[dependencies] -`, tomlEscape(name), tomlEscape(desc)) -} - -func buildRustMain(name string, vision *Fact) string { - desc := singleLine(name) - if vision != nil && vision.Title != "" { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`// %s -fn main() { - println!("Starting %s..."); -} -`, desc, name) -} - -func buildPomXml(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>com.example</groupId> - <artifactId>%s</artifactId> - <version>0.1.0</version> - <packaging>jar</packaging> - <name>%s</name> - <properties> - <maven.compiler.source>21</maven.compiler.source> - <maven.compiler.target>21</maven.compiler.target> - </properties> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <configuration> - <archive> - <manifest> - <mainClass>App</mainClass> - </manifest> - </archive> - </configuration> - </plugin> - </plugins> - </build> -</project> -`, xmlEscape(name), xmlEscape(desc)) -} - -func buildJavaMain(name string, vision *Fact) string { - desc := singleLine(name) - if vision != nil && vision.Title != "" { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`// %s -public class App { - public static void main(String[] args) { - System.out.println("Starting %s..."); - } -} -`, desc, name) -} - -func buildPyprojectToml(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`[project] -name = "%s" -version = "0.1.0" -description = "%s" -requires-python = ">=3.11" -dependencies = [ - "click>=8.0", -] - -[project.scripts] -%s = "%s.cli:main" - -[project.optional-dependencies] -dev = ["pytest", "ruff"] - -[build-system] -requires = ["setuptools>=68.0"] -build-backend = "setuptools.build_meta" -`, tomlEscape(name), tomlEscape(desc), tomlEscape(name), pyPackageName(name)) -} - -func buildPyInit(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - safeDesc := strings.ReplaceAll(singleLine(desc), `"""`, `\"\"\"`) - return fmt.Sprintf("\"\"\"%s\"\"\"\n\n__version__ = \"0.1.0\"\n", safeDesc) -} - -func buildPyCLI(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - safeDesc := strings.ReplaceAll(singleLine(desc), `"""`, `\"\"\"`) - return fmt.Sprintf(`"""CLI entry point for %s.""" - -import click - -from . import __version__ - - -@click.group() -@click.version_option(version=__version__) -def main(): - """%s""" - pass - - -@main.command() -@click.argument("path", type=click.Path(exists=True)) -def run(path: str): - """Run the main operation on PATH.""" - click.echo(f"TODO: implement main logic for {path}") - - -if __name__ == "__main__": - main() -`, safeDesc, safeDesc) -} - -func buildPackageJSON(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`{ - "name": "%s", - "version": "0.1.0", - "description": "%s", - "type": "module", - "main": "dist/index.js", - "scripts": { - "build": "tsc", - "dev": "tsx src/index.ts", - "test": "vitest run", - "lint": "eslint src/" - }, - "devDependencies": { - "typescript": "^5.0.0", - "tsx": "^4.0.0", - "vitest": "^2.0.0", - "eslint": "^9.0.0" - } -} -`, jsonEscape(name), jsonEscape(desc)) -} - -func buildJSPackageJSON(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - return fmt.Sprintf(`{ - "name": "%s", - "version": "0.1.0", - "description": "%s", - "main": "src/index.js", - "scripts": { - "start": "node src/index.js", - "test": "vitest run", - "lint": "eslint src/" - }, - "devDependencies": { - "vitest": "^2.0.0", - "eslint": "^9.0.0" - } -} -`, jsonEscape(name), jsonEscape(desc)) -} - -func buildTSConfig() string { - return `{ - "compilerOptions": { - "target": "ES2022", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "strict": true, - "outDir": "dist", - "rootDir": "src", - "declaration": true, - "esModuleInterop": true, - "skipLibCheck": true - }, - "include": ["src/**/*"] -} -` -} - -func buildTSIndex(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - desc = strings.ReplaceAll(desc, "*/", "* /") - return fmt.Sprintf(`/** - * %s - */ - -export function main(): void { - console.log("TODO: implement main logic"); -} - -main(); -`, desc) -} - -func buildJSIndex(name string, vision *Fact) string { - desc := name - if vision != nil { - desc = singleLine(vision.Title) - } - desc = strings.ReplaceAll(desc, "*/", "* /") - return fmt.Sprintf(`/** - * %s - */ - -function main() { - console.log("TODO: implement main logic"); -} - -main(); -`, desc) -} - -func inferProjectType(constitution *Fact, requirements []Fact, vision *Fact) string { - all := "" - if constitution != nil { - all += strings.ToLower(constitution.Body) - } - if vision != nil { - all += " " + strings.ToLower(vision.Body) + " " + strings.ToLower(vision.Title) - } - for _, r := range requirements { - all += " " + strings.ToLower(r.Title) + " " + strings.ToLower(r.Body) - } - - switch { - case strings.Contains(all, "operator") || strings.Contains(all, "controller") || - strings.Contains(all, "kubernetes") || strings.Contains(all, "k8s") || - strings.Contains(all, "helm") || strings.Contains(all, "crd") || - strings.Contains(all, "kustomize") || strings.Contains(all, "namespace"): - return "kubernetes" - case strings.Contains(all, "dashboard") || strings.Contains(all, "frontend") || - strings.Contains(all, "react") || strings.Contains(all, "vue") || - strings.Contains(all, "web app") || strings.Contains(all, "ui component") || - strings.Contains(all, "next.js") || containsWord(all, "vite"): - return "ui" - case strings.Contains(all, "docker") || strings.Contains(all, "container") || - strings.Contains(all, "deploy") || strings.Contains(all, "service"): - return "container" - case strings.Contains(all, "library") || strings.Contains(all, "package") || strings.Contains(all, "sdk"): - return "library" - case strings.Contains(all, "api") || strings.Contains(all, "server") || strings.Contains(all, "endpoint"): - return "api" - default: - return "cli" - } -} - -func buildDockerfile(lang, name string) string { - switch lang { - case "go": - return fmt.Sprintf(`FROM golang:1.23-alpine AS builder -WORKDIR /app -COPY go.mod ./ -COPY go.sum* ./ -RUN go mod download 2>/dev/null || true -COPY . . -RUN go mod tidy -RUN CGO_ENABLED=0 go build -o /bin/%s . - -FROM alpine:3.21 -RUN apk add --no-cache ca-certificates -COPY --from=builder /bin/%s /usr/local/bin/%s -ENTRYPOINT ["%s"] -`, name, name, name, name) - case "python": - return fmt.Sprintf(`FROM python:3.12-slim -WORKDIR /app -COPY pyproject.toml . -COPY src/ src/ -RUN pip install --no-cache-dir . -ENTRYPOINT ["%s"] -`, name) - case "rust": - return fmt.Sprintf(`FROM rust:1.82-slim AS builder -WORKDIR /app -COPY Cargo.toml ./ -COPY Cargo.lock* ./ -COPY src/ src/ -RUN cargo build --release - -FROM debian:bookworm-slim -RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* -COPY --from=builder /app/target/release/%s /usr/local/bin/%s -ENTRYPOINT ["%s"] -`, name, name, name) - case "java": - return fmt.Sprintf(`FROM maven:3.9-eclipse-temurin-21 AS builder -WORKDIR /app -COPY pom.xml . -RUN mvn dependency:go-offline -COPY src/ src/ -RUN mvn package -DskipTests - -FROM eclipse-temurin:21-jre -COPY --from=builder /app/target/%s-*.jar /app/%s.jar -ENTRYPOINT ["java", "-jar", "/app/%s.jar"] -`, name, name, name) - case "javascript": - return `FROM node:22-alpine -WORKDIR /app -COPY package*.json ./ -RUN npm ci --omit=dev -COPY src/ src/ -CMD ["node", "src/index.js"] -` - default: - return `FROM node:22-alpine AS builder -WORKDIR /app -COPY package*.json ./ -RUN npm ci -COPY . . -RUN npm run build - -FROM node:22-alpine -WORKDIR /app -COPY --from=builder /app/dist ./dist -COPY --from=builder /app/node_modules ./node_modules -COPY --from=builder /app/package.json . -CMD ["node", "dist/index.js"] -` - } -} - -func buildKustomization() string { - return `apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -resources: - - base - -# Use overlays for environment-specific config: -# kubectl apply -k deploy/overlays/dev -# kubectl apply -k deploy/overlays/prod -` -} - -func buildK8sDeployment(name string) string { - return fmt.Sprintf(`apiVersion: apps/v1 -kind: Deployment -metadata: - name: %s - labels: - app: %s -spec: - replicas: 1 - selector: - matchLabels: - app: %s - template: - metadata: - labels: - app: %s - spec: - containers: - - name: %s - image: %s:latest - ports: - - containerPort: 8080 - envFrom: - - configMapRef: - name: %s-config - - secretRef: - name: %s-secrets - resources: - requests: - memory: "64Mi" - cpu: "100m" - limits: - memory: "256Mi" - cpu: "500m" - livenessProbe: - httpGet: - path: /healthz - port: 8080 - initialDelaySeconds: 5 - readinessProbe: - httpGet: - path: /readyz - port: 8080 - initialDelaySeconds: 3 -`, name, name, name, name, name, name, name, name) -} - -func buildK8sService(name string) string { - return fmt.Sprintf(`apiVersion: v1 -kind: Service -metadata: - name: %s - labels: - app: %s -spec: - type: ClusterIP - ports: - - port: 80 - targetPort: 8080 - protocol: TCP - selector: - app: %s -`, name, name, name) -} - -func buildK8sConfigMap(name string) string { - return fmt.Sprintf(`apiVersion: v1 -kind: ConfigMap -metadata: - name: %s-config -data: - LOG_LEVEL: "info" - PORT: "8080" - # Add application-specific config here -`, name) -} - -func buildK8sSecret(name string) string { - return fmt.Sprintf(`apiVersion: v1 -kind: Secret -metadata: - name: %s-secrets -type: Opaque -data: {} - # Populate from sealed-secrets, external-secrets-operator, or - # kubectl create secret generic %s-secrets --from-literal=API_KEY=<value> - # Do NOT add plaintext secrets to this file. -`, name, name) -} - -func buildK8sBaseKustomization() string { - return `apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -resources: - - deployment.yaml - - service.yaml - - configmap.yaml - - secret.yaml -` -} - -func buildK8sOverlayKustomization(name, env string) string { - replicas := 1 - if env == "prod" { - replicas = 3 - } - return fmt.Sprintf(`apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization - -resources: - - ../../base - -namePrefix: %s- - -patches: - - target: - kind: Deployment - name: %s - patch: | - - op: replace - path: /spec/replicas - value: %d -`, env, name, replicas) -} - -func buildNightlyCI(lang string) string { - var setupStep, testCmd string - switch lang { - case "go": - setupStep = " - uses: actions/setup-go@v5\n with:\n go-version: stable\n" - testCmd = "go test -race -cover -count=3 ./..." - case "python": - setupStep = " - uses: actions/setup-python@v5\n with:\n python-version: '3.12'\n - run: pip install -e '.[dev]'\n" - testCmd = "pytest --tb=long -v" - case "rust": - setupStep = " - uses: dtolnay/rust-toolchain@stable\n" - testCmd = "cargo test -- --nocapture" - case "java": - setupStep = " - uses: actions/setup-java@v4\n with:\n distribution: temurin\n java-version: '21'\n" - testCmd = "mvn verify -P integration-test" - case "shell": - setupStep = "" - testCmd = "bash test.sh" - default: - setupStep = " - uses: actions/setup-node@v4\n with:\n node-version: 22\n - run: npm ci\n" - testCmd = "npm test -- --reporter=verbose" - } - return fmt.Sprintf(`name: Nightly -on: - schedule: - - cron: '0 4 * * *' # 4am UTC daily - workflow_dispatch: {} - -jobs: - full-suite: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 -%s - name: Full test suite - run: %s - - name: Upload results - if: always() - uses: actions/upload-artifact@v4 - with: - name: nightly-results - path: coverage* -`, setupStep, testCmd) -} - -func buildI18nFile(locale, name string) string { - escaped := jsonEscape(name) - switch locale { - case "es": - return fmt.Sprintf(`{ - "app.title": "%s", - "app.description": "Descripción del proyecto", - "common.save": "Guardar", - "common.cancel": "Cancelar", - "common.delete": "Eliminar", - "common.edit": "Editar", - "common.loading": "Cargando...", - "common.error": "Error", - "common.success": "Éxito", - "common.search": "Buscar" -} -`, escaped) - default: - return fmt.Sprintf(`{ - "app.title": "%s", - "app.description": "Project description", - "common.save": "Save", - "common.cancel": "Cancel", - "common.delete": "Delete", - "common.edit": "Edit", - "common.loading": "Loading...", - "common.error": "Error", - "common.success": "Success", - "common.search": "Search" -} -`, escaped) - } -} - -func buildI18nIndex() string { - content, _ := buildI18nIndexForLang("typescript") - return content -} - -func buildI18nIndexForLang(lang string) (content string, path string) { - switch lang { - case "python": - return `import json -from pathlib import Path - -_dir = Path(__file__).parent -_messages = { - "en": json.loads((_dir / "en.json").read_text()), - "es": json.loads((_dir / "es.json").read_text()), -} -_locale = "en" - - -def set_locale(locale: str) -> None: - global _locale - _locale = locale - - -def t(key: str) -> str: - return _messages.get(_locale, {}).get(key, key) -`, "src/i18n/__init__.py" - case "go": - return `package i18n - -import ( - "embed" - "encoding/json" -) - -//go:embed en.json es.json -var localeFS embed.FS - -var messages = map[string]map[string]string{} -var currentLocale = "en" - -func init() { - for _, loc := range []string{"en", "es"} { - data, _ := localeFS.ReadFile(loc + ".json") - m := map[string]string{} - _ = json.Unmarshal(data, &m) - messages[loc] = m - } -} - -func SetLocale(locale string) { currentLocale = locale } - -func T(key string) string { - if m, ok := messages[currentLocale]; ok { - if v, ok := m[key]; ok { - return v - } - } - return key -} -`, "src/i18n/i18n.go" - case "rust": - return `use std::collections::HashMap; -use std::sync::Mutex; - -static LOCALE: Mutex<String> = Mutex::new(String::new()); - -pub fn set_locale(locale: &str) { - *LOCALE.lock().unwrap() = locale.to_string(); -} - -pub fn t(key: &str) -> String { - let locale = LOCALE.lock().unwrap(); - let loc = if locale.is_empty() { "en" } else { &locale }; - let messages: HashMap<&str, &str> = match loc { - "es" => include!("es_messages.rs"), - _ => include!("en_messages.rs"), - }; - messages.get(key).map(|s| s.to_string()).unwrap_or_else(|| key.to_string()) -} -`, "src/i18n/mod.rs" - case "java": - return `package i18n; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -public class I18n { - private static String locale = "en"; - private static final Map<String, Map<String, String>> messages = new HashMap<>(); - - public static void setLocale(String loc) { locale = loc; } - - public static String t(String key) { - Map<String, String> m = messages.getOrDefault(locale, Map.of()); - return m.getOrDefault(key, key); - } -} -`, "src/i18n/I18n.java" - case "javascript": - return `import en from './en.json' assert { type: 'json' }; -import es from './es.json' assert { type: 'json' }; - -const messages = { en, es }; -let currentLocale = 'en'; - -export function setLocale(locale) { - currentLocale = locale; -} - -export function t(key) { - return messages[currentLocale]?.[key] ?? key; -} -`, "src/i18n/index.js" - case "shell": - return `#!/usr/bin/env bash -LOCALE="${LOCALE:-en}" -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -t() { - local key="$1" - local file="$SCRIPT_DIR/${LOCALE}.json" - if command -v jq &>/dev/null && [ -f "$file" ]; then - jq -r --arg k "$key" '.[$k] // $k' "$file" - else - echo "$key" - fi -} -`, "src/i18n/i18n.sh" - default: - return `import en from './en.json'; -import es from './es.json'; - -export type Locale = 'en' | 'es'; - -const messages: Record<Locale, Record<string, string>> = { en, es }; - -let currentLocale: Locale = 'en'; - -export function setLocale(locale: Locale): void { - currentLocale = locale; -} - -export function t(key: string): string { - return messages[currentLocale]?.[key] ?? key; -} -`, "src/i18n/index.ts" - } -} - -func buildMakefile(lang, name, projectType string) string { - var b strings.Builder - var targets []string - if lang != "javascript" && lang != "shell" { - targets = append(targets, "build") - } - targets = append(targets, "test", "lint") - if lang != "shell" { - targets = append(targets, "clean") - } - if projectType == "container" || projectType == "kubernetes" { - targets = append(targets, "docker-build", "docker-push") - } - if projectType == "kubernetes" { - targets = append(targets, "deploy", "deploy-prod") - } - fmt.Fprintf(&b, ".PHONY: %s\n\n", strings.Join(targets, " ")) - switch lang { - case "go": - fmt.Fprintf(&b, "build:\n\tgo build -o bin/%s .\n\n", name) - b.WriteString("test:\n\tgo test -race -cover ./...\n\n") - b.WriteString("lint:\n\tgolangci-lint run ./...\n\n") - b.WriteString("clean:\n\trm -rf bin/\n\n") - case "python": - b.WriteString("build:\n\tpip install -e .\n\n") - b.WriteString("test:\n\tpytest\n\n") - b.WriteString("lint:\n\truff check .\n\n") - b.WriteString("clean:\n\trm -rf dist/ build/ *.egg-info/\n\n") - case "typescript": - b.WriteString("build:\n\tnpm run build\n\n") - b.WriteString("test:\n\tnpm test\n\n") - b.WriteString("lint:\n\tnpm run lint\n\n") - b.WriteString("clean:\n\trm -rf dist/ node_modules/\n\n") - case "javascript": - b.WriteString("test:\n\tnpm test\n\n") - b.WriteString("lint:\n\tnpm run lint\n\n") - b.WriteString("clean:\n\trm -rf node_modules/\n\n") - case "rust": - b.WriteString("build:\n\tcargo build --release\n\n") - b.WriteString("test:\n\tcargo test\n\n") - b.WriteString("lint:\n\tcargo clippy -- -D warnings\n\n") - b.WriteString("clean:\n\tcargo clean\n\n") - case "java": - b.WriteString("build:\n\tmvn package\n\n") - b.WriteString("test:\n\tmvn test\n\n") - b.WriteString("lint:\n\tmvn checkstyle:check\n\n") - b.WriteString("clean:\n\tmvn clean\n\n") - case "shell": - b.WriteString("test:\n\tbash test.sh\n\n") - b.WriteString("lint:\n\tshellcheck *.sh\n\n") - } - if projectType == "container" || projectType == "kubernetes" { - fmt.Fprintf(&b, "docker-build:\n\tdocker build -t %s:latest .\n\n", name) - fmt.Fprintf(&b, "docker-push:\n\tdocker push %s:latest\n\n", name) - } - if projectType == "kubernetes" { - b.WriteString("deploy:\n\tkubectl apply -k deploy/overlays/dev\n\n") - b.WriteString("deploy-prod:\n\tkubectl apply -k deploy/overlays/prod\n") - } - return b.String() -} - -// --- string helpers --- - -func jsonEscape(s string) string { - s = strings.ReplaceAll(s, `\`, `\\`) - s = strings.ReplaceAll(s, `"`, `\"`) - s = strings.ReplaceAll(s, "\n", `\n`) - s = strings.ReplaceAll(s, "\r", `\r`) - s = strings.ReplaceAll(s, "\t", `\t`) - return s -} - -func xmlEscape(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - s = strings.ReplaceAll(s, `"`, """) - return s -} - -func singleLine(s string) string { - s = strings.ReplaceAll(s, "\n", " ") - s = strings.ReplaceAll(s, "\r", "") - return strings.TrimSpace(s) -} - -func tomlEscape(s string) string { - s = strings.ReplaceAll(s, `\`, `\\`) - s = strings.ReplaceAll(s, `"`, `\"`) - s = strings.ReplaceAll(s, "\n", `\n`) - s = strings.ReplaceAll(s, "\r", `\r`) - s = strings.ReplaceAll(s, "\t", `\t`) - return s -} - -func pyPackageName(name string) string { - return strings.ReplaceAll(name, "-", "_") -} - -func slugify(s string) string { - s = strings.ToLower(s) - s = strings.Map(func(r rune) rune { - if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' { - return r - } - if r == ' ' || r == '_' || r == '\n' || r == '\r' || r == '\t' { - return '-' - } - return -1 - }, s) - for strings.Contains(s, "--") { - s = strings.ReplaceAll(s, "--", "-") - } - return strings.Trim(s, "-") -} - -func truncateSlug(s string) string { - const maxSlugInputLen = 60 - if len(s) <= maxSlugInputLen { - return s - } - // Truncate at rune boundary to avoid splitting multi-byte UTF-8 - runes := []rune(s) - if len(runes) > maxSlugInputLen { - runes = runes[:maxSlugInputLen] - } - return string(runes) -} - -func inferLanguageFromText(text string) string { - lower := strings.ToLower(text) - switch { - case strings.Contains(lower, "python"): - return "python" - case strings.Contains(lower, "typescript"): - return "typescript" - case strings.Contains(lower, "javascript") && !strings.Contains(lower, "typescript"): - return "javascript" - case containsWord(lower, "rust"): - return "rust" - case containsWord(lower, "java") && !strings.Contains(lower, "javascript"): - return "java" - case containsWord(lower, "go") || strings.Contains(lower, "golang"): - return "go" - case containsWord(lower, "shell") || containsWord(lower, "bash"): - return "shell" - } - return "" -} - -func containsWord(text, word string) bool { - idx := 0 - for { - pos := strings.Index(text[idx:], word) - if pos < 0 { - return false - } - absPos := idx + pos - endPos := absPos + len(word) - atStart := absPos == 0 || !isAlpha(text[absPos-1]) - atEnd := endPos >= len(text) || !isAlpha(text[endPos]) - if atStart && atEnd { - return true - } - idx = absPos + 1 - } -} - -func isAlpha(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') -} - -func repoBaseName(url string) string { - url = strings.TrimSuffix(url, "/") - url = strings.TrimSuffix(url, ".git") - parts := strings.Split(url, "/") - for i := len(parts) - 1; i >= 0; i-- { - if parts[i] != "" { - return parts[i] - } - } - return "repo" -} - -func inferLanguage(constitution *Fact) string { - if constitution == nil { - return "go" - } - body := strings.ToLower(constitution.Body + " " + constitution.Title) - switch { - case strings.Contains(body, "typescript") || strings.Contains(body, "react") || strings.Contains(body, "angular") || - strings.Contains(body, "vue") || strings.Contains(body, "next.js") || strings.Contains(body, "nest"): - return "typescript" - case strings.Contains(body, "python") || strings.Contains(body, "pytest") || containsWord(body, "pip") || - strings.Contains(body, "django") || strings.Contains(body, "flask") || strings.Contains(body, "fastapi") || - strings.Contains(body, "sqlalchemy") || strings.Contains(body, "poetry"): - return "python" - case strings.Contains(body, "javascript") || strings.Contains(body, "vitest") || - strings.Contains(body, "express") || strings.Contains(body, "webpack") || containsWord(body, "vite"): - return "javascript" - case containsWord(body, "rust") || strings.Contains(body, "cargo") || strings.Contains(body, "tokio") || - strings.Contains(body, "actix") || containsWord(body, "warp") || strings.Contains(body, "axum"): - return "rust" - case containsWord(body, "java") || strings.Contains(body, "maven") || strings.Contains(body, "gradle") || - strings.Contains(body, "spring") || strings.Contains(body, "kotlin") || strings.Contains(body, "quarkus"): - return "java" - case containsWord(body, "bash") || containsWord(body, "shell") || strings.Contains(body, "posix") || - strings.Contains(body, "zsh") || strings.Contains(body, "makefile") || strings.Contains(body, "shellcheck"): - return "shell" - default: - return "go" - } -} - -func inferTestPath(constitution *Fact) string { - lang := inferLanguage(constitution) - switch lang { - case "go": - return "main_test.go" - case "typescript": - return "src/__tests__/acceptance.test.ts" - case "javascript": - return "src/__tests__/acceptance.test.js" - case "python": - return "tests/test_acceptance.py" - default: - return "main_test.go" - } -} - -func toPascalCase(s string) string { - words := strings.Fields(s) - var b strings.Builder - for _, w := range words { - w = strings.Map(func(r rune) rune { - if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') { - return r - } - return -1 - }, w) - if w == "" { - continue - } - b.WriteString(strings.ToUpper(w[:1]) + w[1:]) - } - if b.Len() == 0 { - return "Unnamed" - } - return b.String() -} - -func toSnakeCase(s string) string { - words := strings.Fields(strings.ToLower(s)) - var filtered []string - for _, w := range words { - w = strings.Map(func(r rune) rune { - if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' { - return r - } - return -1 - }, w) - if w != "" { - filtered = append(filtered, w) - } - } - result := strings.Join(filtered, "_") - if result == "" { - return "unnamed" - } - return result -} diff --git a/src/pkg/knowledge/inception_archive_test.go b/src/pkg/knowledge/inception_archive_test.go deleted file mode 100644 index e4a114b6a4..0000000000 --- a/src/pkg/knowledge/inception_archive_test.go +++ /dev/null @@ -1,406 +0,0 @@ -package knowledge - -import ( - "errors" - "os" - "path/filepath" - "reflect" - "strings" - "testing" - "time" -) - -func TestCampaignArchiveRoundTripListAndRestoreWiki(t *testing.T) { - e := newTestEngine(t) - state, err := e.Start("Archive the handoff campaign") - if err != nil { - t.Fatalf("Start() error = %v", err) - } - state.Answers["audience"] = "operators" - - wikiDir := e.WikiDir() - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - t.Fatalf("mkdir wiki: %v", err) - } - files := map[string]string{ - "b.md": "# second", - "a.md": "# first", - "ignore.txt": "not archived", - } - for name, body := range files { - if err := os.WriteFile(filepath.Join(wikiDir, name), []byte(body), 0o644); err != nil { - t.Fatalf("write wiki %s: %v", name, err) - } - } - - archive, err := e.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("ArchiveCurrentCampaign() error = %v", err) - } - if archive.ID != state.IdeaSlug { - t.Fatalf("archive ID = %q, want %q", archive.ID, state.IdeaSlug) - } - if archive.Engine != "Spec Kit" || archive.Type != "inception" { - t.Fatalf("archive engine/type = %q/%q", archive.Engine, archive.Type) - } - if want := []string{"a.md", "b.md"}; !reflect.DeepEqual(archive.WikiFiles, want) { - t.Fatalf("archive wiki files = %#v, want %#v", archive.WikiFiles, want) - } - - loaded, err := e.LoadCampaignArchive(archive.ID) - if err != nil { - t.Fatalf("LoadCampaignArchive() error = %v", err) - } - if loaded.State == archive.State { - t.Fatal("loaded archive reused state pointer") - } - if loaded.State.Answers["audience"] != "operators" { - t.Fatalf("loaded answer = %q", loaded.State.Answers["audience"]) - } - - oldTime := archive.ArchivedAt.Add(-time.Hour) - newTime := archive.ArchivedAt.Add(time.Hour) - if _, err := e.ReviseExternalCampaign("external beta", "Beta", "speks", "", "", "", []string{"org/repo"}, oldTime); err != nil { - t.Fatalf("ReviseExternalCampaign(old) error = %v", err) - } - if _, err := e.ReviseExternalCampaign("external alpha", "Alpha", "speks", "Custom", "other", "owner", nil, newTime); err != nil { - t.Fatalf("ReviseExternalCampaign(new) error = %v", err) - } - archives, err := e.ListCampaignArchives() - if err != nil { - t.Fatalf("ListCampaignArchives() error = %v", err) - } - if len(archives) != 3 { - t.Fatalf("archive count = %d, want 3", len(archives)) - } - if !archives[0].ArchivedAt.After(archives[1].ArchivedAt) || !archives[1].ArchivedAt.After(archives[2].ArchivedAt) { - t.Fatalf("archives not sorted newest first: %#v", []time.Time{archives[0].ArchivedAt, archives[1].ArchivedAt, archives[2].ArchivedAt}) - } - - if err := os.WriteFile(filepath.Join(wikiDir, "stale.md"), []byte("stale"), 0o644); err != nil { - t.Fatalf("write stale wiki: %v", err) - } - restored, err := e.RestoreCampaignArchive(archive.ID) - if err != nil { - t.Fatalf("RestoreCampaignArchive() error = %v", err) - } - if restored.IdeaSlug != archive.ID || restored.Answers["audience"] != "operators" { - t.Fatalf("restored state = %#v", restored) - } - if _, err := os.Stat(filepath.Join(wikiDir, "stale.md")); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("stale wiki file err = %v, want not exist", err) - } - for name, want := range map[string]string{"a.md": "# first", "b.md": "# second"} { - got, err := os.ReadFile(filepath.Join(wikiDir, name)) - if err != nil { - t.Fatalf("read restored wiki %s: %v", name, err) - } - if string(got) != want { - t.Fatalf("restored wiki %s = %q, want %q", name, got, want) - } - } - if _, err := os.Stat(filepath.Join(wikiDir, "ignore.txt")); err != nil { - t.Fatalf("non-md wiki file should be left alone: %v", err) - } - - restored.Answers["audience"] = "mutated" - if got := e.GetState().Answers["audience"]; got != "operators" { - t.Fatalf("returned restore state aliases engine state, got %q", got) - } -} - -func TestCampaignArchiveLeaseReleaseAndRevise(t *testing.T) { - e := newTestEngine(t) - if _, err := e.Start("Lease and revise campaign"); err != nil { - t.Fatalf("Start() error = %v", err) - } - wikiDir := e.WikiDir() - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - t.Fatalf("mkdir wiki: %v", err) - } - if err := os.WriteFile(filepath.Join(wikiDir, "vision.md"), []byte("# vision"), 0o644); err != nil { - t.Fatalf("write wiki: %v", err) - } - archive, err := e.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("ArchiveCurrentCampaign() error = %v", err) - } - now := time.Date(2026, 9, 24, 12, 0, 0, 0, time.UTC) - - leased, err := e.LeaseCampaignArchive(archive.ID, "alice", "dashboard", now) - if err != nil { - t.Fatalf("LeaseCampaignArchive() error = %v", err) - } - if leased.Lease == nil || leased.Lease.Owner != "alice" || leased.Lease.Surface != "dashboard" || !leased.Lease.ExpiresAt.Equal(now.Add(campaignLeaseTTL)) { - t.Fatalf("lease = %#v", leased.Lease) - } - if _, err := e.LeaseCampaignArchive(archive.ID, "bob", "dashboard", now.Add(time.Minute)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("LeaseCampaignArchive by bob error = %v, want ErrCampaignLeaseHeld", err) - } - if _, err := e.ReleaseCampaignArchive(archive.ID, "bob", now.Add(time.Minute)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("ReleaseCampaignArchive by bob error = %v, want ErrCampaignLeaseHeld", err) - } - if released, err := e.ReleaseCampaignArchive(archive.ID, "alice", now.Add(time.Minute)); err != nil || released.Lease != nil { - t.Fatalf("ReleaseCampaignArchive by alice = %#v, %v", released, err) - } - if _, err := e.ReleaseCampaignArchive(archive.ID, "alice", now.Add(2*time.Minute)); !errors.Is(err, ErrCampaignNoLease) { - t.Fatalf("ReleaseCampaignArchive without lease error = %v, want ErrCampaignNoLease", err) - } - - revision, err := e.ReviseCampaignArchive(archive.ID, "", now) - if err != nil { - t.Fatalf("ReviseCampaignArchive() error = %v", err) - } - if revision.ID != archive.ID+"-rev-2" || revision.RevisionOf != archive.ID || revision.Revision != 2 { - t.Fatalf("revision identity = %#v", revision) - } - if revision.Lease == nil || revision.Lease.Owner != "local" || revision.Lease.Surface != "revise" { - t.Fatalf("revision lease = %#v", revision.Lease) - } - if revision.State == nil || revision.State.IdeaSlug != revision.ID || revision.State.Phase != PhaseCapture { - t.Fatalf("revision state = %#v", revision.State) - } - copiedWiki := filepath.Join(e.dataDir, inceptionCampaignsDir, revision.ID, inceptionArchiveWiki, "vision.md") - if got, err := os.ReadFile(copiedWiki); err != nil || string(got) != "# vision" { - t.Fatalf("revision wiki = %q, %v", got, err) - } - zeroNowRevision, err := e.ReviseCampaignArchive(revision.ID, "carol", time.Time{}) - if err != nil { - t.Fatalf("zero-now ReviseCampaignArchive() error = %v", err) - } - if zeroNowRevision.ID != archive.ID+"-rev-3" || zeroNowRevision.Revision != 3 || zeroNowRevision.Lease.Owner != "carol" { - t.Fatalf("zero-now revision = %#v", zeroNowRevision) - } - - second, err := e.ReviseCampaignArchive(archive.ID, "dana", now.Add(time.Minute)) - if err != nil { - t.Fatalf("second ReviseCampaignArchive() error = %v", err) - } - if second.ID != archive.ID+"-rev-4" || second.Revision != 4 || second.Lease.Owner != "dana" { - t.Fatalf("second revision = %#v", second) - } -} - -func TestCampaignArchiveErrorsAndExternalValidation(t *testing.T) { - e := newTestEngine(t) - if got, err := e.ArchiveCurrentCampaign(); got != nil || err != nil { - t.Fatalf("ArchiveCurrentCampaign with no state = %#v, %v", got, err) - } - archives, err := e.ListCampaignArchives() - if err != nil { - t.Fatalf("ListCampaignArchives empty error = %v", err) - } - if len(archives) != 0 { - t.Fatalf("empty archive list = %#v", archives) - } - - missingIDCalls := []struct { - name string - call func() error - }{ - {"load empty", func() error { _, err := e.LoadCampaignArchive(""); return err }}, - {"lease empty", func() error { _, err := e.LeaseCampaignArchive("", "owner", "", time.Time{}); return err }}, - {"restore empty", func() error { _, err := e.RestoreCampaignArchive(""); return err }}, - {"release empty", func() error { _, err := e.ReleaseCampaignArchive("", "owner", time.Time{}); return err }}, - {"revise empty", func() error { _, err := e.ReviseCampaignArchive("", "owner", time.Time{}); return err }}, - } - for _, tt := range missingIDCalls { - if err := tt.call(); err == nil || !strings.Contains(err.Error(), "campaign id required") { - t.Fatalf("%s error = %v, want campaign id required", tt.name, err) - } - } - if _, err := e.LoadCampaignArchive("does-not-exist"); err == nil || !strings.Contains(err.Error(), "not found") { - t.Fatalf("missing archive error = %v, want not found", err) - } - if _, err := e.ReviseExternalCampaign("", "title", "source", "engine", "type", "owner", nil, time.Time{}); err == nil || !strings.Contains(err.Error(), "campaign id required") { - t.Fatalf("ReviseExternalCampaign empty id error = %v", err) - } - - now := time.Date(2026, 9, 24, 13, 0, 0, 0, time.UTC) - external, err := e.ReviseExternalCampaign(" External Campaign ", " Title ", " Source ", "", "", "", []string{"org/repo"}, now) - if err != nil { - t.Fatalf("ReviseExternalCampaign() error = %v", err) - } - if external.ID != "external-campaign-rev-2" || external.RevisionOf != "external-campaign" || external.Revision != 2 { - t.Fatalf("external identity = %#v", external) - } - if external.Engine != "Spektacular" || external.Type != "spektacular" || external.Title != "Title" || external.Source != "Source" { - t.Fatalf("external metadata = %#v", external) - } - if external.Lease == nil || external.Lease.Owner != "local" || external.Lease.Surface != "revise" { - t.Fatalf("external lease = %#v", external.Lease) - } - if !reflect.DeepEqual(external.Repos, []string{"org/repo"}) { - t.Fatalf("external repos = %#v", external.Repos) - } - second, err := e.ReviseExternalCampaign("external-campaign", "Next", "", "Custom", "research", "dana", nil, time.Time{}) - if err != nil { - t.Fatalf("second ReviseExternalCampaign() error = %v", err) - } - if second.ID != "external-campaign-rev-3" || second.Engine != "Custom" || second.Type != "research" || second.Lease.Owner != "dana" { - t.Fatalf("second external = %#v", second) - } -} - -func TestCampaignArchivePreservesMetadataAndSkipsCorruptEntries(t *testing.T) { - e := newTestEngine(t) - state := &InceptionState{ - Phase: PhaseCapture, - Mode: InceptionGreenfield, - IdeaText: "preserve metadata", - IdeaSlug: "preserve-metadata", - Questions: []Question{{ID: "q1", Text: "Question?", Category: "features"}}, - Answers: map[string]string{"q1": "answer"}, - FactSlugs: []string{"fact-one"}, - StartedAt: time.Date(2026, 9, 24, 14, 0, 0, 0, time.UTC), - } - e.state = state - first, err := e.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("ArchiveCurrentCampaign() error = %v", err) - } - first.Title = "Saved title" - first.Source = "dashboard" - first.Repos = []string{"org/repo"} - first.RevisionOf = "root-campaign" - first.Revision = 4 - first.Lease = &CampaignLease{Owner: "alice", Surface: "dashboard", AcquiredAt: state.StartedAt, ExpiresAt: state.StartedAt.Add(campaignLeaseTTL)} - if err := e.writeArchiveStateLocked(first); err != nil { - t.Fatalf("writeArchiveStateLocked() error = %v", err) - } - - e.state.IdeaText = "updated body" - updated, err := e.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("second ArchiveCurrentCampaign() error = %v", err) - } - if updated.Title != first.Title || updated.Source != first.Source || updated.RevisionOf != first.RevisionOf || updated.Revision != first.Revision { - t.Fatalf("metadata not preserved: %#v", updated) - } - if updated.Lease == nil || updated.Lease.Owner != "alice" || !reflect.DeepEqual(updated.Repos, first.Repos) { - t.Fatalf("lease/repos not preserved: %#v", updated) - } - - root := filepath.Join(e.dataDir, inceptionCampaignsDir) - if err := os.WriteFile(filepath.Join(root, "not-a-dir"), []byte("ignored"), 0o644); err != nil { - t.Fatalf("write non-dir archive entry: %v", err) - } - corruptDir := filepath.Join(root, "corrupt") - if err := os.MkdirAll(corruptDir, 0o755); err != nil { - t.Fatalf("mkdir corrupt archive: %v", err) - } - if err := os.WriteFile(filepath.Join(corruptDir, inceptionArchiveState), []byte("{"), 0o644); err != nil { - t.Fatalf("write corrupt archive: %v", err) - } - archives, err := e.ListCampaignArchives() - if err != nil { - t.Fatalf("ListCampaignArchives() error = %v", err) - } - if len(archives) != 1 || archives[0].ID != first.ID { - t.Fatalf("archives after corrupt skip = %#v", archives) - } - - if err := e.writeArchiveLocked(nil); err != nil { - t.Fatalf("writeArchiveLocked(nil) error = %v", err) - } - if err := e.writeArchiveLocked(&InceptionCampaignArchive{ID: "missing-state"}); err != nil { - t.Fatalf("writeArchiveLocked without state error = %v", err) - } - if err := e.writeArchiveStateLocked(nil); err != nil { - t.Fatalf("writeArchiveStateLocked(nil) error = %v", err) - } -} - -func TestCampaignArchiveAdditionalErrorBranches(t *testing.T) { - e := newTestEngine(t) - state := &InceptionState{Phase: PhaseComplete, IdeaText: "no wiki", IdeaSlug: "no-wiki", Answers: map[string]string{}, StartedAt: time.Now()} - if err := e.writeArchiveLocked(&InceptionCampaignArchive{ID: state.IdeaSlug, ArchivedAt: state.StartedAt, State: state}); err != nil { - t.Fatalf("writeArchiveLocked() error = %v", err) - } - if revised, err := e.ReviseCampaignArchive(state.IdeaSlug, "owner", state.StartedAt); err != nil || revised.ID != "no-wiki-rev-2" { - t.Fatalf("ReviseCampaignArchive without wiki = %#v, %v", revised, err) - } - - expiredAt := state.StartedAt.Add(-2 * campaignLeaseTTL) - archive, err := e.LeaseCampaignArchive(state.IdeaSlug, "alice", "dashboard", expiredAt) - if err != nil { - t.Fatalf("initial LeaseCampaignArchive() error = %v", err) - } - if archive.Lease == nil || !archive.Lease.ExpiresAt.Before(state.StartedAt) { - t.Fatalf("expected expired lease, got %#v", archive.Lease) - } - refreshed, err := e.LeaseCampaignArchive(state.IdeaSlug, "bob", "dashboard", state.StartedAt) - if err != nil { - t.Fatalf("expired lease refresh error = %v", err) - } - if refreshed.Lease.Owner != "bob" { - t.Fatalf("expired lease owner = %q, want bob", refreshed.Lease.Owner) - } - if _, err := e.ReleaseCampaignArchive(state.IdeaSlug, "bob", state.StartedAt.Add(campaignLeaseTTL+time.Minute)); !errors.Is(err, ErrCampaignNoLease) { - t.Fatalf("expired release error = %v, want ErrCampaignNoLease", err) - } - - noState := &InceptionCampaignArchive{ID: "external-only", Engine: "Spektacular", Type: "spektacular", ArchivedAt: state.StartedAt} - if err := e.writeArchiveStateLocked(noState); err != nil { - t.Fatalf("write no-state archive: %v", err) - } - if _, err := e.RestoreCampaignArchive(noState.ID); err == nil || !strings.Contains(err.Error(), "has no inception state") { - t.Fatalf("RestoreCampaignArchive no state error = %v", err) - } - - archiveRoot := filepath.Join(e.dataDir, inceptionCampaignsDir, "id-backfilled") - if err := os.MkdirAll(archiveRoot, 0o755); err != nil { - t.Fatalf("mkdir raw archive: %v", err) - } - raw := `{"engine":"Spec Kit","type":"inception","archived_at":"2026-09-24T14:00:00Z","state":{"phase":"capture","idea_slug":"id-backfilled","answers":{},"started_at":"2026-09-24T14:00:00Z"}}` - if err := os.WriteFile(filepath.Join(archiveRoot, inceptionArchiveState), []byte(raw), 0o644); err != nil { - t.Fatalf("write raw archive: %v", err) - } - backfilled, err := e.LoadCampaignArchive("id-backfilled") - if err != nil { - t.Fatalf("LoadCampaignArchive backfilled error = %v", err) - } - if backfilled.ID != "id-backfilled" { - t.Fatalf("backfilled ID = %q", backfilled.ID) - } -} - -func TestCampaignArchiveSmallBranches(t *testing.T) { - e := newTestEngine(t) - if err := e.restoreArchiveWikiLocked("missing-wiki"); err != nil { - t.Fatalf("restoreArchiveWikiLocked missing wiki error = %v", err) - } - if copyInceptionState(nil) != nil { - t.Fatal("copyInceptionState(nil) should return nil") - } - e.state = &InceptionState{IdeaText: "fallback archive id", Answers: map[string]string{}, StartedAt: time.Now()} - if got := e.archiveFromStateLocked(time.Unix(123, 0)); got.ID != "inception-fallback-archive-id" { - t.Fatalf("fallback archive ID = %q", got.ID) - } - e.state = &InceptionState{Answers: map[string]string{}, StartedAt: time.Now()} - if got := e.archiveFromStateLocked(time.Unix(456, 0)); got.ID != "inception" { - t.Fatalf("empty fallback archive ID = %q", got.ID) - } - - state := &InceptionState{Phase: PhaseCapture, IdeaText: "default owner", IdeaSlug: "default-owner", Answers: map[string]string{}, StartedAt: time.Now()} - if err := e.writeArchiveLocked(&InceptionCampaignArchive{ID: state.IdeaSlug, ArchivedAt: state.StartedAt, State: state}); err != nil { - t.Fatalf("writeArchiveLocked() error = %v", err) - } - leased, err := e.LeaseCampaignArchive(state.IdeaSlug, " ", " surface ", time.Time{}) - if err != nil { - t.Fatalf("LeaseCampaignArchive default owner error = %v", err) - } - if leased.Lease == nil || leased.Lease.Owner != "local" || leased.Lease.Surface != "surface" || leased.Lease.AcquiredAt.IsZero() { - t.Fatalf("default lease = %#v", leased.Lease) - } - renewed, err := e.LeaseCampaignArchive(state.IdeaSlug, "local", "renewed", leased.Lease.AcquiredAt.Add(time.Minute)) - if err != nil { - t.Fatalf("same-owner LeaseCampaignArchive error = %v", err) - } - if renewed.Lease.Surface != "renewed" { - t.Fatalf("renewed lease surface = %q", renewed.Lease.Surface) - } - if _, err := e.ReleaseCampaignArchive(state.IdeaSlug, " ", time.Time{}); err != nil { - t.Fatalf("ReleaseCampaignArchive default owner error = %v", err) - } -} diff --git a/src/pkg/knowledge/inception_campaign_archive_test.go b/src/pkg/knowledge/inception_campaign_archive_test.go deleted file mode 100644 index d9611bd3ca..0000000000 --- a/src/pkg/knowledge/inception_campaign_archive_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package knowledge - -import ( - "errors" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestInceptionCampaignArchiveLeaseReviseAndRestore(t *testing.T) { - dir := t.TempDir() - engine := NewInceptionEngine(dir, nil, nil) - state, err := engine.Start("Collaborative Spektacular workspace") - if err != nil { - t.Fatalf("start inception: %v", err) - } - wikiDir := engine.WikiDir() - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - t.Fatalf("mkdir wiki: %v", err) - } - if err := os.WriteFile(filepath.Join(wikiDir, "spec.md"), []byte("# Spec\nOriginal"), 0o644); err != nil { - t.Fatalf("write wiki: %v", err) - } - - archived, err := engine.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("archive campaign: %v", err) - } - if archived.ID != state.IdeaSlug || archived.Engine != "Spec Kit" || archived.Type != "inception" { - t.Fatalf("archive identity = %+v, want slug %q", archived, state.IdeaSlug) - } - if len(archived.WikiFiles) != 1 || archived.WikiFiles[0] != "spec.md" { - t.Fatalf("archive wiki files = %+v", archived.WikiFiles) - } - - listed, err := engine.ListCampaignArchives() - if err != nil { - t.Fatalf("list archives: %v", err) - } - if len(listed) != 1 || listed[0].ID != archived.ID { - t.Fatalf("listed archives = %+v", listed) - } - - now := time.Date(2026, 9, 24, 12, 0, 0, 0, time.UTC) - leased, err := engine.LeaseCampaignArchive(archived.ID, "alice", "dashboard", now) - if err != nil { - t.Fatalf("lease archive: %v", err) - } - if leased.Lease == nil || leased.Lease.Owner != "alice" || leased.Lease.Surface != "dashboard" { - t.Fatalf("lease = %+v", leased.Lease) - } - if _, err := engine.LeaseCampaignArchive(archived.ID, "bob", "dashboard", now.Add(time.Minute)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("competing lease err = %v, want ErrCampaignLeaseHeld", err) - } - if _, err := engine.ReleaseCampaignArchive(archived.ID, "bob", now.Add(2*time.Minute)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("wrong owner release err = %v, want ErrCampaignLeaseHeld", err) - } - released, err := engine.ReleaseCampaignArchive(archived.ID, "alice", now.Add(3*time.Minute)) - if err != nil { - t.Fatalf("release archive: %v", err) - } - if released.Lease != nil { - t.Fatalf("released lease = %+v, want nil", released.Lease) - } - - revision, err := engine.ReviseCampaignArchive(archived.ID, "carol", now.Add(4*time.Minute)) - if err != nil { - t.Fatalf("revise archive: %v", err) - } - if revision.RevisionOf != archived.ID || revision.Revision != 2 || revision.Lease == nil || revision.Lease.Owner != "carol" { - t.Fatalf("revision = %+v", revision) - } - if revision.State == nil || revision.State.IdeaSlug != revision.ID || revision.State.Phase != PhaseCapture { - t.Fatalf("revision state = %+v", revision.State) - } - - if err := os.WriteFile(filepath.Join(wikiDir, "spec.md"), []byte("# Spec\nChanged"), 0o644); err != nil { - t.Fatalf("change active wiki: %v", err) - } - restored, err := engine.RestoreCampaignArchive(archived.ID) - if err != nil { - t.Fatalf("restore archive: %v", err) - } - if restored.IdeaSlug != archived.ID { - t.Fatalf("restored slug = %q, want %q", restored.IdeaSlug, archived.ID) - } - data, err := os.ReadFile(filepath.Join(wikiDir, "spec.md")) - if err != nil { - t.Fatalf("read restored wiki: %v", err) - } - if string(data) != "# Spec\nOriginal" { - t.Fatalf("restored wiki = %q", string(data)) - } -} - -func TestInceptionExternalCampaignRevisionDefaults(t *testing.T) { - engine := NewInceptionEngine(t.TempDir(), nil, nil) - now := time.Date(2026, 9, 24, 13, 0, 0, 0, time.UTC) - revision, err := engine.ReviseExternalCampaign("Owner/Repo#8687", "Jam Sessions", "owner/repo#8687", "", "", "", []string{"owner/repo"}, now) - if err != nil { - t.Fatalf("revise external campaign: %v", err) - } - if revision.ID == "" || revision.RevisionOf != "ownerrepo8687" || revision.Revision != 2 { - t.Fatalf("external revision identity = %+v", revision) - } - if revision.Engine != "Spektacular" || revision.Type != "spektacular" { - t.Fatalf("external revision kind = %s/%s", revision.Engine, revision.Type) - } - if revision.Lease == nil || revision.Lease.Owner != "local" || revision.Lease.Surface != "revise" { - t.Fatalf("external revision lease = %+v", revision.Lease) - } - - loaded, err := engine.LoadCampaignArchive(revision.ID) - if err != nil { - t.Fatalf("load external revision: %v", err) - } - if loaded.Title != "Jam Sessions" || len(loaded.Repos) != 1 || loaded.Repos[0] != "owner/repo" { - t.Fatalf("loaded external revision = %+v", loaded) - } -} - -// TestInceptionCampaignArchiveDelete pins hivecommons/hive#12698: deleting a -// revision removes only its directory (state + wiki snapshot), leaves the -// base archive and the working wiki intact, and clears the live session when -// the deleted id is the active one. -func TestInceptionCampaignArchiveDelete(t *testing.T) { - dir := t.TempDir() - engine := NewInceptionEngine(dir, nil, nil) - state, err := engine.StartBrownfield("https://github.com/hivecommons/hive") - if err != nil { - t.Fatalf("start brownfield: %v", err) - } - wikiDir := engine.WikiDir() - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - t.Fatalf("mkdir wiki: %v", err) - } - if err := os.WriteFile(filepath.Join(wikiDir, "scan.md"), []byte("# Scan"), 0o644); err != nil { - t.Fatalf("write wiki: %v", err) - } - if _, err := engine.ArchiveCurrentCampaign(); err != nil { - t.Fatalf("archive: %v", err) - } - if err := engine.Reset(); err != nil { - t.Fatalf("reset: %v", err) - } - revision, err := engine.ReviseCampaignArchive(state.IdeaSlug, "alice", time.Now()) - if err != nil { - t.Fatalf("revise: %v", err) - } - - deleted, err := engine.DeleteCampaignArchive(revision.ID) - if err != nil { - t.Fatalf("delete revision: %v", err) - } - if deleted.ID != revision.ID { - t.Fatalf("deleted id = %q, want %q", deleted.ID, revision.ID) - } - if _, err := os.Stat(filepath.Join(dir, inceptionCampaignsDir, revision.ID)); !os.IsNotExist(err) { - t.Fatalf("revision directory still present: %v", err) - } - if _, err := engine.LoadCampaignArchive(state.IdeaSlug); err != nil { - t.Fatalf("base archive removed with revision: %v", err) - } - if _, err := os.Stat(filepath.Join(wikiDir, "scan.md")); err != nil { - t.Fatalf("working wiki touched by delete: %v", err) - } - if _, err := engine.DeleteCampaignArchive(revision.ID); err == nil || !strings.Contains(err.Error(), "not found") { - t.Fatalf("second delete err = %v, want not found", err) - } - if _, err := engine.DeleteCampaignArchive(" "); err == nil { - t.Fatalf("blank id should be rejected") - } - - // Deleting the live session's campaign clears it too. - if _, err := engine.RestoreCampaignArchive(state.IdeaSlug); err != nil { - t.Fatalf("restore: %v", err) - } - if _, err := engine.DeleteCampaignArchive(state.IdeaSlug); err != nil { - t.Fatalf("delete active: %v", err) - } - if engine.GetState() != nil { - t.Fatalf("active state should be cleared after deleting its campaign") - } - if _, err := os.Stat(filepath.Join(dir, inceptionStateFile)); !os.IsNotExist(err) { - t.Fatalf("state file still present: %v", err) - } - listed, err := engine.ListCampaignArchives() - if err != nil || len(listed) != 0 { - t.Fatalf("archives after delete = %+v err=%v, want none", listed, err) - } -} diff --git a/src/pkg/knowledge/inception_campaigns_test.go b/src/pkg/knowledge/inception_campaigns_test.go deleted file mode 100644 index 40a672c3b9..0000000000 --- a/src/pkg/knowledge/inception_campaigns_test.go +++ /dev/null @@ -1,270 +0,0 @@ -package knowledge - -import ( - "errors" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func writeCampaignWiki(t *testing.T, e *InceptionEngine, files map[string]string) { - t.Helper() - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - if err := os.MkdirAll(wikiDir, 0o755); err != nil { - t.Fatalf("mkdir wiki: %v", err) - } - for name, body := range files { - path := filepath.Join(wikiDir, name) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatalf("mkdir wiki parent: %v", err) - } - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { - t.Fatalf("write wiki %s: %v", name, err) - } - } -} - -func readCampaignFile(t *testing.T, path string) string { - t.Helper() - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read %s: %v", path, err) - } - return string(data) -} - -func TestCampaignArchiveLifecycleLeaseReviseAndRestore(t *testing.T) { - e := newTestEngine(t) - state, err := e.Start("Durable campaign archive flow") - if err != nil { - t.Fatalf("Start: %v", err) - } - if err := e.SetQuestions([]Question{{ID: "goal", Text: "Goal?"}}); err != nil { - t.Fatalf("SetQuestions: %v", err) - } - if _, err := e.SubmitAnswers(map[string]string{"goal": "restore wiki"}); err != nil { - t.Fatalf("SubmitAnswers: %v", err) - } - writeCampaignWiki(t, e, map[string]string{ - "brief.md": "original brief", - "notes.md": "original notes", - "ignored.txt": "not archived", - "nested/skip.md": "nested file is skipped", - }) - - archive, err := e.ArchiveCurrentCampaign() - if err != nil { - t.Fatalf("ArchiveCurrentCampaign: %v", err) - } - if archive == nil { - t.Fatal("ArchiveCurrentCampaign returned nil archive") - } - if archive.ID != state.IdeaSlug { - t.Fatalf("archive ID = %q, want %q", archive.ID, state.IdeaSlug) - } - if archive.Engine != "Spec Kit" || archive.Type != "inception" { - t.Fatalf("archive engine/type = %q/%q", archive.Engine, archive.Type) - } - if got, want := strings.Join(archive.WikiFiles, ","), "brief.md,notes.md"; got != want { - t.Fatalf("archive wiki files = %q, want %q", got, want) - } - - archives, err := e.ListCampaignArchives() - if err != nil { - t.Fatalf("ListCampaignArchives: %v", err) - } - if len(archives) != 1 || archives[0].ID != archive.ID { - t.Fatalf("archives = %+v, want one archive %q", archives, archive.ID) - } - - loaded, err := e.LoadCampaignArchive(archive.ID) - if err != nil { - t.Fatalf("LoadCampaignArchive: %v", err) - } - loaded.State.Answers["goal"] = "mutated copy" - reloaded, err := e.LoadCampaignArchive(archive.ID) - if err != nil { - t.Fatalf("reload after copy mutation: %v", err) - } - if reloaded.State.Answers["goal"] != "restore wiki" { - t.Fatalf("archive state was aliased through load: %q", reloaded.State.Answers["goal"]) - } - - now := time.Date(2026, 9, 24, 18, 0, 0, 0, time.UTC) - leased, err := e.LeaseCampaignArchive(archive.ID, "alice", "resume", now) - if err != nil { - t.Fatalf("LeaseCampaignArchive alice: %v", err) - } - if leased.Lease == nil || leased.Lease.Owner != "alice" || leased.Lease.Surface != "resume" || !leased.Lease.ExpiresAt.Equal(now.Add(campaignLeaseTTL)) { - t.Fatalf("lease = %+v", leased.Lease) - } - if _, err := e.LeaseCampaignArchive(archive.ID, "bob", "resume", now.Add(time.Hour)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("conflicting lease err = %v, want ErrCampaignLeaseHeld", err) - } - if _, err := e.ReleaseCampaignArchive(archive.ID, "bob", now.Add(time.Hour)); !errors.Is(err, ErrCampaignLeaseHeld) { - t.Fatalf("conflicting release err = %v, want ErrCampaignLeaseHeld", err) - } - refreshed, err := e.LeaseCampaignArchive(archive.ID, "alice", "resume-again", now.Add(2*time.Hour)) - if err != nil { - t.Fatalf("LeaseCampaignArchive refresh: %v", err) - } - if refreshed.Lease.Surface != "resume-again" { - t.Fatalf("refreshed surface = %q", refreshed.Lease.Surface) - } - released, err := e.ReleaseCampaignArchive(archive.ID, "alice", now.Add(3*time.Hour)) - if err != nil { - t.Fatalf("ReleaseCampaignArchive alice: %v", err) - } - if released.Lease != nil { - t.Fatalf("release left lease = %+v", released.Lease) - } - if _, err := e.ReleaseCampaignArchive(archive.ID, "alice", now.Add(4*time.Hour)); !errors.Is(err, ErrCampaignNoLease) { - t.Fatalf("release without lease err = %v, want ErrCampaignNoLease", err) - } - - revision, err := e.ReviseCampaignArchive(archive.ID, "carol", now.Add(5*time.Hour)) - if err != nil { - t.Fatalf("ReviseCampaignArchive: %v", err) - } - if revision.ID != archive.ID+"-rev-2" || revision.RevisionOf != archive.ID || revision.Revision != 2 { - t.Fatalf("revision linkage = id:%q of:%q rev:%d", revision.ID, revision.RevisionOf, revision.Revision) - } - if revision.Lease == nil || revision.Lease.Owner != "carol" || revision.Lease.Surface != "revise" { - t.Fatalf("revision lease = %+v", revision.Lease) - } - if revision.State.IdeaSlug != revision.ID || revision.State.Phase != PhaseCapture { - t.Fatalf("revision state = slug:%q phase:%q", revision.State.IdeaSlug, revision.State.Phase) - } - revisionWiki := filepath.Join(e.dataDir, inceptionCampaignsDir, revision.ID, inceptionArchiveWiki, "brief.md") - if got := readCampaignFile(t, revisionWiki); got != "original brief" { - t.Fatalf("revision wiki brief = %q", got) - } - - if err := e.Reset(); err != nil { - t.Fatalf("Reset: %v", err) - } - writeCampaignWiki(t, e, map[string]string{ - "brief.md": "changed brief", - "stale.md": "remove on restore", - }) - restored, err := e.RestoreCampaignArchive(revision.ID) - if err != nil { - t.Fatalf("RestoreCampaignArchive: %v", err) - } - if restored.IdeaSlug != revision.ID || restored.Answers["goal"] != "restore wiki" { - t.Fatalf("restored state = %+v", restored) - } - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - if got := readCampaignFile(t, filepath.Join(wikiDir, "brief.md")); got != "original brief" { - t.Fatalf("restored brief = %q", got) - } - if _, err := os.Stat(filepath.Join(wikiDir, "stale.md")); !os.IsNotExist(err) { - t.Fatalf("stale wiki file err = %v, want not exist", err) - } -} - -func TestCampaignArchiveExternalReviseAndErrorPaths(t *testing.T) { - e := newTestEngine(t) - if archives, err := e.ListCampaignArchives(); err != nil || len(archives) != 0 { - t.Fatalf("empty ListCampaignArchives = len %d err %v", len(archives), err) - } - if archive, err := e.ArchiveCurrentCampaign(); err != nil || archive != nil { - t.Fatalf("nil-state ArchiveCurrentCampaign = archive %+v err %v", archive, err) - } - - missingID := "missing-campaign" - for name, run := range map[string]func() error{ - "load missing": func() error { _, err := e.LoadCampaignArchive(missingID); return err }, - "lease missing": func() error { _, err := e.LeaseCampaignArchive(missingID, "alice", "resume", time.Time{}); return err }, - "release missing": func() error { _, err := e.ReleaseCampaignArchive(missingID, "alice", time.Time{}); return err }, - "revise missing": func() error { _, err := e.ReviseCampaignArchive(missingID, "alice", time.Time{}); return err }, - "restore missing": func() error { _, err := e.RestoreCampaignArchive(missingID); return err }, - "bad id": func() error { _, err := e.LoadCampaignArchive("../.."); return err }, - } { - t.Run(name, func(t *testing.T) { - if err := run(); err == nil { - t.Fatal("expected error") - } - }) - } - - outside := filepath.Join(e.dataDir, "escaped", inceptionArchiveState) - if err := os.MkdirAll(filepath.Dir(outside), 0o755); err != nil { - t.Fatalf("mkdir escaped fixture: %v", err) - } - if err := os.WriteFile(outside, []byte(`{"id":"escaped"}`), 0o644); err != nil { - t.Fatalf("write escaped fixture: %v", err) - } - if _, err := e.LoadCampaignArchive("../escaped"); err == nil { - t.Fatal("path traversal load unexpectedly found archive outside campaigns dir") - } - - now := time.Date(2026, 9, 24, 19, 0, 0, 0, time.UTC) - external, err := e.ReviseExternalCampaign("External Campaign", "External Title", "https://example.invalid/campaign", "", "", "", []string{"hivecommons/hive"}, now) - if err != nil { - t.Fatalf("ReviseExternalCampaign: %v", err) - } - if external.ID != "external-campaign-rev-2" || external.RevisionOf != "external-campaign" || external.Revision != 2 { - t.Fatalf("external revision linkage = id:%q of:%q rev:%d", external.ID, external.RevisionOf, external.Revision) - } - if external.Engine != "Spektacular" || external.Type != "spektacular" || external.Lease == nil || external.Lease.Owner != "local" { - t.Fatalf("external defaults/lease = engine:%q type:%q lease:%+v", external.Engine, external.Type, external.Lease) - } - loaded, err := e.LoadCampaignArchive(external.ID) - if err != nil { - t.Fatalf("load external revision: %v", err) - } - if loaded.Title != "External Title" || loaded.Source != "https://example.invalid/campaign" || len(loaded.Repos) != 1 || loaded.Repos[0] != "hivecommons/hive" { - t.Fatalf("external round trip = %+v", loaded) - } - if _, err := e.RestoreCampaignArchive(external.ID); err == nil || !strings.Contains(err.Error(), "no inception state") { - t.Fatalf("restore external err = %v, want no inception state", err) - } - - second, err := e.ReviseExternalCampaign("External Campaign", "External Title 2", "source", "Other", "custom", "dana", nil, now.Add(time.Hour)) - if err != nil { - t.Fatalf("second ReviseExternalCampaign: %v", err) - } - if second.ID != "external-campaign-rev-3" || second.Engine != "Other" || second.Type != "custom" || second.Lease.Owner != "dana" { - t.Fatalf("second external revision = %+v", second) - } - if _, err := e.ReviseExternalCampaign("../..", "bad", "", "", "", "", nil, now); err == nil { - t.Fatal("ReviseExternalCampaign accepted path traversal/empty id") - } -} - -func TestCampaignArchiveExpiredLeaseAndArchiveFallbackID(t *testing.T) { - e := newTestEngine(t) - now := time.Date(2026, 9, 24, 20, 0, 0, 0, time.UTC) - e.state = &InceptionState{Phase: PhaseCapture, IdeaText: "!!!", Answers: map[string]string{}, StartedAt: now} - archive := e.archiveFromStateLocked(now) - if archive.ID != "inception" { - t.Fatalf("sanitized archive id = %q, want inception", archive.ID) - } - if err := e.writeArchiveLocked(archive); err != nil { - t.Fatalf("writeArchiveLocked fallback: %v", err) - } - leased, err := e.LeaseCampaignArchive(archive.ID, "alice", "resume", now) - if err != nil { - t.Fatalf("LeaseCampaignArchive: %v", err) - } - if leased.Lease == nil { - t.Fatal("expected lease") - } - released, err := e.ReleaseCampaignArchive(archive.ID, "bob", now.Add(2*campaignLeaseTTL)) - if !errors.Is(err, ErrCampaignNoLease) { - t.Fatalf("expired release err = %v, want ErrCampaignNoLease", err) - } - if released != nil { - t.Fatalf("expired release archive = %+v, want nil", released) - } - loaded, err := e.LoadCampaignArchive(archive.ID) - if err != nil { - t.Fatalf("load after expired release: %v", err) - } - if loaded.Lease != nil { - t.Fatalf("expired release did not clear lease: %+v", loaded.Lease) - } -} diff --git a/src/pkg/knowledge/inception_coverage_boost_test.go b/src/pkg/knowledge/inception_coverage_boost_test.go deleted file mode 100644 index e0cff0ff34..0000000000 --- a/src/pkg/knowledge/inception_coverage_boost_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package knowledge - -import ( - "context" - "os" - "path/filepath" - "testing" -) - -func TestBuildTestStubsAllLanguages(t *testing.T) { - acceptance := []Fact{{Title: "Test 1", Body: "Verify it works"}} - langs := []struct { - body string - lang string - }{ - {"Go project", "go"}, - {"TypeScript React app", "typescript"}, - {"Python FastAPI service", "python"}, - {"Rust tokio service", "rust"}, - {"Java Spring Boot app", "java"}, - {"Shell scripts", "shell"}, - } - for _, tt := range langs { - got := buildTestStubs(acceptance, tt.lang) - if got == "" { - t.Errorf("buildTestStubs(%q) should produce output", tt.lang) - } - } -} - -func TestBuildTestStubsDefaultLang(t *testing.T) { - acceptance := []Fact{{Title: "Test", Body: "Works"}} - got := buildTestStubs(acceptance, "") - if got == "" { - t.Error("empty lang should default to Go test stubs") - } -} - -func TestBuildNightlyCIAllLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell", "javascript"} - for _, lang := range langs { - got := buildNightlyCI(lang) - if got == "" { - t.Errorf("buildNightlyCI(%q) should produce output", lang) - } - } -} - -func TestBuildMakefileAllLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell"} - for _, lang := range langs { - got := buildMakefile(lang, "myproject", "cli") - if got == "" { - t.Errorf("buildMakefile(%q) should produce output", lang) - } - } -} - -func TestBuildI18nFileMultipleLocales(t *testing.T) { - locales := []string{"en", "es", "fr", "de"} - for _, locale := range locales { - got := buildI18nFile(locale, "myproject") - if got == "" { - t.Errorf("buildI18nFile(%q) should produce output", locale) - } - } -} - -func TestBuildGitignoreAllLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell", "javascript", "unknown"} - for _, lang := range langs { - got := buildGitignore(lang) - if got == "" { - t.Errorf("buildGitignore(%q) should produce output", lang) - } - } -} - -func TestBuildDockerfileAllLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell", "unknown"} - for _, lang := range langs { - got := buildDockerfile(lang, "myproject") - if got == "" { - t.Errorf("buildDockerfile(%q) should produce output", lang) - } - } -} - -func TestBuildReadmeWithAllFacts(t *testing.T) { - vision := &Fact{Title: "My Project", Body: "A tool for everything"} - constitution := &Fact{Body: "Go microservice"} - reqs := []Fact{ - {Title: "Req 1", Body: "Fast"}, - {Title: "Req 2", Body: "Scalable"}, - } - constraints := []Fact{ - {Title: "Constraint 1", Body: "No external deps"}, - } - stakeholders := []Fact{ - {Title: "Team A", Body: "Backend"}, - {Title: "Team B", Body: "Frontend"}, - } - - got := buildReadme("build a tool", "go", "build a tool", vision, constitution, reqs, constraints, stakeholders) - if got == "" { - t.Error("should produce README") - } -} - -func TestBuildReadmeNoVision(t *testing.T) { - got := buildReadme("idea text", "go", "idea text", nil, nil, nil, nil, nil) - if got == "" { - t.Error("should produce README with defaults") - } -} - -func TestBuildContributingAllLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell"} - for _, lang := range langs { - got := buildContributing("myproject", lang, &Fact{Body: lang + " project"}) - if got == "" { - t.Errorf("buildContributing(%q) should produce output", lang) - } - } -} - -func TestBuildShellMainNoVision(t *testing.T) { - got := buildShellMain("mytool", nil) - if got == "" { - t.Error("nil vision should still produce shell main") - } -} - -func TestBuildRustMainNoVision(t *testing.T) { - got := buildRustMain("myproject", nil) - if got == "" { - t.Error("nil vision should still produce rust main") - } -} - -func TestBuildJavaMainNoVision(t *testing.T) { - got := buildJavaMain("myproject", nil) - if got == "" { - t.Error("nil vision should still produce java main") - } -} - -func TestBuildK8sOverlayKustomizationMultipleEnvs(t *testing.T) { - envs := []string{"dev", "staging", "production"} - for _, env := range envs { - got := buildK8sOverlayKustomization("myproject", env) - if got == "" { - t.Errorf("buildK8sOverlayKustomization(%q) should produce output", env) - } - } -} - -func TestInferProjectTypeMoreCases(t *testing.T) { - tests := []struct { - body string - want string - }{ - {"Kubernetes operator with CRDs", "kubernetes"}, - {"Helm chart for deployment", "kubernetes"}, - {"Docker container service", "container"}, - {"SDK and client library", "library"}, - {"REST API server", "api"}, - {"CLI command tool", "cli"}, - } - for _, tt := range tests { - got := inferProjectType(&Fact{Body: tt.body}, nil, nil) - if got != tt.want { - t.Errorf("inferProjectType(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestInferTestPathAllLanguages(t *testing.T) { - tests := []struct { - body string - want string - }{ - {"Go project", "main_test.go"}, - {"TypeScript app", "src/__tests__/acceptance.test.ts"}, - {"Python service", "tests/test_acceptance.py"}, - {"Rust crate", "main_test.go"}, - {"Java app", "main_test.go"}, - } - for _, tt := range tests { - got := inferTestPath(&Fact{Body: tt.body}) - if got != tt.want { - t.Errorf("inferTestPath(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestRepoBaseNameEdgeCases(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"", "repo"}, - {"simple", "simple"}, - {"https://github.com/org/repo.git", "repo"}, - {"git@github.com:org/project.git", "project"}, - {"/path/to/local/repo", "repo"}, - } - for _, tt := range tests { - got := repoBaseName(tt.input) - if got != tt.want { - t.Errorf("repoBaseName(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestProduceScaffoldAllLanguages(t *testing.T) { - langs := []struct { - body string - lang string - }{ - {"TypeScript React application", "typescript"}, - {"Python FastAPI service", "python"}, - {"Rust tokio server", "rust"}, - {"Java Spring Boot", "java"}, - {"Shell automation scripts", "shell"}, - } - - for _, tt := range langs { - e := newTestEngine(t) - e.Start("build a " + tt.lang + " project") - - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - constFact := "---\ntitle: Architecture\ntype: constitution\n---\n" + tt.body - os.WriteFile(filepath.Join(wikiDir, "const.md"), []byte(constFact), 0644) - - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.TODO()) - if err != nil { - t.Fatalf("%s: error: %v", tt.lang, err) - } - if result == nil || len(result.Files) == 0 { - t.Errorf("%s: should produce files", tt.lang) - } - } -} diff --git a/src/pkg/knowledge/inception_edge2_test.go b/src/pkg/knowledge/inception_edge2_test.go deleted file mode 100644 index f2b958ad77..0000000000 --- a/src/pkg/knowledge/inception_edge2_test.go +++ /dev/null @@ -1,819 +0,0 @@ -package knowledge - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestProduceScaffoldAllLanguagesContent(t *testing.T) { - langs := []struct { - idea string - wantExt string - wantFile string - }{ - {"A Go CLI tool", ".go", "go.mod"}, - {"A Python tool", ".py", "pyproject.toml"}, - {"A Rust service", ".rs", "Cargo.toml"}, - {"A TypeScript app", ".ts", "tsconfig.json"}, - {"A Java service", ".java", "pom.xml"}, - {"A JavaScript tool", ".js", "package.json"}, - {"A Shell script", ".sh", ""}, - } - - for _, tt := range langs { - t.Run(tt.idea, func(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - _, err := e.Start(tt.idea) - if err != nil { - t.Fatal(err) - } - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(result.Files) == 0 { - t.Fatal("no files produced") - } - - // Check language-specific files exist - hasExt := false - hasFile := false - for _, f := range result.Files { - if len(tt.wantExt) > 0 && endsWith(f.Path, tt.wantExt) { - hasExt = true - } - if tt.wantFile != "" && f.Path == tt.wantFile { - hasFile = true - } - // Check no cross-contamination - if tt.idea == "A Python tool" && endsWith(f.Path, ".go") && f.Path != ".gitignore" { - t.Errorf("Python idea should not have .go file: %s", f.Path) - } - if tt.idea == "A Go CLI tool" && endsWith(f.Path, ".py") { - t.Errorf("Go idea should not have .py file: %s", f.Path) - } - if tt.idea == "A Rust service" && endsWith(f.Path, ".java") { - t.Errorf("Rust idea should not have .java file: %s", f.Path) - } - } - if !hasExt { - paths := "" - for _, f := range result.Files { - paths += f.Path + " " - } - t.Errorf("no %s file found in: %s", tt.wantExt, paths) - } - if tt.wantFile != "" && !hasFile { - t.Errorf("expected %s not found", tt.wantFile) - } - }) - } -} - -func endsWith(s, suffix string) bool { - return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix -} - -func TestStartWithMaxLengthIdea(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - // Exactly 4000 chars (max allowed) - idea := "A Python tool that " - for len(idea) < 4000 { - idea += "x" - } - idea = idea[:4000] - - _, err := e.Start(idea) - if err != nil { - t.Fatalf("4000-char idea should be accepted: %v", err) - } -} - -func TestStartWithOverMaxLengthIdea(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - idea := "A Python tool that " - for len(idea) < 4001 { - idea += "x" - } - - _, err := e.Start(idea) - if err == nil { - t.Error("4001-char idea should be rejected") - } -} - -func TestSubmitAnswersWithEmptyValue(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go tool") - - e.mu.Lock() - e.state.Phase = PhaseClarify - e.state.Questions = []Question{ - {ID: "q1", Text: "What?", Category: "general"}, - } - e.mu.Unlock() - - _, err := e.SubmitAnswers(map[string]string{"q1": " "}) - if err == nil { - t.Error("whitespace-only answer should be rejected") - } -} - -func TestResetIdempotent(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - // Reset with no active inception - err := e.Reset() - if err != nil { - t.Fatalf("reset with no inception should not error: %v", err) - } - - // Start and reset - e.Start("Test idea") - err = e.Reset() - if err != nil { - t.Fatalf("reset should not error: %v", err) - } - - // Double reset - err = e.Reset() - if err != nil { - t.Fatalf("double reset should not error: %v", err) - } - - state := e.GetState() - if state != nil { - t.Error("state should be nil after reset") - } -} - -func TestAdvanceToCompletePhaseGuard(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test") - - // capture phase - err := e.AdvanceToComplete() - if err == nil { - t.Error("should reject advance from capture phase") - } - - // clarify phase - e.mu.Lock() - e.state.Phase = PhaseClarify - e.mu.Unlock() - err = e.AdvanceToComplete() - if err == nil { - t.Error("should reject advance from clarify phase") - } - - // structure phase - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - err = e.AdvanceToComplete() - if err == nil { - t.Error("should reject advance from structure phase") - } - - // scaffold phase — should work - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - err = e.AdvanceToComplete() - if err != nil { - t.Errorf("should accept advance from scaffold: %v", err) - } - - // complete phase — idempotent - err = e.AdvanceToComplete() - if err != nil { - t.Errorf("should accept advance from complete (idempotent): %v", err) - } -} - -func TestInferLanguageFromTextEdgeCases(t *testing.T) { - tests := []struct { - text string - want string - }{ - {"A Django REST API", ""}, // django not checked in inferLanguageFromText (only inferLanguage) - {"Build with Cargo", ""}, // cargo not in inferLanguageFromText - {"A tool using Golang", "go"}, // golang keyword - {"Use Go for this project", "go"}, // "go" as whole word - {"Logo design tool", ""}, // "logo" contains "go" but not as word boundary - {"A JavaScript AND Java app", "javascript"}, // javascript matched first - {"", ""}, // empty - {"Cargo is a Go tool", "go"}, // "go" as word, "cargo" doesn't match - {"Let's go build something", "go"}, // "go" preceded by space - } - for _, tt := range tests { - got := inferLanguageFromText(tt.text) - if got != tt.want { - t.Errorf("inferLanguageFromText(%q) = %q, want %q", tt.text, got, tt.want) - } - } -} - -func TestInferLanguageFalsePositives(t *testing.T) { - tests := []struct { - body string - want string - }{ - // Words containing "rust" should NOT match Rust - {"Build a trustworthy service", "go"}, - {"Handle frustrated users gracefully", "go"}, - // But actual Rust should match - {"Build with Rust and tokio", "rust"}, - {"Use Cargo for dependency management", "rust"}, - // Words containing "java" should NOT match Java (unless it IS java) - {"A Java Spring Boot service", "java"}, - // Words containing "shell" should NOT match Shell - {"Protect against shellshock vulnerabilities", "go"}, - {"A nutshell guide to APIs", "go"}, - // But actual shell should match - {"Write a bash automation script", "shell"}, - // "pip" inside "pipeline" should still match python (it's a framework keyword) - {"Build a data pipeline with pip", "python"}, - } - for _, tt := range tests { - fact := &Fact{Body: tt.body} - got := inferLanguage(fact) - if got != tt.want { - t.Errorf("inferLanguage(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestContainsWord(t *testing.T) { - tests := []struct { - text string - word string - want bool - }{ - {"hello go world", "go", true}, - {"go build", "go", true}, - {"use go", "go", true}, - {"logo design", "go", false}, - {"cargo build", "go", false}, - {"ergo sum", "go", false}, - {"golang tools", "go", false}, // "go" in "golang" is not word-bounded - {"let's go!", "go", true}, // punctuation after - {"a go-tool", "go", true}, // hyphen after (not alpha) - {"", "go", false}, - {"go", "go", true}, // exact match - {"GO", "go", false}, // case sensitive - {"trust me", "rust", false}, - {"rust lang", "rust", true}, - {"in rust we trust", "rust", true}, - } - for _, tt := range tests { - got := containsWord(tt.text, tt.word) - if got != tt.want { - t.Errorf("containsWord(%q, %q) = %v, want %v", tt.text, tt.word, got, tt.want) - } - } -} - -func TestInferProjectTypeEdgeCases(t *testing.T) { - tests := []struct { - body string - want string - }{ - {"Build a REST API backend", "api"}, - {"Create a CLI tool", "cli"}, - {"Build a web frontend with React", "ui"}, - {"Create a reusable library", "library"}, - {"Kubernetes operator for deployments", "kubernetes"}, - {"A simple script", "cli"}, // default - {"Deploy a containerized service", "container"}, // "container" keyword - {"Manage Docker containers", "container"}, // "docker" keyword - } - for _, tt := range tests { - constitution := &Fact{Body: tt.body} - got := inferProjectType(constitution, nil, nil) - if got != tt.want { - t.Errorf("inferProjectType(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestRecordFactsPhaseGuard(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test") - - facts := []IdeationFact{ - {Title: "Vision", Body: "A tool", Type: FactVision}, - } - - // capture phase — should fail - err := e.RecordFacts(context.Background(), facts) - if err == nil { - t.Error("should reject facts in capture phase") - } - - // structure phase — should work - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - err = e.RecordFacts(context.Background(), facts) - if err != nil { - t.Errorf("should accept facts in structure phase: %v", err) - } - - // scaffold phase — should fail (already recorded) - err = e.RecordFacts(context.Background(), facts) - if err == nil { - t.Error("should reject facts in scaffold phase") - } -} - -func TestRecordFactsValidation(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - // Empty facts - err := e.RecordFacts(context.Background(), nil) - if err == nil { - t.Error("should reject nil facts") - } - - // Empty title - err = e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "", Body: "content", Type: FactVision}, - }) - if err == nil { - t.Error("should reject empty title") - } - - // Empty body - err = e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Vision", Body: "", Type: FactVision}, - }) - if err == nil { - t.Error("should reject empty body") - } -} - -func TestGetStateDeepCopy(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test idea") - - state1 := e.GetState() - state2 := e.GetState() - - // Mutating state1 should not affect state2 - state1.IdeaText = "MUTATED" - if state2.IdeaText == "MUTATED" { - t.Error("GetState should return deep copies — mutation propagated") - } - - // Mutating answers map - state1.Answers["new_key"] = "new_value" - if _, exists := state2.Answers["new_key"]; exists { - t.Error("GetState should return deep copies — map mutation propagated") - } -} - -func TestStartBrownfieldValidation(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - // Empty URL - _, err := e.StartBrownfield("") - if err == nil { - t.Error("should reject empty URL") - } - - // No https prefix - _, err = e.StartBrownfield("github.com/org/repo") - if err == nil { - t.Error("should reject non-https URL") - } - - // Valid URL - state, err := e.StartBrownfield("https://github.com/org/repo") - if err != nil { - t.Fatal(err) - } - if state.Mode != InceptionBrownfield { - t.Errorf("mode = %q, want brownfield", state.Mode) - } - if state.RepoURL != "https://github.com/org/repo" { - t.Errorf("repo URL not preserved: %q", state.RepoURL) - } - - // Second start without reset should fail - _, err = e.StartBrownfield("https://github.com/org/repo2") - if err == nil { - t.Error("should reject second start without reset") - } -} - -func TestStartBrownfieldURLMaxLength(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - // Very long URL (>2000 chars) - longURL := "https://github.com/org/" - for len(longURL) < 2001 { - longURL += "x" - } - _, err := e.StartBrownfield(longURL) - if err == nil { - t.Error("should reject URL over 2000 chars") - } -} - -func TestConcurrentGetState(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test") - - // Concurrent reads should not race - done := make(chan bool, 10) - for i := 0; i < 10; i++ { - go func() { - state := e.GetState() - if state == nil { - t.Error("state should not be nil during concurrent read") - } - done <- true - }() - } - for i := 0; i < 10; i++ { - <-done - } -} - -func TestInferLanguageSubstringFalsePositives(t *testing.T) { - tests := []struct { - body string - notWant string - desc string - }{ - {"My favorite build tool", "javascript", "favorite contains vite"}, - {"Send an invite to the team", "javascript", "invite contains vite"}, - {"Build a pipeline for data", "python", "pipeline contains pip"}, - // "warp speed" — "warp" is a standalone word and a Rust framework. - // This is an inherent ambiguity, not a substring bug. Accepted as-is. - } - for _, tt := range tests { - fact := &Fact{Body: tt.body} - got := inferLanguage(fact) - if got == tt.notWant { - t.Errorf("inferLanguage(%q) = %q — false positive: %s", tt.body, got, tt.desc) - } - } -} - -func TestInferLanguagePriority(t *testing.T) { - // When constitution mentions multiple languages, the first match wins - tests := []struct { - body string - want string - }{ - // TypeScript keywords checked first - {"Use React with Python backend", "typescript"}, - {"Angular frontend, Java backend", "typescript"}, - // Python keywords checked second - {"Django app with some JavaScript", "python"}, - {"FastAPI service", "python"}, - // Explicit language names with word boundaries - {"Build in Rust, deploy to Kubernetes", "rust"}, - {"Java microservice with Docker", "java"}, - } - for _, tt := range tests { - fact := &Fact{Body: tt.body} - got := inferLanguage(fact) - if got != tt.want { - t.Errorf("inferLanguage(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestContainsWordBoundaries(t *testing.T) { - // Exhaustive boundary tests - tests := []struct { - text string - word string - want bool - }{ - // Start of string - {"go is great", "go", true}, - {"gopher", "go", false}, - // End of string - {"I love go", "go", true}, - {"cargo", "go", false}, - // Surrounded by punctuation - {"(go)", "go", true}, - {"[go]", "go", true}, - {`"go"`, "go", true}, - {"go.", "go", true}, - {"go,", "go", true}, - {"go;", "go", true}, - {"go!", "go", true}, - {"go?", "go", true}, - // Numbers adjacent - {"go2", "go", true}, // digit after = word boundary (digits aren't alpha) - {"2go", "go", true}, // digit before = word boundary - } - for _, tt := range tests { - got := containsWord(tt.text, tt.word) - if got != tt.want { - t.Errorf("containsWord(%q, %q) = %v, want %v", tt.text, tt.word, got, tt.want) - } - } -} - -func TestProduceScaffoldWithFacts(t *testing.T) { - // Test with actual facts to verify scaffold quality - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Python REST API for managing tasks") - - // Simulate structure phase with facts - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - facts := []IdeationFact{ - {Title: "Task Management API", Body: "A RESTful API for CRUD operations on tasks", Type: FactVision}, - {Title: "Python 3.12, FastAPI, SQLAlchemy", Body: "Use Python 3.12 with FastAPI framework and SQLAlchemy ORM", Type: FactConstitution}, - {Title: "CRUD endpoints", Body: "Create, read, update, delete tasks via REST", Type: FactRequirement}, - {Title: "Authentication", Body: "JWT-based auth for all endpoints", Type: FactRequirement}, - {Title: "PostgreSQL only", Body: "Must use PostgreSQL as the database", Type: FactConstraint}, - } - err := e.RecordFacts(context.Background(), facts) - if err != nil { - t.Fatal(err) - } - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // Should have Python files - hasPy := false - hasPyproject := false - for _, f := range result.Files { - if endsWith(f.Path, ".py") { - hasPy = true - } - if f.Path == "pyproject.toml" { - hasPyproject = true - } - // Should NOT have Go files - if f.Path == "go.mod" || f.Path == "main.go" { - t.Errorf("Python API should not have Go file: %s", f.Path) - } - } - if !hasPy { - t.Error("should have .py files") - } - if !hasPyproject { - t.Error("should have pyproject.toml") - } - - // README should mention the project - for _, f := range result.Files { - if f.Path == "README.md" { - if !strings.Contains(f.Content, "Task Management") { - t.Error("README should mention the vision title") - } - break - } - } -} - -func TestInferProjectTypeFalsePositives(t *testing.T) { - tests := []struct { - body string - notWant string - desc string - }{ - {"Send an invite to users", "ui", "invite contains vite"}, - {"My favorite deployment tool", "ui", "favorite contains vite"}, - // But actual vite should match - {"Build with Vite and React", "cli", "actual Vite framework should be ui"}, - } - for _, tt := range tests { - fact := &Fact{Body: tt.body} - got := inferProjectType(fact, nil, nil) - if got == tt.notWant { - t.Errorf("inferProjectType(%q) = %q — false positive: %s", tt.body, got, tt.desc) - } - } - - // Positive test: actual Vite should match ui - viteFact := &Fact{Body: "Build with Vite and React"} - if got := inferProjectType(viteFact, nil, nil); got != "ui" { - t.Errorf("Vite project should be ui, got %q", got) - } -} - -func TestWriteFactsToVaultInvalidDir(t *testing.T) { - // Create engine with a path that can't be created - e := NewInceptionEngine("/dev/null/impossible", nil, nil) - e.mu.Lock() - e.state = &InceptionState{ - Phase: PhaseStructure, - IdeaText: "test", - } - e.mu.Unlock() - - // Should not panic — just log a warning - e.writeFactsToVault([]IdeationFact{ - {Title: "Test", Body: "Body", Type: FactVision}, - }) -} - -func TestSaveStateInvalidDir(t *testing.T) { - e := NewInceptionEngine("/dev/null/impossible", nil, nil) - e.mu.Lock() - e.state = &InceptionState{ - Phase: PhaseCapture, - IdeaText: "test", - Answers: make(map[string]string), - } - e.mu.Unlock() - - // saveState should return error, not panic - err := e.saveState() - if err == nil { - t.Error("saveState to invalid path should return error") - } -} - -func TestParseInceptionFactFileEdgeCases(t *testing.T) { - tests := []struct { - name string - content string - wantErr bool - }{ - {"normal", "---\ntitle: Test\ntype: requirement\nconfidence: 0.8\n---\nBody text", false}, - {"no frontmatter", "Just body text without frontmatter", false}, - {"empty", "", false}, - {"unclosed frontmatter", "---\ntitle: Test\nno closing delimiter", false}, - {"empty frontmatter", "---\n---\nBody after empty frontmatter", false}, - {"special chars in title", "---\ntitle: \"Test with \\\"quotes\\\"\"\ntype: vision\n---\nBody", false}, - {"missing title", "---\ntype: requirement\n---\nBody", false}, - {"invalid confidence", "---\nconfidence: notanumber\n---\nBody", false}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Should never panic - title, body, factType, confidence := parseInceptionFactFile(tt.content, "test.md") - _ = title - _ = body - _ = factType - _ = confidence - }) - } -} - -func TestGatherFactsEmptyWiki(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test") - - // Wiki dir doesn't exist yet - facts := e.GatherFactsPublic(context.Background()) - // Should return some facts (at least the idea fact) - // or nil if wiki doesn't exist - _ = facts // just verify no panic -} - -func TestGatherFactsWithFiles(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test idea") - - // Write some wiki files - wikiDir := e.WikiDir() - os.MkdirAll(wikiDir, 0o755) - os.WriteFile(filepath.Join(wikiDir, "vision-test.md"), []byte("---\ntitle: Test Vision\ntype: vision\nconfidence: 0.9\n---\nA test project"), 0o644) - os.WriteFile(filepath.Join(wikiDir, "req-feature.md"), []byte("---\ntitle: Feature X\ntype: requirement\n---\nMust have feature X"), 0o644) - os.WriteFile(filepath.Join(wikiDir, "not-markdown.txt"), []byte("should be ignored"), 0o644) - - facts := e.GatherFactsPublic(context.Background()) - if len(facts) != 2 { - t.Errorf("expected 2 facts (skipping .txt), got %d", len(facts)) - } - - // Check fact types parsed correctly - hasVision := false - hasReq := false - for _, f := range facts { - if f.Type == FactVision { - hasVision = true - if f.Confidence != 0.9 { - t.Errorf("vision confidence = %f, want 0.9", f.Confidence) - } - } - if f.Type == FactRequirement { - hasReq = true - } - } - if !hasVision { - t.Error("should have a vision fact") - } - if !hasReq { - t.Error("should have a requirement fact") - } -} - -func TestContainsWordPerformance(t *testing.T) { - // Pathological input — long string with many near-matches - long := strings.Repeat("goo ", 10000) - result := containsWord(long, "go") - if result { - t.Error("should not find 'go' in 'goo goo goo...'") - } - - // Another pathological case — word at very end - long2 := strings.Repeat("x ", 10000) + "go" - result2 := containsWord(long2, "go") - if !result2 { - t.Error("should find 'go' at end of long string") - } -} - -func TestSubmitAnswersInvalidKey(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go tool") - e.mu.Lock() - e.state.Phase = PhaseClarify - e.state.Questions = []Question{ - {ID: "q1", Text: "What?"}, - {ID: "q2", Text: "Who?"}, - } - e.mu.Unlock() - - // Answer with non-existent key - _, err := e.SubmitAnswers(map[string]string{"nonexistent": "value"}) - if err == nil { - t.Error("should reject answer key not matching any question ID") - } - - // Mix valid and invalid keys - _, err = e.SubmitAnswers(map[string]string{"q1": "good", "bad_key": "bad"}) - if err == nil { - t.Error("should reject if ANY key doesn't match") - } - - // Valid keys should work - state, err := e.SubmitAnswers(map[string]string{"q1": "answer1", "q2": "answer2"}) - if err != nil { - t.Fatalf("valid keys should work: %v", err) - } - if state.Phase != PhaseStructure { - t.Errorf("should advance to structure, got %s", state.Phase) - } -} - -func TestSubmitAnswersPartialOK(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go tool") - e.mu.Lock() - e.state.Phase = PhaseClarify - e.state.Questions = []Question{ - {ID: "q1", Text: "What?"}, - {ID: "q2", Text: "Who?"}, - } - e.mu.Unlock() - - // Only answer one question (partial) — should be accepted - state, err := e.SubmitAnswers(map[string]string{"q1": "just one"}) - if err != nil { - t.Fatalf("partial answers should be accepted: %v", err) - } - if state.Answers["q1"] != "just one" { - t.Error("answer not recorded") - } -} diff --git a/src/pkg/knowledge/inception_edge_test.go b/src/pkg/knowledge/inception_edge_test.go deleted file mode 100644 index 78e7edd974..0000000000 --- a/src/pkg/knowledge/inception_edge_test.go +++ /dev/null @@ -1,225 +0,0 @@ -package knowledge - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestProduceScaffoldEmptyFacts(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - state, err := e.Start("A Go CLI") - if err != nil { - t.Fatal(err) - } - if state == nil { - t.Fatal("state is nil") - } - // Skip to scaffold without recording facts - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(result.Files) == 0 { - t.Error("should produce files even with no facts") - } -} - -func TestProduceScaffoldShortIdeaText(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - // Very short idea - was the cause of bug #464 - _, err := e.Start("Go") - if err != nil { - t.Fatal(err) - } - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - // This should NOT panic - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(result.Files) == 0 { - t.Error("should produce files for short idea") - } -} - -func TestProduceScaffoldUnicodeIdea(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - _, err := e.Start("データ処理ツール Python") - if err != nil { - t.Fatal(err) - } - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(result.Files) == 0 { - t.Error("should produce files for unicode idea") - } - // Check Python files are generated - hasPy := false - for _, f := range result.Files { - if strings.HasSuffix(f.Path, ".py") || f.Path == "pyproject.toml" { - hasPy = true - break - } - } - if !hasPy { - t.Error("unicode idea with Python keyword should produce Python files") - } -} - -func TestProduceScaffoldNewlineIdea(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - _, err := e.Start("A Rust CLI\nthat processes\ndata") - if err != nil { - t.Fatal(err) - } - if e.state.IdeaSlug == "" { - t.Error("slug should not be empty") - } - if strings.Contains(e.state.IdeaSlug, "\n") { - t.Error("slug should not contain newlines") - } - // Check slug doesn't have concatenated words - if strings.Contains(e.state.IdeaSlug, "clithat") { - t.Errorf("slug has concatenated words: %s", e.state.IdeaSlug) - } -} - -func TestLoadStateNilAnswers(t *testing.T) { - dir := t.TempDir() - // Write a state file with null answers - stateJSON := `{"phase":"clarify","mode":"greenfield","idea_text":"test","idea_slug":"test","answers":null,"fact_slugs":null,"started_at":"2026-01-01T00:00:00Z"}` - stateDir := filepath.Join(dir, "inception") - os.MkdirAll(stateDir, 0o755) - os.WriteFile(filepath.Join(stateDir, "state.json"), []byte(stateJSON), 0o644) - - // This should NOT panic when loading - e := NewInceptionEngine(dir, nil, nil) - state := e.GetState() - if state == nil { - t.Fatal("state should be loaded") - } - if state.Answers == nil { - t.Error("Answers should be initialized, not nil") - } - if state.FactSlugs == nil { - t.Error("FactSlugs should be initialized, not nil") - } - - // SubmitAnswers should not panic - _, err := e.SubmitAnswers(map[string]string{"q1": "answer1"}) - // Should fail because q1 doesn't match any question, but NOT panic - if err == nil { - t.Log("SubmitAnswers accepted orphan key (no questions to validate against)") - } -} - -func TestWriteFactsToVaultDedup(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("Test idea") - - // Create facts with duplicate slugs - facts := []IdeationFact{ - {Title: "Login works", Body: "Users can log in", Type: FactRequirement}, - {Title: "Login works!", Body: "Login is functional", Type: FactRequirement}, - } - e.writeFactsToVault(facts) - - // Check that both files exist (dedup should add suffix) - wikiDir := filepath.Join(dir, inceptionWikiDir) - entries, err := os.ReadDir(wikiDir) - if err != nil { - t.Fatal(err) - } - mdCount := 0 - for _, entry := range entries { - if strings.HasSuffix(entry.Name(), ".md") { - mdCount++ - } - } - if mdCount != 2 { - t.Errorf("expected 2 md files, got %d (duplicate slugs lost a file)", mdCount) - } -} - -func TestSlugifyWhitespace(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"hello world", "hello-world"}, - {"hello\nworld", "hello-world"}, - {"hello\tworld", "hello-world"}, - {"hello\r\nworld", "hello-world"}, - } - for _, tt := range tests { - got := slugify(tt.input) - if got != tt.want { - t.Errorf("slugify(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestJsonEscapeControlChars(t *testing.T) { - tests := []struct { - input string - want string - }{ - {`hello "world"`, `hello \"world\"`}, - {"line1\nline2", `line1\nline2`}, - {"tab\there", `tab\there`}, - {"cr\rhere", `cr\rhere`}, - {`back\slash`, `back\\slash`}, - } - for _, tt := range tests { - got := jsonEscape(tt.input) - if got != tt.want { - t.Errorf("jsonEscape(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestTomlEscapeControlChars(t *testing.T) { - input := "line1\nline2" - got := tomlEscape(input) - if strings.Contains(got, "\n") { - t.Errorf("tomlEscape should escape newlines, got %q", got) - } -} - -func TestBuildI18nIndexForAllLangs(t *testing.T) { - langs := []string{"python", "go", "rust", "java", "javascript", "shell", "typescript", ""} - for _, lang := range langs { - content, path := buildI18nIndexForLang(lang) - if content == "" { - t.Errorf("buildI18nIndexForLang(%q) returned empty content", lang) - } - if path == "" { - t.Errorf("buildI18nIndexForLang(%q) returned empty path", lang) - } - // Check no .ts files for non-TS languages - if lang != "" && lang != "typescript" && strings.HasSuffix(path, ".ts") { - t.Errorf("buildI18nIndexForLang(%q) returned .ts path %q", lang, path) - } - } -} diff --git a/src/pkg/knowledge/inception_endpoint_test.go b/src/pkg/knowledge/inception_endpoint_test.go deleted file mode 100644 index a560f3cfe8..0000000000 --- a/src/pkg/knowledge/inception_endpoint_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package knowledge - -import ( - "bytes" - "context" - "log/slog" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" -) - -func TestInceptionOptionalProjectEndpoint(t *testing.T) { - for _, tc := range []struct { - name string - nilAPI bool - layer LayerType - status int - wantWrites int32 - wantWarn bool - }{ - {name: "no API", nilAPI: true}, - {name: "no endpoints"}, - {name: "org endpoint only", layer: LayerOrg}, - {name: "project endpoint", layer: LayerProject, status: http.StatusOK, wantWrites: 2}, - {name: "project write fails", layer: LayerProject, status: http.StatusInternalServerError, wantWrites: 2, wantWarn: true}, - } { - t.Run(tc.name, func(t *testing.T) { - var logs bytes.Buffer - logger := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelWarn})) - var writes atomic.Int32 - var api *KnowledgeAPI - if !tc.nilAPI { - api = &KnowledgeAPI{logger: logger} - if tc.layer != "" { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost || r.URL.Path != "/api/ingest" { - t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) - } - writes.Add(1) - status := tc.status - if status == 0 { - status = http.StatusOK - } - w.WriteHeader(status) - })) - defer server.Close() - api.layers = []layerClient{{layerType: tc.layer, client: NewClient(server.URL, logger)}} - } - } - - dir := t.TempDir() - engine := NewInceptionEngine(dir, api, logger) - if _, err := engine.Start("A project"); err != nil { - t.Fatal(err) - } - if err := engine.SetQuestions([]Question{{ID: "scope", Text: "What should it do?"}}); err != nil { - t.Fatal(err) - } - if _, err := engine.SubmitAnswers(map[string]string{"scope": "Meet acceptance criteria"}); err != nil { - t.Fatal(err) - } - fact := IdeationFact{Title: "Acceptance", Body: "The project meets its criteria", Type: FactAcceptance} - if err := engine.RecordFacts(context.Background(), []IdeationFact{fact}); err != nil { - t.Fatal(err) - } - if state := engine.GetState(); state.Phase != PhaseScaffold || len(state.FactSlugs) != 2 { - t.Fatalf("unexpected inception state: %+v", state) - } - if got := writes.Load(); got != tc.wantWrites { - t.Errorf("remote writes = %d, want %d", got, tc.wantWrites) - } - if got := strings.Contains(logs.String(), "failed to record ideation fact"); got != tc.wantWarn { - t.Errorf("record warning = %v, want %v; logs: %s", got, tc.wantWarn, &logs) - } - if !tc.wantWarn && logs.Len() != 0 { - t.Errorf("unexpected warnings: %s", &logs) - } - if api != nil { - assertInceptionVaultFact(t, api, "inception-wiki", fact) - } - - // The local facts must remain available to agents after a restart, - // including when the remote endpoint is absent or its write failed. - restartedAPI := &KnowledgeAPI{logger: logger} - NewInceptionEngine(dir, restartedAPI, logger) - assertInceptionVaultFact(t, restartedAPI, engine.GetState().WikiName, fact) - }) - } -} - -func assertInceptionVaultFact(t *testing.T, api *KnowledgeAPI, name string, want IdeationFact) { - t.Helper() - facts := api.VaultFacts(name) - if len(facts) != 1 { - t.Fatalf("local wiki facts = %d, want 1", len(facts)) - } - if got := facts[0]; got.Title != want.Title || got.Type != want.Type || !strings.Contains(got.Body, want.Body) { - t.Errorf("local wiki fact = %+v, want %+v", got, want) - } -} diff --git a/src/pkg/knowledge/inception_fuzz_test.go b/src/pkg/knowledge/inception_fuzz_test.go deleted file mode 100644 index 7f30e94758..0000000000 --- a/src/pkg/knowledge/inception_fuzz_test.go +++ /dev/null @@ -1,190 +0,0 @@ -package knowledge - -import ( - "context" - "testing" -) - -func FuzzProduceScaffold(f *testing.F) { - f.Add("A Go CLI tool") - f.Add("A Python microservice") - f.Add("") - f.Add("A Rust tool with \"quotes\" and <html>") - f.Add("Line1\nLine2\nLine3") - f.Add("A tool with 日本語 characters") - f.Add("A\x00null\x00byte\x00tool") - f.Add("A tool with \t tabs \r\n and \r returns") - f.Add("x") - f.Add(string(make([]byte, 4000))) - - f.Fuzz(func(t *testing.T, idea string) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - - state, err := e.Start(idea) - if err != nil { - return // validation error, not a bug - } - if state == nil { - return - } - - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - // This must NOT panic - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - return - } - if result == nil { - t.Error("result should not be nil when err is nil") - } - }) -} - -func FuzzSlugify(f *testing.F) { - f.Add("hello world") - f.Add("") - f.Add("A\nB\tC") - f.Add("日本語テスト") - f.Add(" lots of spaces ") - f.Add("---dashes---") - f.Add("a\x00b\x00c") - - f.Fuzz(func(t *testing.T, input string) { - result := slugify(input) - // Must not contain newlines, tabs, or double dashes - for _, r := range result { - if r == '\n' || r == '\r' || r == '\t' { - t.Errorf("slugify(%q) contains control char: %q", input, result) - } - } - if len(result) > 0 && (result[0] == '-' || result[len(result)-1] == '-') { - t.Errorf("slugify(%q) has leading/trailing dash: %q", input, result) - } - }) -} - -func FuzzJsonEscape(f *testing.F) { - f.Add("hello") - f.Add(`"quotes"`) - f.Add("new\nline") - f.Add("tab\there") - f.Add(`back\slash`) - f.Add("\x00\x01\x02") - - f.Fuzz(func(t *testing.T, input string) { - result := jsonEscape(input) - // Must not contain unescaped newlines, tabs, or quotes - for i, r := range result { - if r == '\n' || r == '\r' || r == '\t' { - t.Errorf("jsonEscape(%q) contains unescaped control char at %d: %q", input, i, result) - } - } - }) -} - -func FuzzContainsWord(f *testing.F) { - f.Add("hello go world", "go") - f.Add("logo design", "go") - f.Add("", "go") - f.Add("go", "go") - f.Add("gogo", "go") - - f.Fuzz(func(t *testing.T, text, word string) { - if len(word) == 0 { - return - } - // Must not panic - _ = containsWord(text, word) - }) -} - -func FuzzBuildPyInit(f *testing.F) { - f.Add("myproject", "A cool tool") - f.Add("test", `Project with "quotes"`) - f.Add("pkg", "Has\nnewlines") - f.Add("x", `Has """ triple quotes """.`) - f.Add("", "") - - f.Fuzz(func(t *testing.T, name, visionTitle string) { - var vision *Fact - if visionTitle != "" { - vision = &Fact{Title: visionTitle} - } - // Must not panic - result := buildPyInit(name, vision) - if result == "" { - t.Error("buildPyInit should always produce output") - } - }) -} - -func FuzzBuildGoMain(f *testing.F) { - f.Add("myproject", "A CLI tool") - f.Add("test", `Has "quotes"`) - f.Add("x", "") - - f.Fuzz(func(t *testing.T, name, visionTitle string) { - var vision *Fact - if visionTitle != "" { - vision = &Fact{Title: visionTitle} - } - result := buildGoMain(name, vision) - if result == "" { - t.Error("buildGoMain should always produce output") - } - }) -} - -func FuzzBuildAllTestStubs(f *testing.F) { - f.Add("Normal title") - f.Add(`Title with "quotes"`) - f.Add(`Title with 'apostrophes'`) - f.Add("Title with \\ backslash") - f.Add("Title with \n newline") - f.Add(`Title with """ triple`) - f.Add("C:\\Users\\path\\file") - f.Add("$HOME expansion") - f.Add("`backtick` command") - f.Add("") - - f.Fuzz(func(t *testing.T, title string) { - facts := []Fact{{Title: title, Body: "test body"}} - - // All 6 builders must not panic - _ = buildGoTestStubs(facts) - _ = buildTSTestStubs(facts) - _ = buildPythonTestStubs(facts) - _ = buildRustTestStubs(facts) - _ = buildJavaTestStubs(facts) - _ = buildShellTestStubs(facts) - }) -} - -func FuzzBuildAllScaffoldFiles(f *testing.F) { - f.Add("myproject", "A cool tool") - f.Add("x", "") - f.Add("test-project", `Has "quotes" and <html>`) - f.Add("proj", "Line1\nLine2") - - f.Fuzz(func(t *testing.T, name, desc string) { - vision := &Fact{Title: desc, Body: desc} - constitution := &Fact{Body: "Go project"} - - _ = buildReadme(name, "go", desc, vision, constitution, nil, nil, nil) - _ = buildClaudeMD("go", constitution, nil) - _ = buildContributing(name, "go", constitution) - _ = buildAgentsMD(constitution, nil, nil, vision) - _ = buildCIConfig("go") - _ = buildNightlyCI("go") - _ = buildGitignore("go") - _ = buildMakefile("go", name, "cli") - _ = buildGoMain(name, vision) - _ = buildGoCmdRoot(name, vision) - _ = buildGoMod(name) - _ = buildDockerfile("go", name) - }) -} diff --git a/src/pkg/knowledge/inception_helpers_test.go b/src/pkg/knowledge/inception_helpers_test.go deleted file mode 100644 index e056e60dea..0000000000 --- a/src/pkg/knowledge/inception_helpers_test.go +++ /dev/null @@ -1,244 +0,0 @@ -package knowledge - -import ( - "log/slog" - "testing" -) - -func TestSlugify(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"Hello World", "hello-world"}, - {"my_project_name", "my-project-name"}, - {"Already-Slug", "already-slug"}, - {"Special!@#Chars", "specialchars"}, - {" spaces ", "spaces"}, - {"double--dash", "double-dash"}, - {"", ""}, - {"UPPER CASE", "upper-case"}, - } - for _, tt := range tests { - got := slugify(tt.input) - if got != tt.want { - t.Errorf("slugify(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestTruncateSlug(t *testing.T) { - short := "short" - if truncateSlug(short) != short { - t.Errorf("short string should not be truncated") - } - - long := "a-very-long-project-name-that-exceeds-sixty-characters-in-total-length-and-more" - got := truncateSlug(long) - if len(got) != 60 { - t.Errorf("expected truncated to 60, got %d", len(got)) - } -} - -func TestRepoBaseName(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"https://github.com/org/myrepo.git", "myrepo"}, - {"https://github.com/org/myrepo", "myrepo"}, - {"git@github.com:org/repo.git", "repo"}, - {"repo", "repo"}, - {"", "repo"}, - } - for _, tt := range tests { - got := repoBaseName(tt.input) - if got != tt.want { - t.Errorf("repoBaseName(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestPyPackageName(t *testing.T) { - if pyPackageName("my-project") != "my_project" { - t.Error("should replace dashes with underscores") - } - if pyPackageName("no_dashes") != "no_dashes" { - t.Error("no dashes should be unchanged") - } -} - -func TestToPascalCase(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"hello world", "HelloWorld"}, - {"my project", "MyProject"}, - {"single", "Single"}, - {"UPPER case", "UPPERCase"}, - {"with-special!chars", "Withspecialchars"}, - {"", "Unnamed"}, - } - for _, tt := range tests { - got := toPascalCase(tt.input) - if got != tt.want { - t.Errorf("toPascalCase(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestToSnakeCase(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"Hello World", "hello_world"}, - {"MY PROJECT", "my_project"}, - {"single", "single"}, - {"with-special!chars", "withspecialchars"}, - {"", "unnamed"}, - } - for _, tt := range tests { - got := toSnakeCase(tt.input) - if got != tt.want { - t.Errorf("toSnakeCase(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestInferLanguage(t *testing.T) { - tests := []struct { - body string - want string - }{ - {"A TypeScript web app using React", "typescript"}, - {"Python API with FastAPI", "python"}, - {"Rust service using tokio and axum", "rust"}, - {"Java Spring Boot application", "java"}, - {"Bash shell scripts with Makefile", "shell"}, - {"A Go microservice", "go"}, - {"", "go"}, - } - for _, tt := range tests { - fact := &Fact{Body: tt.body} - got := inferLanguage(fact) - if got != tt.want { - t.Errorf("inferLanguage(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestInferLanguageNil(t *testing.T) { - if inferLanguage(nil) != "go" { - t.Error("nil constitution should default to go") - } -} - -func TestInferTestPath(t *testing.T) { - goFact := &Fact{Body: "A Go project"} - if inferTestPath(goFact) != "main_test.go" { - t.Errorf("go test path = %q", inferTestPath(goFact)) - } - - tsFact := &Fact{Body: "TypeScript React app"} - if inferTestPath(tsFact) != "src/__tests__/acceptance.test.ts" { - t.Errorf("ts test path = %q", inferTestPath(tsFact)) - } - - pyFact := &Fact{Body: "Python FastAPI service"} - if inferTestPath(pyFact) != "tests/test_acceptance.py" { - t.Errorf("python test path = %q", inferTestPath(pyFact)) - } -} - -func TestFindFactByType(t *testing.T) { - facts := []Fact{ - {Type: FactPattern, Title: "Pattern A"}, - {Type: FactVision, Title: "Vision"}, - {Type: FactDecision, Title: "Decision A"}, - } - - got := findFactByType(facts, FactVision) - if got == nil || got.Title != "Vision" { - t.Error("should find vision fact") - } - - missing := findFactByType(facts, FactConstraint) - if missing != nil { - t.Error("should return nil for missing type") - } -} - -func TestFilterFactsByType(t *testing.T) { - facts := []Fact{ - {Type: FactRequirement, Title: "Req 1"}, - {Type: FactPattern, Title: "Pattern"}, - {Type: FactRequirement, Title: "Req 2"}, - } - - got := filterFactsByType(facts, FactRequirement) - if len(got) != 2 { - t.Fatalf("expected 2 requirements, got %d", len(got)) - } - if got[0].Title != "Req 1" || got[1].Title != "Req 2" { - t.Error("wrong requirements returned") - } - - empty := filterFactsByType(facts, FactConstraint) - if len(empty) != 0 { - t.Error("should return empty for missing type") - } -} - -func TestDefaultConfidence(t *testing.T) { - tests := []struct { - ft FactType - want float64 - }{ - {FactIdea, 0.3}, - {FactVision, 0.6}, - {FactPattern, 0.5}, - } - for _, tt := range tests { - got := defaultConfidence(tt.ft) - if got != tt.want { - t.Errorf("defaultConfidence(%q) = %f, want %f", tt.ft, got, tt.want) - } - } -} - -func TestFileStoreSetName(t *testing.T) { - dir := t.TempDir() - fs, err := NewFileStore(dir, "test", slog.Default()) - if err != nil { - t.Fatal(err) - } - fs.SetName("test-vault") - if fs.Name() != "test-vault" { - t.Errorf("Name() = %q, want 'test-vault'", fs.Name()) - } -} - -func TestFileStoreRecordAndAccessCount(t *testing.T) { - dir := t.TempDir() - fs, err := NewFileStore(dir, "test", slog.Default()) - if err != nil { - t.Fatal(err) - } - - if fs.AccessCount("fact-1") != 0 { - t.Error("initial access count should be 0") - } - - fs.RecordAccess("fact-1") - fs.RecordAccess("fact-1") - fs.RecordAccess("fact-2") - - if fs.AccessCount("fact-1") != 2 { - t.Errorf("fact-1 access count = %d, want 2", fs.AccessCount("fact-1")) - } - if fs.AccessCount("fact-2") != 1 { - t.Errorf("fact-2 access count = %d, want 1", fs.AccessCount("fact-2")) - } -} diff --git a/src/pkg/knowledge/inception_record_test.go b/src/pkg/knowledge/inception_record_test.go deleted file mode 100644 index ab3bd5d4d9..0000000000 --- a/src/pkg/knowledge/inception_record_test.go +++ /dev/null @@ -1,334 +0,0 @@ -package knowledge - -import ( - "context" - "log/slog" - "os" - "path/filepath" - "testing" -) - -func TestRecordFactsSuccess(t *testing.T) { - e := newTestEngine(t) - e.Start("my project idea") - - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - e.SetQuestions([]Question{{ID: "lang", Text: "What language?"}}) - - e.mu.Lock() - e.state.Phase = PhaseClarify - e.mu.Unlock() - e.SubmitAnswers(map[string]string{"lang": "Go"}) - - facts := []IdeationFact{ - {Title: "Project Vision", Body: "Build a CLI tool", Type: FactVision}, - {Title: "Main Requirement", Body: "Must be fast", Type: FactRequirement}, - } - - err := e.RecordFacts(context.Background(), facts) - if err != nil { - t.Fatalf("RecordFacts error: %v", err) - } - - state := e.GetState() - if state.Phase != PhaseScaffold { - t.Errorf("phase = %q, want scaffold", state.Phase) - } - if len(state.FactSlugs) < 2 { - t.Errorf("fact slugs = %d, want at least 2", len(state.FactSlugs)) - } -} - -func TestRecordFactsNoState(t *testing.T) { - e := newTestEngine(t) - err := e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Test", Body: "Body", Type: FactVision}, - }) - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestRecordFactsEmpty(t *testing.T) { - e := newTestEngine(t) - e.Start("idea") - err := e.RecordFacts(context.Background(), nil) - if err == nil { - t.Error("should error with empty facts") - } -} - -func TestRecordFactsInvalidType(t *testing.T) { - e := newTestEngine(t) - e.Start("idea") - err := e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Test", Body: "Body", Type: FactPattern}, - }) - if err == nil { - t.Error("non-ideation type should error") - } -} - -func TestRecordFactsMissingTitle(t *testing.T) { - e := newTestEngine(t) - e.Start("idea") - err := e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "", Body: "Body", Type: FactVision}, - }) - if err == nil { - t.Error("empty title should error") - } -} - -func TestRecordFactsMissingBody(t *testing.T) { - e := newTestEngine(t) - e.Start("idea") - err := e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Test", Body: "", Type: FactVision}, - }) - if err == nil { - t.Error("empty body should error") - } -} - -func TestRecordFactsBrownfieldBoost(t *testing.T) { - e := newTestEngine(t) - e.StartBrownfield("https://github.com/org/repo") - - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - facts := []IdeationFact{ - {Title: "Vision", Body: "Existing project", Type: FactVision}, - } - err := e.RecordFacts(context.Background(), facts) - if err != nil { - t.Fatalf("error: %v", err) - } -} - -func TestGatherFactsPublicEmpty(t *testing.T) { - e := newTestEngine(t) - facts := e.GatherFactsPublic(context.Background()) - if len(facts) != 0 { - t.Errorf("no wiki dir should return empty, got %d", len(facts)) - } -} - -func TestGatherFactsPublicFromFiles(t *testing.T) { - e := newTestEngine(t) - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - - fact1 := `--- -title: Project Vision -type: vision -confidence: 0.8 ---- -Build an awesome CLI tool.` - - fact2 := `--- -title: Main Requirement -type: requirement -confidence: 0.7 ---- -Must be fast and reliable.` - - os.WriteFile(filepath.Join(wikiDir, "vision-project.md"), []byte(fact1), 0644) - os.WriteFile(filepath.Join(wikiDir, "req-main.md"), []byte(fact2), 0644) - os.WriteFile(filepath.Join(wikiDir, "not-a-fact.txt"), []byte("ignore"), 0644) - os.Mkdir(filepath.Join(wikiDir, "subdir"), 0755) - - facts := e.GatherFactsPublic(context.Background()) - if len(facts) != 2 { - t.Fatalf("expected 2 facts, got %d", len(facts)) - } - - visionFound := false - for _, f := range facts { - if f.Type == FactVision { - visionFound = true - if f.Title != "Project Vision" { - t.Errorf("vision title = %q", f.Title) - } - if f.Confidence != 0.8 { - t.Errorf("vision confidence = %f", f.Confidence) - } - } - } - if !visionFound { - t.Error("vision fact should be found") - } -} - -func TestProduceScaffoldNoState(t *testing.T) { - e := newTestEngine(t) - _, err := e.ProduceScaffold(context.Background()) - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestProduceScaffoldGreenfield(t *testing.T) { - e := newTestEngine(t) - e.Start("build a Go CLI tool for task management") - - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - - visionFact := `--- -title: Task Manager -type: vision -confidence: 0.8 ---- -A CLI tool for managing tasks efficiently.` - - constFact := `--- -title: Go Architecture -type: constitution -confidence: 0.7 ---- -Go microservice with cobra CLI framework.` - - os.WriteFile(filepath.Join(wikiDir, "vision-task.md"), []byte(visionFact), 0644) - os.WriteFile(filepath.Join(wikiDir, "const-arch.md"), []byte(constFact), 0644) - - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatalf("error: %v", err) - } - if result == nil { - t.Fatal("result should not be nil") - } - if len(result.Files) == 0 { - t.Error("should produce at least one file") - } - - hasReadme := false - for _, f := range result.Files { - if f.Path == "README.md" { - hasReadme = true - } - } - if !hasReadme { - t.Error("scaffold should include README.md") - } -} - -func TestClearWikiVault(t *testing.T) { - e := newTestEngine(t) - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - os.WriteFile(filepath.Join(wikiDir, "fact.md"), []byte("test"), 0644) - os.WriteFile(filepath.Join(wikiDir, "other.txt"), []byte("keep"), 0644) - - e.clearWikiVault() - - entries, _ := os.ReadDir(wikiDir) - for _, entry := range entries { - if entry.Name() == "fact.md" { - t.Error("clearWikiVault should remove .md files") - } - } -} - -func TestWriteFactsToVault(t *testing.T) { - e := newTestEngine(t) - facts := []IdeationFact{ - {Title: "Vision", Body: "Build something", Type: FactVision}, - {Title: "Requirement", Body: "Must be fast", Type: FactRequirement}, - } - - e.writeFactsToVault(facts) - - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - entries, err := os.ReadDir(wikiDir) - if err != nil { - t.Fatalf("wiki dir should exist: %v", err) - } - - mdCount := 0 - for _, entry := range entries { - if filepath.Ext(entry.Name()) == ".md" { - mdCount++ - } - } - if mdCount != 2 { - t.Errorf("expected 2 .md files, got %d", mdCount) - } -} - -func TestBuildK8sConfigMap(t *testing.T) { - got := buildK8sConfigMap("myproject") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildK8sSecret(t *testing.T) { - got := buildK8sSecret("myproject") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildK8sBaseKustomization(t *testing.T) { - got := buildK8sBaseKustomization() - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildK8sOverlayKustomization(t *testing.T) { - got := buildK8sOverlayKustomization("myproject", "dev") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildNightlyCI(t *testing.T) { - got := buildNightlyCI("go") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildMakefile(t *testing.T) { - got := buildMakefile("go", "myproject", "cli") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildI18nFile(t *testing.T) { - got := buildI18nFile("en", "myproject") - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildI18nIndex(t *testing.T) { - got := buildI18nIndex() - if got == "" { - t.Error("should produce output") - } -} - -func TestNewInceptionEngineWithDir(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, slog.Default()) - if e == nil { - t.Fatal("engine should not be nil") - } - if e.GetState() != nil { - t.Error("fresh engine should have nil state") - } -} diff --git a/src/pkg/knowledge/inception_scaffold_test.go b/src/pkg/knowledge/inception_scaffold_test.go deleted file mode 100644 index 0face93c4c..0000000000 --- a/src/pkg/knowledge/inception_scaffold_test.go +++ /dev/null @@ -1,444 +0,0 @@ -package knowledge - -import ( - "strings" - "testing" -) - -func TestBuildReadme(t *testing.T) { - vision := &Fact{Title: "MyProject", Body: "A cool tool"} - constitution := &Fact{Body: "Go microservice"} - reqs := []Fact{{Title: "Req 1", Body: "Must be fast"}} - constraints := []Fact{{Title: "Constraint 1", Body: "No external deps"}} - stakeholders := []Fact{{Title: "Team A", Body: "Backend devs"}} - - got := buildReadme("build a tool", "go", "build a tool", vision, constitution, reqs, constraints, stakeholders) - if !strings.Contains(got, "MyProject") { - t.Error("should contain project name") - } - if !strings.Contains(got, "Must be fast") { - t.Error("should contain requirement") - } - if !strings.Contains(got, "No external deps") { - t.Error("should contain constraint") - } -} - -func TestBuildReadmeMinimal(t *testing.T) { - got := buildReadme("simple idea", "go", "simple idea", nil, nil, nil, nil, nil) - if got == "" { - t.Error("should produce output even with nil facts") - } - if !strings.Contains(got, "Project") { - t.Error("should have default title") - } -} - -func TestBuildClaudeMD(t *testing.T) { - constitution := &Fact{Body: "Go microservice with REST API"} - constraints := []Fact{{Body: "Must use stdlib only"}} - - got := buildClaudeMD("go", constitution, constraints) - if !strings.Contains(got, "Guidelines") { - t.Error("should contain Guidelines header") - } - if !strings.Contains(got, "Go microservice") { - t.Error("should contain constitution body") - } -} - -func TestBuildClaudeMDNil(t *testing.T) { - got := buildClaudeMD("go", nil, nil) - if got == "" { - t.Error("should produce output with nil inputs") - } -} - -func TestBuildContributing(t *testing.T) { - constitution := &Fact{Body: "TypeScript React application"} - got := buildContributing("myproject", "typescript", constitution) - if !strings.Contains(got, "Contributing") { - t.Error("should contain Contributing header") - } -} - -func TestBuildContributingNil(t *testing.T) { - got := buildContributing("myproject", "go", nil) - if got == "" { - t.Error("should produce output with nil constitution") - } -} - -func TestBuildTestStubsGo(t *testing.T) { - acceptance := []Fact{{Title: "Test 1", Body: "It works"}} - got := buildTestStubs(acceptance, "go") - if !strings.Contains(got, "Test") { - t.Error("should contain test content") - } -} - -func TestBuildGoTestStubs(t *testing.T) { - acceptance := []Fact{ - {Title: "Login works", Body: "User can log in"}, - {Title: "Logout works", Body: "User can log out"}, - } - got := buildGoTestStubs(acceptance) - if !strings.Contains(got, "func Test") { - t.Error("should contain Go test functions") - } -} - -func TestBuildTSTestStubs(t *testing.T) { - acceptance := []Fact{{Title: "Button clicks", Body: "Button responds"}} - got := buildTSTestStubs(acceptance) - if !strings.Contains(got, "describe") || !strings.Contains(got, "it.todo") { - t.Error("should contain TS test structure") - } -} - -func TestBuildPythonTestStubs(t *testing.T) { - acceptance := []Fact{{Title: "API responds", Body: "Returns 200"}} - got := buildPythonTestStubs(acceptance) - if !strings.Contains(got, "def test_") { - t.Error("should contain Python test functions") - } -} - -func TestBuildRustTestStubs(t *testing.T) { - acceptance := []Fact{{Title: "Compiles", Body: "No errors"}} - got := buildRustTestStubs(acceptance) - if !strings.Contains(got, "#[test]") { - t.Error("should contain Rust test attribute") - } -} - -func TestBuildJavaTestStubs(t *testing.T) { - acceptance := []Fact{{Title: "Starts up", Body: "No crash"}} - got := buildJavaTestStubs(acceptance) - if !strings.Contains(got, "@Test") { - t.Error("should contain Java @Test annotation") - } -} - -func TestBuildShellTestStubs(t *testing.T) { - acceptance := []Fact{{Title: "Script runs", Body: "Exits 0"}} - got := buildShellTestStubs(acceptance) - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildShellMain(t *testing.T) { - vision := &Fact{Body: "A CLI tool for automation"} - got := buildShellMain("mytool", vision) - if !strings.Contains(got, "#!/") { - t.Error("should contain shebang") - } - if !strings.Contains(got, "mytool") { - t.Error("should contain tool name") - } -} - -func TestBuildCIConfigGo(t *testing.T) { - got := buildCIConfig("go") - if !strings.Contains(got, "go") { - t.Error("Go CI should reference go") - } -} - -func TestBuildCIConfigTS(t *testing.T) { - got := buildCIConfig("typescript") - if !strings.Contains(got, "npm") || !strings.Contains(got, "node") { - t.Error("TS CI should reference npm/node") - } -} - -func TestBuildCIConfigPython(t *testing.T) { - got := buildCIConfig("python") - if !strings.Contains(got, "pip") || !strings.Contains(got, "python") { - t.Error("Python CI should reference pip/python") - } -} - -func TestBuildCIConfigRust(t *testing.T) { - got := buildCIConfig("rust") - if !strings.Contains(got, "cargo") { - t.Error("Rust CI should reference cargo") - } -} - -func TestBuildCIConfigJava(t *testing.T) { - got := buildCIConfig("java") - if !strings.Contains(got, "mvn") || !strings.Contains(got, "java") { - t.Error("Java CI should reference mvn/java") - } -} - -func TestBuildCIConfigShell(t *testing.T) { - got := buildCIConfig("shell") - if !strings.Contains(got, "shellcheck") || !strings.Contains(got, "bash") { - t.Error("Shell CI should reference shellcheck/bash") - } -} - -func TestBuildGitignoreLanguages(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell", "javascript"} - for _, lang := range langs { - got := buildGitignore(lang) - if got == "" { - t.Errorf("buildGitignore(%q) should not be empty", lang) - } - if !strings.Contains(got, ".") { - t.Errorf("buildGitignore(%q) should contain file patterns", lang) - } - } -} - -func TestBuildGoMod(t *testing.T) { - got := buildGoMod("myproject") - if !strings.Contains(got, "module") { - t.Error("should contain module directive") - } -} - -func TestBuildGoMain(t *testing.T) { - vision := &Fact{Body: "A CLI tool"} - got := buildGoMain("myproject", vision) - if !strings.Contains(got, "package main") { - t.Error("should contain package main") - } -} - -func TestBuildGoCmdRoot(t *testing.T) { - vision := &Fact{Body: "A CLI tool"} - got := buildGoCmdRoot("myproject", vision) - if !strings.Contains(got, "cobra") || !strings.Contains(got, "rootCmd") { - t.Error("should contain cobra root command") - } -} - -func TestBuildCargoToml(t *testing.T) { - vision := &Fact{Body: "A Rust service"} - got := buildCargoToml("myproject", vision) - if !strings.Contains(got, "[package]") { - t.Error("should contain [package] section") - } -} - -func TestBuildRustMain(t *testing.T) { - vision := &Fact{Body: "A Rust service"} - got := buildRustMain("myproject", vision) - if !strings.Contains(got, "fn main()") { - t.Error("should contain fn main()") - } -} - -func TestBuildPomXml(t *testing.T) { - vision := &Fact{Body: "A Java app"} - got := buildPomXml("myproject", vision) - if !strings.Contains(got, "<project") { - t.Error("should contain <project tag") - } -} - -func TestBuildJavaMain(t *testing.T) { - vision := &Fact{Body: "A Java app"} - got := buildJavaMain("myproject", vision) - if !strings.Contains(got, "public static void main") { - t.Error("should contain main method") - } -} - -func TestBuildPyprojectToml(t *testing.T) { - vision := &Fact{Body: "A Python tool"} - got := buildPyprojectToml("myproject", vision) - if !strings.Contains(got, "[project]") { - t.Error("should contain [project] section") - } -} - -func TestBuildPyInit(t *testing.T) { - vision := &Fact{Body: "A Python tool"} - got := buildPyInit("myproject", vision) - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildPyCLI(t *testing.T) { - vision := &Fact{Body: "A Python CLI"} - got := buildPyCLI("myproject", vision) - if !strings.Contains(got, "def main") { - t.Error("should contain main function") - } -} - -func TestBuildPackageJSON(t *testing.T) { - vision := &Fact{Body: "A TS app"} - got := buildPackageJSON("myproject", vision) - if !strings.Contains(got, `"name"`) { - t.Error("should contain name field") - } -} - -func TestBuildTSConfig(t *testing.T) { - got := buildTSConfig() - if !strings.Contains(got, "compilerOptions") { - t.Error("should contain compilerOptions") - } -} - -func TestBuildTSIndex(t *testing.T) { - vision := &Fact{Body: "A TS app"} - got := buildTSIndex("myproject", vision) - if got == "" { - t.Error("should produce output") - } -} - -func TestBuildDockerfile(t *testing.T) { - langs := []string{"go", "typescript", "python", "rust", "java", "shell"} - for _, lang := range langs { - got := buildDockerfile(lang, "myproject") - if !strings.Contains(got, "FROM") { - t.Errorf("buildDockerfile(%q) should contain FROM", lang) - } - } -} - -func TestBuildKustomization(t *testing.T) { - got := buildKustomization() - if !strings.Contains(got, "apiVersion") { - t.Error("should contain apiVersion") - } -} - -func TestBuildK8sDeployment(t *testing.T) { - got := buildK8sDeployment("myproject") - if !strings.Contains(got, "Deployment") { - t.Error("should contain Deployment kind") - } -} - -func TestBuildK8sService(t *testing.T) { - got := buildK8sService("myproject") - if !strings.Contains(got, "Service") { - t.Error("should contain Service kind") - } -} - -func TestInferProjectName(t *testing.T) { - vision := &Fact{Title: "My Cool Project"} - got := inferProjectName(vision, &InceptionState{}) - if got == "" { - t.Error("should infer name from vision") - } -} - -func TestInferProjectNameNilVision(t *testing.T) { - state := &InceptionState{IdeaSlug: "idea-myrepo"} - got := inferProjectName(nil, state) - if got != "myrepo" { - t.Errorf("nil vision should use idea slug, got %q", got) - } -} - -func TestInferProjectNameDefault(t *testing.T) { - got := inferProjectName(nil, &InceptionState{}) - if got != "myproject" { - t.Errorf("empty state should default to 'myproject', got %q", got) - } -} - -func TestInferProjectType(t *testing.T) { - tests := []struct { - body string - want string - }{ - {"Build a REST API backend", "api"}, - {"Create a CLI tool", "cli"}, - {"Build a web frontend with React", "ui"}, - {"Create a reusable library", "library"}, - {"Something else entirely", "cli"}, - } - for _, tt := range tests { - constitution := &Fact{Body: tt.body} - got := inferProjectType(constitution, nil, nil) - if got != tt.want { - t.Errorf("inferProjectType(%q) = %q, want %q", tt.body, got, tt.want) - } - } -} - -func TestBuildAgentsMD(t *testing.T) { - constitution := &Fact{Body: "Go project"} - constraints := []Fact{{Body: "Must be fast"}} - requirements := []Fact{{Body: "Support REST"}} - vision := &Fact{Title: "MyProject"} - - got := buildAgentsMD(constitution, constraints, requirements, vision) - if got == "" { - t.Error("should produce output") - } -} - -func TestParseInceptionFactFile(t *testing.T) { - content := `--- -title: My Fact -type: requirement -confidence: 0.8 ---- -This is the body of the fact.` - - title, body, factType, confidence := parseInceptionFactFile(content, "test.md") - if title != "My Fact" { - t.Errorf("title = %q", title) - } - if !strings.Contains(body, "body of the fact") { - t.Errorf("body = %q", body) - } - if factType != "requirement" { - t.Errorf("factType = %q", factType) - } - if confidence != 0.8 { - t.Errorf("confidence = %f", confidence) - } -} - -func TestParseInceptionFactFileNoFrontmatter(t *testing.T) { - content := "Just plain text without frontmatter" - title, body, _, _ := parseInceptionFactFile(content, "idea.md") - if title == "" && body == "" { - t.Error("should handle content without frontmatter") - } -} - -func TestFormatAnswersForPrompt(t *testing.T) { - engine := &InceptionEngine{ - state: &InceptionState{ - Questions: []Question{ - {ID: "q1", Text: "What does it do?"}, - {ID: "q2", Text: "Who uses it?"}, - }, - Answers: map[string]string{ - "q1": "It builds stuff", - "q2": "Developers", - }, - }, - } - got := engine.FormatAnswersForPrompt() - if !strings.Contains(got, "What does it do?") { - t.Error("should contain question text") - } - if !strings.Contains(got, "It builds stuff") { - t.Error("should contain answer text") - } -} - -func TestFormatAnswersForPromptEmpty(t *testing.T) { - engine := &InceptionEngine{state: &InceptionState{}} - got := engine.FormatAnswersForPrompt() - if got != "" { - t.Errorf("empty answers should return empty, got %q", got) - } -} diff --git a/src/pkg/knowledge/inception_state_test.go b/src/pkg/knowledge/inception_state_test.go deleted file mode 100644 index 8884b4c854..0000000000 --- a/src/pkg/knowledge/inception_state_test.go +++ /dev/null @@ -1,308 +0,0 @@ -package knowledge - -import ( - "context" - "log/slog" - "os" - "path/filepath" - "testing" -) - -func TestNewInceptionEngineNoState(t *testing.T) { - dir := t.TempDir() - e := &InceptionEngine{ - dataDir: dir, - logger: slog.Default(), - } - e.loadState() - e.connectExistingVault() - - if e.state != nil { - t.Error("no state file should leave state nil") - } -} - -func TestGetStateNil(t *testing.T) { - e := newTestEngine(t) - if e.GetState() != nil { - t.Error("initial state should be nil") - } -} - -func TestStartGreenfield(t *testing.T) { - e := newTestEngine(t) - state, err := e.Start("build a CLI tool for managing tasks") - if err != nil { - t.Fatalf("Start error: %v", err) - } - if state == nil { - t.Fatal("state should not be nil") - } - if state.Phase != PhaseCapture { - t.Errorf("phase = %q, want %q", state.Phase, PhaseCapture) - } - if state.Mode != InceptionGreenfield { - t.Errorf("mode = %q, want %q", state.Mode, InceptionGreenfield) - } - if state.IdeaText != "build a CLI tool for managing tasks" { - t.Errorf("idea text = %q", state.IdeaText) - } - if state.IdeaSlug == "" { - t.Error("idea slug should be set") - } -} - -func TestStartDuplicate(t *testing.T) { - e := newTestEngine(t) - e.Start("first idea") - _, err := e.Start("second idea") - if err == nil { - t.Error("starting while active should error") - } -} - -func TestStartBrownfield(t *testing.T) { - e := newTestEngine(t) - state, err := e.StartBrownfield("https://github.com/org/repo") - if err != nil { - t.Fatalf("StartBrownfield error: %v", err) - } - if state.Mode != InceptionBrownfield { - t.Errorf("mode = %q, want %q", state.Mode, InceptionBrownfield) - } - if state.RepoURL != "https://github.com/org/repo" { - t.Errorf("repo URL = %q", state.RepoURL) - } -} - -func TestStartBrownfieldDuplicate(t *testing.T) { - e := newTestEngine(t) - e.StartBrownfield("https://github.com/org/repo") - _, err := e.StartBrownfield("https://github.com/org/repo2") - if err == nil { - t.Error("starting while active should error") - } -} - -func TestSetQuestions(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - - questions := []Question{ - {ID: "language", Text: "What language?", Category: "language"}, - {ID: "users", Text: "Who uses it?", Category: "users"}, - } - err := e.SetQuestions(questions) - if err != nil { - t.Fatalf("SetQuestions error: %v", err) - } - - state := e.GetState() - if len(state.Questions) != 2 { - t.Errorf("expected 2 questions, got %d", len(state.Questions)) - } -} - -func TestSetQuestionsNoState(t *testing.T) { - e := newTestEngine(t) - err := e.SetQuestions([]Question{{ID: "q1", Text: "test"}}) - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestSubmitAnswers(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - e.SetQuestions([]Question{ - {ID: "language", Text: "What language?"}, - }) - - answers := map[string]string{"language": "Go"} - _, err := e.SubmitAnswers(answers) - if err != nil { - t.Fatalf("SubmitAnswers error: %v", err) - } - - state := e.GetState() - if state.Answers["language"] != "Go" { - t.Errorf("answer = %q", state.Answers["language"]) - } -} - -func TestSubmitAnswersNoState(t *testing.T) { - e := newTestEngine(t) - _, err := e.SubmitAnswers(map[string]string{"q1": "a1"}) - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestAdvanceToCompleteNoState(t *testing.T) { - e := newTestEngine(t) - err := e.AdvanceToComplete() - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestAdvanceToCompleteWrongPhase(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - err := e.AdvanceToComplete() - if err == nil { - t.Error("should error in questions phase") - } -} - -func TestSetWikiName(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - e.SetWikiName("my-cool-wiki") - - state := e.GetState() - if state.WikiName != "my-cool-wiki" { - t.Errorf("wiki name = %q", state.WikiName) - } -} - -func TestSetWikiNameNoState(t *testing.T) { - e := newTestEngine(t) - e.SetWikiName("test") -} - -func TestIncrementAutoFactCount(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - e.IncrementAutoFactCount(3) - e.IncrementAutoFactCount(2) - - state := e.GetState() - if state.AutoFactCount != 5 { - t.Errorf("auto fact count = %d, want 5", state.AutoFactCount) - } -} - -func TestIncrementAutoFactCountNoState(t *testing.T) { - e := newTestEngine(t) - e.IncrementAutoFactCount(1) -} - -func TestIncrementAutoQuestionCount(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - e.IncrementAutoQuestionCount(4) - - state := e.GetState() - if state.AutoQuestionCount != 4 { - t.Errorf("auto question count = %d, want 4", state.AutoQuestionCount) - } -} - -func TestHasWikiFilesEmpty(t *testing.T) { - e := newTestEngine(t) - if e.HasWikiFiles() { - t.Error("empty dir should have no wiki files") - } -} - -func TestHasWikiFilesPresent(t *testing.T) { - e := newTestEngine(t) - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - os.WriteFile(filepath.Join(wikiDir, "fact.md"), []byte("# Fact"), 0644) - - if !e.HasWikiFiles() { - t.Error("should detect .md files in wiki dir") - } -} - -func TestHasWikiFilesNonMD(t *testing.T) { - e := newTestEngine(t) - wikiDir := filepath.Join(e.dataDir, inceptionWikiDir) - os.MkdirAll(wikiDir, 0755) - os.WriteFile(filepath.Join(wikiDir, "readme.txt"), []byte("text"), 0644) - - if e.HasWikiFiles() { - t.Error("non-.md files should not count") - } -} - -func TestReset(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - - if e.GetState() == nil { - t.Fatal("state should be set after Start") - } - - err := e.Reset() - if err != nil { - t.Fatalf("Reset error: %v", err) - } - if e.GetState() != nil { - t.Error("state should be nil after Reset") - } -} - -func TestResetNoState(t *testing.T) { - e := newTestEngine(t) - err := e.Reset() - if err != nil { - t.Errorf("Reset with no state should not error, got %v", err) - } -} - -func TestSaveAndLoadState(t *testing.T) { - e := newTestEngine(t) - e.Start("test idea") - e.SetWikiName("test-wiki") - - e2 := &InceptionEngine{ - dataDir: e.dataDir, - logger: slog.Default(), - } - e2.loadState() - - if e2.state == nil { - t.Fatal("loaded state should not be nil") - } - if e2.state.IdeaText != "test idea" { - t.Errorf("idea text = %q", e2.state.IdeaText) - } - if e2.state.WikiName != "test-wiki" { - t.Errorf("wiki name = %q", e2.state.WikiName) - } -} - -func TestLoadStateInvalidJSON(t *testing.T) { - e := newTestEngine(t) - statePath := filepath.Join(e.dataDir, inceptionStateFile) - os.MkdirAll(filepath.Dir(statePath), 0755) - os.WriteFile(statePath, []byte("{bad json"), 0644) - - e.loadState() - if e.state != nil { - t.Error("invalid JSON should leave state nil") - } -} - -func TestReadIdeaFactNoState(t *testing.T) { - e := newTestEngine(t) - _, err := e.ReadIdeaFact(context.TODO()) - if err == nil { - t.Error("should error with no active inception") - } -} - -func TestReadIdeaFactNoAPI(t *testing.T) { - e := newTestEngine(t) - e.Start("my idea") - fact, err := e.ReadIdeaFact(context.TODO()) - if err != nil { - t.Fatalf("error: %v", err) - } - if fact != nil { - t.Error("nil API should return nil fact") - } -} diff --git a/src/pkg/knowledge/inception_syntax_test.go b/src/pkg/knowledge/inception_syntax_test.go deleted file mode 100644 index d8abe492fa..0000000000 --- a/src/pkg/knowledge/inception_syntax_test.go +++ /dev/null @@ -1,782 +0,0 @@ -package knowledge - -import ( - "context" - "encoding/json" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func TestScaffoldGoSyntax(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go CLI for managing tasks") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Task Manager CLI", Body: "CLI for task management with cobra", Type: FactVision}, - {Title: "Go 1.23, cobra, stdlib", Body: "Use Go 1.23 with cobra CLI framework", Type: FactConstitution}, - {Title: "CRUD tasks", Body: "Create, list, update, delete tasks", Type: FactRequirement}, - {Title: "Must be fast", Body: "Sub-second response time", Type: FactConstraint}, - {Title: "CLI users pass", Body: "All CLI acceptance criteria pass", Type: FactAcceptance}, - }) - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // Write Go files to temp dir and try to parse them - projDir := filepath.Join(t.TempDir(), "goproject") - os.MkdirAll(projDir, 0o755) - for _, f := range result.Files { - if !strings.HasSuffix(f.Path, ".go") { - continue - } - fullPath := filepath.Join(projDir, f.Path) - os.MkdirAll(filepath.Dir(fullPath), 0o755) - os.WriteFile(fullPath, []byte(f.Content), 0o644) - } - // Write go.mod - for _, f := range result.Files { - if f.Path == "go.mod" { - os.WriteFile(filepath.Join(projDir, "go.mod"), []byte(f.Content), 0o644) - } - } - - // Check Go syntax with go vet (parse only) - cmd := exec.Command("go", "vet", "./...") - cmd.Dir = projDir - out, err := cmd.CombinedOutput() - if err != nil { - // go vet may fail because of missing deps, that's ok - // but syntax errors would say "expected X, found Y" - outStr := string(out) - if strings.Contains(outStr, "expected") && strings.Contains(outStr, "found") { - t.Errorf("Go syntax error in scaffold:\n%s", outStr) - } - } -} - -func TestScaffoldJSONValidity(t *testing.T) { - // Test that package.json, tsconfig.json etc. are valid JSON - langs := []struct { - idea string - jsonFile string - }{ - {"A TypeScript app", "package.json"}, - {"A TypeScript app", "tsconfig.json"}, - {"A JavaScript tool", "package.json"}, - } - - for _, tt := range langs { - t.Run(tt.idea+"/"+tt.jsonFile, func(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start(tt.idea) - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - for _, f := range result.Files { - if f.Path == tt.jsonFile { - var js interface{} - if err := json.Unmarshal([]byte(f.Content), &js); err != nil { - t.Errorf("%s is not valid JSON:\n%s\nerror: %v", tt.jsonFile, f.Content[:200], err) - } - return - } - } - t.Errorf("%s not found in scaffold", tt.jsonFile) - }) - } -} - -func TestScaffoldYAMLBasicValidity(t *testing.T) { - // Check that CI YAML files don't have obvious issues - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Python tool") - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - for _, f := range result.Files { - if !strings.HasSuffix(f.Path, ".yml") && !strings.HasSuffix(f.Path, ".yaml") { - continue - } - // Basic checks - if strings.Contains(f.Content, "\t") { - t.Errorf("%s contains tabs (YAML should use spaces): %s", f.Path, f.Content[:100]) - } - if !strings.Contains(f.Content, "name:") { - t.Errorf("%s missing 'name:' field", f.Path) - } - } -} - -func TestScaffoldSpecialCharsInVision(t *testing.T) { - // Vision title with special characters should not break scaffold files - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go tool") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - specialVision := `Project "with quotes" & <tags> and 'apostrophes' plus """ triple quotes """` - e.RecordFacts(context.Background(), []IdeationFact{ - {Title: specialVision, Body: "Special chars in vision", Type: FactVision}, - {Title: "Go, stdlib", Body: "Use Go standard library", Type: FactConstitution}, - {Title: "Core feature", Body: "Main functionality", Type: FactRequirement}, - }) - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // Check JSON files are still valid - for _, f := range result.Files { - if strings.HasSuffix(f.Path, ".json") { - var js interface{} - if err := json.Unmarshal([]byte(f.Content), &js); err != nil { - t.Errorf("special chars broke JSON in %s: %v\ncontent: %s", f.Path, err, f.Content[:min(200, len(f.Content))]) - } - } - } - - // Check Go files don't have unclosed strings - for _, f := range result.Files { - if strings.HasSuffix(f.Path, ".go") { - lines := strings.Split(f.Content, "\n") - for i, line := range lines { - quoteCount := strings.Count(line, `"`) - strings.Count(line, `\"`) - if quoteCount%2 != 0 && !strings.HasPrefix(strings.TrimSpace(line), "//") { - // Odd number of unescaped quotes — possible unclosed string - // (This is a heuristic, not perfect) - _ = i // just flag for manual review - } - } - } - } -} - -func TestCIConfigAllLanguages(t *testing.T) { - langs := []string{"go", "python", "typescript", "javascript", "rust", "java", "shell", ""} - for _, lang := range langs { - t.Run(lang, func(t *testing.T) { - ci := buildCIConfig(lang) - if ci == "" { - t.Error("CI config should not be empty") - } - if !strings.Contains(ci, "name:") { - t.Error("CI config missing name field") - } - if strings.Contains(ci, "\t") { - t.Errorf("CI config contains tabs") - } - - nightly := buildNightlyCI(lang) - if nightly == "" { - t.Error("nightly CI should not be empty") - } - }) - } -} - -func TestGitignoreAllLanguages(t *testing.T) { - langs := []string{"go", "python", "typescript", "javascript", "rust", "java", "shell", "unknown"} - for _, lang := range langs { - got := buildGitignore(lang) - if got == "" { - t.Errorf("buildGitignore(%q) returned empty", lang) - } - } -} - -func TestMakefileAllLanguages(t *testing.T) { - langs := []string{"go", "python", "typescript", "javascript", "rust", "java", "shell"} - types := []string{"cli", "api", "library", "container", "kubernetes", "ui"} - - for _, lang := range langs { - for _, pt := range types { - name := lang + "-" + pt - t.Run(name, func(t *testing.T) { - mf := buildMakefile(lang, "testproject", pt) - if mf == "" { - t.Error("Makefile should not be empty") - } - if !strings.Contains(mf, ".PHONY") { - t.Error("Makefile missing .PHONY") - } - }) - } - } -} - -func TestDockerfileAllLanguages(t *testing.T) { - langs := []string{"go", "python", "typescript", "javascript", "rust", "java", "shell"} - for _, lang := range langs { - t.Run(lang, func(t *testing.T) { - df := buildDockerfile(lang, "testproject") - if df == "" { - t.Error("Dockerfile should not be empty") - } - if !strings.Contains(df, "FROM") { - t.Error("Dockerfile missing FROM") - } - // Check no tabs (Dockerfiles use spaces) - lines := strings.Split(df, "\n") - for i, line := range lines { - if strings.HasPrefix(line, "\t") { - t.Errorf("line %d starts with tab: %q", i+1, line) - } - } - }) - } -} - -func TestK8sManifests(t *testing.T) { - name := "test-app" - - deployment := buildK8sDeployment(name) - if !strings.Contains(deployment, "kind: Deployment") { - t.Error("missing Deployment kind") - } - if !strings.Contains(deployment, name) { - t.Error("deployment missing project name") - } - - service := buildK8sService(name) - if !strings.Contains(service, "kind: Service") { - t.Error("missing Service kind") - } - - configmap := buildK8sConfigMap(name) - if !strings.Contains(configmap, "kind: ConfigMap") { - t.Error("missing ConfigMap kind") - } - - secret := buildK8sSecret(name) - if !strings.Contains(secret, "kind: Secret") { - t.Error("missing Secret kind") - } - - kustomize := buildKustomization() - if !strings.Contains(kustomize, "apiVersion") { - t.Error("missing kustomization apiVersion") - } - - for _, env := range []string{"dev", "prod"} { - overlay := buildK8sOverlayKustomization(name, env) - if !strings.Contains(overlay, "resources") { - t.Errorf("%s overlay missing resources", env) - } - } -} - -func TestPomXmlSpecialChars(t *testing.T) { - // XML special chars in vision should be escaped - vision := &Fact{Title: `Project with <tags> & "quotes"`} - pom := buildPomXml("test-project", vision) - - if strings.Contains(pom, "&\"") { - t.Error("pom.xml has unescaped ampersand before quote") - } - if !strings.Contains(pom, "<project") { - t.Error("pom.xml missing <project tag") - } - // Should be well-formed enough to not have bare < or & in text content - // (xmlEscape handles this) -} - -func TestCargoTomlSpecialChars(t *testing.T) { - vision := &Fact{Title: "Project with \"quotes\" and\nnewlines"} - cargo := buildCargoToml("test-project", vision) - - if !strings.Contains(cargo, "[package]") { - t.Error("Cargo.toml missing [package]") - } - // Check no raw newlines in the description value - lines := strings.Split(cargo, "\n") - for _, line := range lines { - if strings.HasPrefix(line, "description") { - if strings.Count(line, `"`) < 2 { - t.Errorf("description line has unclosed quotes: %s", line) - } - } - } -} - -func TestScaffoldLanguageCrossCheck(t *testing.T) { - // Constitution says "React" (→ TypeScript) but idea says "Python" - // Cross-check should override to Python - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Python dashboard for monitoring") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Dashboard", Body: "A monitoring dashboard", Type: FactVision}, - {Title: "React frontend", Body: "Use React with TypeScript", Type: FactConstitution}, - {Title: "Real-time data", Body: "Show live metrics", Type: FactRequirement}, - }) - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // Cross-check should detect Python in idea and override React/TypeScript - hasPy := false - hasTS := false - for _, f := range result.Files { - if strings.HasSuffix(f.Path, ".py") || f.Path == "pyproject.toml" { - hasPy = true - } - if f.Path == "tsconfig.json" { - hasTS = true - } - } - if !hasPy { - t.Error("cross-check should override to Python (from idea text)") - } - if hasTS { - t.Error("should not have TypeScript files when idea says Python") - } -} - -func TestScaffoldNoConstitution(t *testing.T) { - // No constitution fact → should default to Go (or cross-check from idea) - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Rust CLI tool") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "Rust CLI", Body: "A fast CLI tool", Type: FactVision}, - {Title: "Speed", Body: "Must be fast", Type: FactRequirement}, - // No constitution! - }) - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // inferLanguage(nil) returns "go", but cross-check should find "rust" in idea - hasRust := false - hasGo := false - for _, f := range result.Files { - if f.Path == "Cargo.toml" || strings.HasSuffix(f.Path, ".rs") { - hasRust = true - } - if f.Path == "go.mod" { - hasGo = true - } - } - if !hasRust { - t.Error("cross-check should detect Rust from idea text even without constitution") - } - if hasGo { - t.Error("should not have Go files when idea says Rust") - } -} - -func TestScaffoldWithManyFacts(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Go tool") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - // Create 50 facts — tests dedup and performance - var facts []IdeationFact - facts = append(facts, IdeationFact{Title: "Vision", Body: "A tool", Type: FactVision}) - facts = append(facts, IdeationFact{Title: "Go stdlib", Body: "Use Go", Type: FactConstitution}) - for i := 0; i < 20; i++ { - facts = append(facts, IdeationFact{ - Title: "Requirement " + strings.Repeat("x", i), - Body: "Must do something " + strings.Repeat("y", i*10), - Type: FactRequirement, - }) - } - for i := 0; i < 10; i++ { - facts = append(facts, IdeationFact{ - Title: "Constraint " + strings.Repeat("z", i), - Body: "Limit " + strings.Repeat("w", i*5), - Type: FactConstraint, - }) - } - for i := 0; i < 10; i++ { - facts = append(facts, IdeationFact{ - Title: "Acceptance " + strings.Repeat("a", i), - Body: "Test that " + strings.Repeat("b", i*5), - Type: FactAcceptance, - }) - } - - err := e.RecordFacts(context.Background(), facts) - if err != nil { - t.Fatal(err) - } - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - if len(result.Files) == 0 { - t.Error("should produce files with many facts") - } - - // Test file should have test stubs for each acceptance fact - for _, f := range result.Files { - if f.Path == "main_test.go" { - testCount := strings.Count(f.Content, "func Test") - if testCount < 5 { - t.Errorf("expected at least 5 test stubs, got %d", testCount) - } - return - } - } -} - -func TestScaffoldWithVeryLongFactBody(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Python tool") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - // Very long fact body (10KB) - longBody := strings.Repeat("This is a very detailed requirement. ", 300) - facts := []IdeationFact{ - {Title: "Vision", Body: "A data tool", Type: FactVision}, - {Title: "Python 3.12", Body: "Use Python", Type: FactConstitution}, - {Title: "Long requirement", Body: longBody, Type: FactRequirement}, - } - - err := e.RecordFacts(context.Background(), facts) - if err != nil { - t.Fatal(err) - } - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // README should contain the long body (or truncated) - for _, f := range result.Files { - if f.Path == "README.md" { - if len(f.Content) < 100 { - t.Error("README seems too short with a long requirement") - } - return - } - } -} - -func TestScaffoldShellKubernetes(t *testing.T) { - // Shell project for Kubernetes operator — should have both .sh and K8s manifests - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start("A Shell tool for Kubernetes deployments") - e.mu.Lock() - e.state.Phase = PhaseStructure - e.mu.Unlock() - - e.RecordFacts(context.Background(), []IdeationFact{ - {Title: "K8s Deploy Tool", Body: "Automate Kubernetes deployments", Type: FactVision}, - {Title: "Bash, kubectl", Body: "Use bash with kubectl commands", Type: FactConstitution}, - {Title: "Deploy apps", Body: "Deploy to namespace", Type: FactRequirement}, - }) - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - hasShell := false - hasK8s := false - for _, f := range result.Files { - if strings.HasSuffix(f.Path, ".sh") { - hasShell = true - } - if strings.Contains(f.Path, "deploy/") || strings.Contains(f.Path, "kustomization") { - hasK8s = true - } - } - if !hasShell { - t.Error("shell K8s project should have .sh files") - } - if !hasK8s { - t.Error("K8s project should have deploy/ manifests") - } -} - -func TestScaffoldCIMatchesLanguage(t *testing.T) { - langs := []struct { - idea string - ciMustHave string - ciMustNot string - }{ - {"A Go CLI", "go build", "npm"}, - {"A Python tool", "pip", "go build"}, - {"A Rust service", "cargo", "npm"}, - {"A TypeScript app", "npm", "go build"}, - {"A Java service", "mvn", "cargo"}, - {"A JavaScript tool", "npm", "go build"}, - {"A Shell script", "shellcheck", "npm"}, - } - - for _, tt := range langs { - t.Run(tt.idea, func(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start(tt.idea) - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - for _, f := range result.Files { - if f.Path == ".github/workflows/ci.yml" { - lower := strings.ToLower(f.Content) - if !strings.Contains(lower, tt.ciMustHave) { - t.Errorf("CI for %s should contain %q", tt.idea, tt.ciMustHave) - } - if strings.Contains(lower, tt.ciMustNot) { - t.Errorf("CI for %s should NOT contain %q", tt.idea, tt.ciMustNot) - } - return - } - } - t.Error("no ci.yml found") - }) - } -} - -func TestScaffoldMakefileMatchesLanguage(t *testing.T) { - langs := []struct { - idea string - mustHave string - }{ - {"A Go CLI", "go build"}, - {"A Python tool", "pytest"}, - {"A Rust service", "cargo"}, - {"A TypeScript app", "npm run build"}, - {"A Java service", "mvn"}, - {"A Shell script", "shellcheck"}, - } - - for _, tt := range langs { - t.Run(tt.idea, func(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start(tt.idea) - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - for _, f := range result.Files { - if f.Path == "Makefile" { - if !strings.Contains(f.Content, tt.mustHave) { - t.Errorf("Makefile for %s should contain %q\ncontent: %s", tt.idea, tt.mustHave, f.Content[:min(200, len(f.Content))]) - } - return - } - } - t.Error("no Makefile found") - }) - } -} - -func TestTestStubsBackslashEscaping(t *testing.T) { - acceptance := []Fact{ - {Title: `Handle C:\path\to\file`, Body: "File paths"}, - {Title: `Test with "quotes" and 'apostrophes'`, Body: "Quotes"}, - {Title: `Backslash at end\`, Body: "Trailing"}, - } - - // Go stubs - goStubs := buildGoTestStubs(acceptance) - if strings.Contains(goStubs, `C:\p`) && !strings.Contains(goStubs, `C:\\p`) { - t.Error("Go stubs: backslash not escaped") - } - - // TS stubs - tsStubs := buildTSTestStubs(acceptance) - if strings.Contains(tsStubs, `C:\p`) && !strings.Contains(tsStubs, `C:\\p`) { - t.Error("TS stubs: backslash not escaped") - } - - // Python stubs - pyStubs := buildPythonTestStubs(acceptance) - if strings.Contains(pyStubs, `C:\p`) && !strings.Contains(pyStubs, `C:\\p`) { - t.Error("Python stubs: backslash not escaped") - } - - // Rust stubs - rsStubs := buildRustTestStubs(acceptance) - if strings.Contains(rsStubs, `C:\p`) && !strings.Contains(rsStubs, `C:\\p`) { - t.Error("Rust stubs: backslash not escaped") - } - - // Java stubs - javaStubs := buildJavaTestStubs(acceptance) - if strings.Contains(javaStubs, `C:\p`) && !strings.Contains(javaStubs, `C:\\p`) { - t.Error("Java stubs: backslash not escaped") - } -} - -func TestScaffoldInvariants(t *testing.T) { - // Every scaffold output must satisfy these properties regardless of language - ideas := []string{ - "A Go CLI tool", - "A Python microservice", - "A Rust API", - "A TypeScript dashboard", - "A Java enterprise app", - "A JavaScript utility", - "A Shell automation script", - } - - for _, idea := range ideas { - t.Run(idea, func(t *testing.T) { - dir := t.TempDir() - e := NewInceptionEngine(dir, nil, nil) - e.Start(idea) - e.mu.Lock() - e.state.Phase = PhaseScaffold - e.mu.Unlock() - - result, err := e.ProduceScaffold(context.Background()) - if err != nil { - t.Fatal(err) - } - - // INVARIANT 1: Always has README.md - hasReadme := false - for _, f := range result.Files { - if f.Path == "README.md" { - hasReadme = true - if f.Content == "" { - t.Error("README.md should not be empty") - } - } - } - if !hasReadme { - t.Error("every scaffold must have README.md") - } - - // INVARIANT 2: Always has .gitignore - hasGitignore := false - for _, f := range result.Files { - if f.Path == ".gitignore" { - hasGitignore = true - } - } - if !hasGitignore { - t.Error("every scaffold must have .gitignore") - } - - // INVARIANT 3: Always has Makefile - hasMakefile := false - for _, f := range result.Files { - if f.Path == "Makefile" { - hasMakefile = true - } - } - if !hasMakefile { - t.Error("every scaffold must have Makefile") - } - - // INVARIANT 4: Always has CI config - hasCI := false - for _, f := range result.Files { - if f.Path == ".github/workflows/ci.yml" { - hasCI = true - } - } - if !hasCI { - t.Error("every scaffold must have ci.yml") - } - - // INVARIANT 5: No duplicate paths - seen := make(map[string]bool) - for _, f := range result.Files { - if seen[f.Path] { - t.Errorf("duplicate file path: %s", f.Path) - } - seen[f.Path] = true - } - - // INVARIANT 6: No empty paths - for _, f := range result.Files { - if f.Path == "" { - t.Error("file path must not be empty") - } - } - - // INVARIANT 7: No empty content - for _, f := range result.Files { - if f.Content == "" { - t.Errorf("file %s has empty content", f.Path) - } - } - - // INVARIANT 8: All files have a purpose - for _, f := range result.Files { - if f.Purpose == "" { - t.Errorf("file %s has no purpose", f.Path) - } - } - - // INVARIANT 9: All paths are relative (no leading /) - for _, f := range result.Files { - if strings.HasPrefix(f.Path, "/") { - t.Errorf("file path is absolute: %s", f.Path) - } - } - - // INVARIANT 10: No path traversal - for _, f := range result.Files { - if strings.Contains(f.Path, "..") { - t.Errorf("file path contains ..: %s", f.Path) - } - } - }) - } -} diff --git a/src/pkg/knowledge/inception_test_helpers_test.go b/src/pkg/knowledge/inception_test_helpers_test.go deleted file mode 100644 index edf5e684d0..0000000000 --- a/src/pkg/knowledge/inception_test_helpers_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package knowledge - -import ( - "log/slog" - "testing" -) - -func newTestEngine(t *testing.T) *InceptionEngine { - t.Helper() - return NewInceptionEngine(t.TempDir(), nil, slog.Default()) -} diff --git a/src/pkg/knowledge/inception_vault_connect_test.go b/src/pkg/knowledge/inception_vault_connect_test.go deleted file mode 100644 index 0caffc8f5e..0000000000 --- a/src/pkg/knowledge/inception_vault_connect_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package knowledge - -import ( - "encoding/json" - "io" - "log/slog" - "os" - "path/filepath" - "testing" -) - -// TestConnectExistingVault_NilAPI verifies connectExistingVault returns -// safely when the KnowledgeAPI is nil. -func TestConnectExistingVault_NilAPI(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - e := &InceptionEngine{dataDir: dir, api: nil, logger: logger} - // Should not panic. - e.connectExistingVault() -} - -// TestConnectExistingVault_MissingDir verifies connectExistingVault -// is a no-op when the inception-wiki directory does not exist. -func TestConnectExistingVault_MissingDir(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - kapi := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - e := &InceptionEngine{dataDir: dir, api: kapi, logger: logger} - // No inception-wiki dir — should return without error. - e.connectExistingVault() -} - -// TestConnectExistingVault_EmptyDir verifies connectExistingVault -// is a no-op when the inception-wiki directory exists but is empty. -func TestConnectExistingVault_EmptyDir(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - kapi := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - vaultDir := filepath.Join(dir, inceptionWikiDir) - if err := os.MkdirAll(vaultDir, 0o755); err != nil { - t.Fatalf("mkdir: %v", err) - } - e := &InceptionEngine{dataDir: dir, api: kapi, logger: logger} - e.connectExistingVault() -} - -// TestConnectExistingVault_WithFiles verifies connectExistingVault -// reconnects a vault when the inception-wiki directory has files. -func TestConnectExistingVault_WithFiles(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - kapi := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - vaultDir := filepath.Join(dir, inceptionWikiDir) - if err := os.MkdirAll(vaultDir, 0o755); err != nil { - t.Fatalf("mkdir: %v", err) - } - if err := os.WriteFile(filepath.Join(vaultDir, "test.md"), []byte("# Test"), 0o644); err != nil { - t.Fatalf("write: %v", err) - } - e := &InceptionEngine{dataDir: dir, api: kapi, logger: logger} - e.connectExistingVault() - - // Calling again should hit the "already connected" branch. - e.connectExistingVault() -} - -// TestConnectExistingVault_WithCustomWikiName verifies connectExistingVault -// uses the WikiName from saved state instead of the default. -func TestConnectExistingVault_WithCustomWikiName(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - kapi := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - - // Create inception-wiki directory with a file. - vaultDir := filepath.Join(dir, inceptionWikiDir) - if err := os.MkdirAll(vaultDir, 0o755); err != nil { - t.Fatalf("mkdir: %v", err) - } - if err := os.WriteFile(filepath.Join(vaultDir, "fact.md"), []byte("# Fact\nBody"), 0o644); err != nil { - t.Fatalf("write: %v", err) - } - - // Write a state file with a custom WikiName so connectExistingVault uses it. - stateDir := filepath.Join(dir, "inception") - if err := os.MkdirAll(stateDir, 0o755); err != nil { - t.Fatalf("mkdir: %v", err) - } - state := &InceptionState{WikiName: "my-custom-wiki"} - stateBytes, err := json.Marshal(state) - if err != nil { - t.Fatalf("marshal: %v", err) - } - if err := os.WriteFile(filepath.Join(stateDir, "state.json"), stateBytes, 0o644); err != nil { - t.Fatalf("write state: %v", err) - } - - // NewInceptionEngine loads state then calls connectExistingVault. - eng := NewInceptionEngine(dir, kapi, logger) - if eng == nil { - t.Fatal("nil engine") - } -} - -// TestNewInceptionEngine_FullStartup exercises the constructor with -// pre-existing state and wiki files — the most realistic startup path. -func TestNewInceptionEngine_FullStartup(t *testing.T) { - dir := t.TempDir() - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - kapi := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - - // First create and start an inception so state + wiki exist. - eng1 := NewInceptionEngine(dir, kapi, logger) - if _, err := eng1.Start("test startup project in go"); err != nil { - t.Fatalf("Start: %v", err) - } - - // Create a wiki file so connectExistingVault finds content. - vaultDir := filepath.Join(dir, inceptionWikiDir) - if err := os.MkdirAll(vaultDir, 0o755); err != nil { - t.Fatalf("mkdir: %v", err) - } - if err := os.WriteFile(filepath.Join(vaultDir, "readme.md"), []byte("# Hello"), 0o644); err != nil { - t.Fatalf("write: %v", err) - } - - // Re-create the engine — simulates a restart. - kapi2 := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) - eng2 := NewInceptionEngine(dir, kapi2, logger) - if eng2 == nil { - t.Fatal("nil engine on restart") - } - if st := eng2.GetState(); st == nil { - t.Fatal("state should be loaded on restart") - } -} diff --git a/src/pkg/knowledge/inception_wiki.go b/src/pkg/knowledge/inception_wiki.go new file mode 100644 index 0000000000..63cf3ace2c --- /dev/null +++ b/src/pkg/knowledge/inception_wiki.go @@ -0,0 +1,63 @@ +package knowledge + +import ( + "encoding/json" + "io" + "log/slog" + "os" + "path/filepath" + "strings" +) + +const ( + // inceptionWikiDir is where past inception runs wrote their ideation + // facts (vision, constitution, requirements, ...) as Markdown files, + // relative to the data dir. + inceptionWikiDir = "inception-wiki" + // inceptionWikiDefaultName is the vault name those runs registered. + inceptionWikiDefaultName = "inception-wiki" + // inceptionStateFile carried an optional custom vault name (WikiName). + inceptionStateFile = "inception/state.json" +) + +// ReconnectInceptionWiki keeps the knowledge facts produced by past +// inception runs available after the inception engine was retired in favour +// of Inception (spek) sessions. Those facts live as Markdown files under +// <dataDir>/inception-wiki; the engine used to reconnect that directory as a +// knowledge vault on every boot, so this does the same. It only reads: no +// fact, vault file or state file is written, moved or deleted. +func ReconnectInceptionWiki(dataDir string, api *KnowledgeAPI, logger *slog.Logger) { + if logger == nil { + logger = slog.New(slog.NewTextHandler(io.Discard, nil)) + } + if api == nil { + return + } + vaultDir := filepath.Join(dataDir, inceptionWikiDir) + entries, err := os.ReadDir(vaultDir) + if err != nil || len(entries) == 0 { + return + } + name := inceptionWikiName(dataDir) + if err := api.ConnectVault(vaultDir, name); err != nil { + if !strings.Contains(err.Error(), "already connected") { + logger.Warn("failed to reconnect inception wiki on startup", "error", err) + } + return + } + logger.Info("inception wiki reconnected on startup", "dir", vaultDir, "name", name, "files", len(entries)) +} + +// inceptionWikiName returns the vault name a past run saved in its state +// file (a renamed wiki), or the default. +func inceptionWikiName(dataDir string) string { + data, err := os.ReadFile(filepath.Join(dataDir, inceptionStateFile)) + if err != nil { + return inceptionWikiDefaultName + } + var state InceptionState + if json.Unmarshal(data, &state) != nil || strings.TrimSpace(state.WikiName) == "" { + return inceptionWikiDefaultName + } + return state.WikiName +} diff --git a/src/pkg/knowledge/inception_wiki_test.go b/src/pkg/knowledge/inception_wiki_test.go new file mode 100644 index 0000000000..daf17a3ce1 --- /dev/null +++ b/src/pkg/knowledge/inception_wiki_test.go @@ -0,0 +1,83 @@ +package knowledge + +import ( + "encoding/json" + "io" + "log/slog" + "os" + "path/filepath" + "testing" +) + +func writeInceptionWikiFixture(t *testing.T, dir, wikiName string) string { + t.Helper() + vault := filepath.Join(dir, inceptionWikiDir) + if err := os.MkdirAll(vault, 0o755); err != nil { + t.Fatal(err) + } + fact := filepath.Join(vault, "vision.md") + if err := os.WriteFile(fact, []byte("---\ntype: vision\n---\n# Vision\nBody"), 0o644); err != nil { + t.Fatal(err) + } + if wikiName != "" { + state, _ := json.Marshal(InceptionState{WikiName: wikiName}) + if err := os.MkdirAll(filepath.Join(dir, "inception"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, inceptionStateFile), state, 0o644); err != nil { + t.Fatal(err) + } + } + return fact +} + +func vaultNames(api *KnowledgeAPI) map[string]bool { + out := map[string]bool{} + for _, v := range api.Vaults() { + out[v.Name] = true + } + return out +} + +// Past inception facts must stay served (and untouched) after the inception +// engine was retired. +func TestReconnectInceptionWikiKeepsPastFacts(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + for _, c := range []struct{ saved, want string }{ + {"", inceptionWikiDefaultName}, + {"my-custom-wiki", "my-custom-wiki"}, + } { + dir := t.TempDir() + fact := writeInceptionWikiFixture(t, dir, c.saved) + api := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) + ReconnectInceptionWiki(dir, api, logger) + if !vaultNames(api)[c.want] { + t.Fatalf("vault %q not connected; vaults = %v", c.want, api.Vaults()) + } + // A second call hits the already-connected branch quietly. + ReconnectInceptionWiki(dir, api, nil) + if _, err := os.Stat(fact); err != nil { + t.Fatalf("past inception fact must stay on disk: %v", err) + } + } +} + +func TestReconnectInceptionWikiNoops(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + ReconnectInceptionWiki(t.TempDir(), nil, logger) + + missing := t.TempDir() + api := NewKnowledgeAPI(nil, KnowledgeConfig{}, logger) + ReconnectInceptionWiki(missing, api, logger) + empty := t.TempDir() + if err := os.MkdirAll(filepath.Join(empty, inceptionWikiDir), 0o755); err != nil { + t.Fatal(err) + } + ReconnectInceptionWiki(empty, api, logger) + if vaultNames(api)[inceptionWikiDefaultName] { + t.Fatal("no files: nothing must be connected") + } + if got := inceptionWikiName(missing); got != inceptionWikiDefaultName { + t.Fatalf("inceptionWikiName with no state = %q", got) + } +} diff --git a/src/pkg/knowledge/slug.go b/src/pkg/knowledge/slug.go new file mode 100644 index 0000000000..9669ff3aa0 --- /dev/null +++ b/src/pkg/knowledge/slug.go @@ -0,0 +1,31 @@ +package knowledge + +import "strings" + +// slugify and xmlEscape outlived the inception engine they were written for: +// vault, codemap, document-source and suggestion code still use them. + +func slugify(s string) string { + s = strings.ToLower(s) + s = strings.Map(func(r rune) rune { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' { + return r + } + if r == ' ' || r == '_' || r == '\n' || r == '\r' || r == '\t' { + return '-' + } + return -1 + }, s) + for strings.Contains(s, "--") { + s = strings.ReplaceAll(s, "--", "-") + } + return strings.Trim(s, "-") +} + +func xmlEscape(s string) string { + s = strings.ReplaceAll(s, "&", "&") + s = strings.ReplaceAll(s, "<", "<") + s = strings.ReplaceAll(s, ">", ">") + s = strings.ReplaceAll(s, `"`, """) + return s +} diff --git a/src/pkg/policies/defaults/brainstorm-advisory.md b/src/pkg/policies/defaults/brainstorm-advisory.md index 23866af8cb..431ad1f4cf 100644 --- a/src/pkg/policies/defaults/brainstorm-advisory.md +++ b/src/pkg/policies/defaults/brainstorm-advisory.md @@ -9,123 +9,14 @@ You are the **brainstorm** agent. Advisory mode only — beads, never GitHub iss - Write heartbeat entries - Search GitHub - Read other policy files -- Do general ideation or repo analysis -**Idea**: ${INCEPTION_IDEA} -**Phase**: ${INCEPTION_PHASE} -**Mode**: ${INCEPTION_MODE} - -If the Idea field above is empty, skip to the "Normal Ideation Mode" section at the bottom. - -Your ONLY task this kick is to process the inception idea above. Start immediately with the phase-specific instructions below. Do NOT do anything else first. - -### If phase is `capture` — generate clarification questions - -⚠️ **DO NOT run spec-kit, specify, or any init commands during capture phase.** -⚠️ **DO NOT clone repos, read files, or do any setup.** -⚠️ Your ONLY action is to create `bd create` bead commands below. Nothing else. - -The user submitted the idea above. You MUST generate exactly 5–7 targeted clarification questions. The inception engine will NOT advance until at least 5 question beads are recorded. Use community KB patterns (below) to infer smart defaults. - -**Start creating beads IMMEDIATELY — do not think, plan, or run other commands first.** - -Required categories (create ALL of these as separate beads): -1. **language** — what language/runtime (only if not inferable from the idea) -2. **users** — who are the primary users and how will they use it -3. **features** — the 2–3 must-have features -4. **constraints** — what it must NOT do, boundaries, non-functional requirements -5. **testing** — how will you know it's working, success criteria -6. **deployment** — how and where will this run (container, CLI, serverless, etc.) -7. **storage** — what data does it manage and how is it persisted - -For EACH question, run these two commands (one bead per question): - -```bash -bd create --title "Clarification: <question text>" --type advisory --priority 2 \ - --actor brainstorm --external-ref "inception/${INCEPTION_SLUG}" -``` - -Then immediately update the bead with metadata: - -```bash -bd update <bead-id> --set-metadata question_id="<category>" \ - --set-metadata default="<your smart default>" \ - --set-metadata category="<language|users|features|constraints|testing|deployment|storage>" -``` - -Create all 5–7 beads before doing anything else. Do NOT run specify, spec-kit, mkdir, or any other commands. - -**After creating all beads, output a summary table in EXACTLY this format:** - -``` -│ # │ Category │ Question │ Smart Default │ -│ 1 │ users │ <question text> │ <default value> │ -│ 2 │ features │ <question text> │ <default value> │ -│ 3 │ constraints │ <question text> │ <default value> │ -│ 4 │ testing │ <question text> │ <default value> │ -│ 5 │ deployment │ <question text> │ <default value> │ -``` - -This table format is REQUIRED — the inception engine parses it to detect questions. Use │ (box-drawing character) as the column delimiter. Include Category, Question, and Smart Default columns. - -### If phase is `clarify` — review answers - -User answers: - -${INCEPTION_ANSWERS} - -If critical info is still missing, create follow-up question beads. Otherwise produce structured facts. - -### If phase is `structure` — produce KB facts from the idea and answers - -Using the idea and user answers, create structured knowledge base fact beads. - -⚠️ **Create ALL fact beads FIRST, before running any other commands.** -⚠️ Do NOT run spec-kit/specify until all fact beads are created. - -**Create KB fact beads** — one bead per fact, based on the idea and answers: - -- 1 **vision** fact — from the project brief: what this project is and why -- 1 **constitution** fact — from CONSTITUTION.md: language, architecture, testing philosophy, code style, dependency philosophy -- 2–5 **requirement** facts — from SPEC.md: what the system must do -- 1–3 **constraint** facts — from SPEC.md constraints: boundaries and non-functional requirements -- 1–2 **stakeholder** facts — who uses this and their needs -- 2–5 **acceptance** facts — from PLAN.md: testable success criteria - -```bash -bd create --title "<fact title>" --type advisory --priority 1 \ - --actor brainstorm --external-ref "inception/${INCEPTION_SLUG}" -bd update <bead-id> --set-metadata fact_type="<vision|constitution|requirement|constraint|stakeholder|acceptance>" -bd update <bead-id> --set-metadata fact_body="<detailed content from spec-kit artifact>" -``` - -Optionally, initialize a spec-kit project for the scaffold phase: - -```bash -mkdir -p /tmp/inception-specs && cd /tmp/inception-specs -/usr/local/bin/specify init --here --ai copilot --no-git --force 2>/dev/null || true -``` - -### If phase is `scaffold` — generate bootstrap files from spec-kit + facts - -Include the spec-kit artifacts directly as scaffold output: -- `specs/CONSTITUTION.md` — immutable project principles (from spec-kit) -- `specs/SPEC.md` — structured requirements (from spec-kit) -- `specs/PLAN.md` — implementation steps (from spec-kit) -- `specs/TASKS.md` — concrete task breakdown (from spec-kit) -- `README.md` — from vision + requirements -- `CLAUDE.md` — from constitution + constraints -- Test stubs — from acceptance criteria -- `.github/workflows/ci.yml` — from constitution language -- `CONTRIBUTING.md` — from constitution code style - -Record each file as a bead with content in metadata. +Interactive project inception (turning a raw idea into specs, plans and a starting project) now happens in Inception (spek) sessions in the dashboard, not through this agent. --- -## Normal Ideation Mode (no inception active) +## Ideation -If no inception idea is provided above, do ongoing ideation: +Do ongoing ideation: - **Feature proposals** — based on gaps in the codebase, community patterns, or KB insights - **Architecture improvements** — refactoring opportunities, performance bottlenecks, tech debt @@ -146,7 +37,8 @@ bd update <bead-id> --set-metadata detail="<detailed proposal>" 1. **DO NOT create PRs, push code, or merge anything** 2. **DO NOT create GitHub issues** — findings go to beads only -3. **Only close your own beads** — where `actor` is `brainstorm` +3. **DO NOT clone repos** or run setup/init commands — ideation works from the KB and the kick context +4. **Only close your own beads** — where `actor` is `brainstorm` ## Reaping @@ -154,8 +46,6 @@ bd update <bead-id> --set-metadata detail="<detailed proposal>" bd list --status=open --actor=brainstorm --json 2>/dev/null ``` -⚠️ **DO NOT close beads with external_ref starting with "inception/"** — these are active inception question/fact beads managed by the inception engine. Only close non-inception beads that are genuinely stale. - -Close stale beads (non-inception only). Print: `Reap: <N> open, <M> closed this cycle` +Beads with an external_ref starting with "inception/" were left by the retired inception workflow; leave them open unless an operator asks you to close them. Close other stale beads. Print: `Reap: <N> open, <M> closed this cycle` ${KNOWLEDGE} diff --git a/src/pkg/policies/source_sync_test.go b/src/pkg/policies/source_sync_test.go index 8ff51054d7..b41d4e13ef 100644 --- a/src/pkg/policies/source_sync_test.go +++ b/src/pkg/policies/source_sync_test.go @@ -215,10 +215,10 @@ func TestPolicyGuardrailsPresent(t *testing.T) { why: "PRs must be opened by the App via hive-open-pr, not raw gh or the GitHub MCP create_pull_request", }, { - name: "brainstorm-advisory forbids setup during capture", + name: "brainstorm-advisory forbids setup", file: "brainstorm-advisory.md", fragment: "DO NOT clone repos", - why: "capture phase must not clone or run init commands", + why: "the advisory brainstorm agent must not clone or run init commands", }, } diff --git a/src/pkg/scheduler/kick_priming_test.go b/src/pkg/scheduler/kick_priming_test.go index 6a8b0121be..d90fc0d90b 100644 --- a/src/pkg/scheduler/kick_priming_test.go +++ b/src/pkg/scheduler/kick_priming_test.go @@ -2,7 +2,6 @@ package scheduler import ( "context" - "encoding/json" "errors" "log/slog" "os" @@ -12,7 +11,6 @@ import ( "time" "github.com/hivecommons/hive/pkg/config" - "github.com/hivecommons/hive/pkg/knowledge" ) // --- agentsRepoRoot --- @@ -201,137 +199,6 @@ func TestPrimeAgentsMd_EmptyAgentsMdYieldsEmpty(t *testing.T) { } } -// --- inceptionVars --- - -// writeInceptionState persists a crafted state file where NewInceptionEngine -// loads it from, so tests can exercise states not reachable via Start alone. -func writeInceptionState(t *testing.T, dataDir string, state knowledge.InceptionState) { - t.Helper() - dir := filepath.Join(dataDir, "inception") - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - raw, err := json.Marshal(state) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, "state.json"), raw, 0o644); err != nil { - t.Fatal(err) - } -} - -func TestInceptionVars_NoEngine(t *testing.T) { - s := New(&config.Config{}, slog.Default()) - idea, phase, mode, answers, slug, repoURL := s.inceptionVars() - if idea != "" || phase != "" || mode != "" || answers != "" || slug != "" || repoURL != "" { - t.Errorf("inceptionVars() with no engine = (%q,%q,%q,%q,%q,%q), want all empty", - idea, phase, mode, answers, slug, repoURL) - } -} - -func TestInceptionVars_EngineWithoutState(t *testing.T) { - s := New(&config.Config{}, slog.Default()) - s.SetInception(knowledge.NewInceptionEngine(t.TempDir(), nil, nil)) - - idea, phase, mode, answers, slug, repoURL := s.inceptionVars() - if idea != "" || phase != "" || mode != "" || answers != "" || slug != "" || repoURL != "" { - t.Errorf("inceptionVars() with stateless engine = (%q,%q,%q,%q,%q,%q), want all empty", - idea, phase, mode, answers, slug, repoURL) - } -} - -func TestInceptionVars_GreenfieldState(t *testing.T) { - dataDir := t.TempDir() - writeInceptionState(t, dataDir, knowledge.InceptionState{ - Phase: knowledge.PhaseCapture, - Mode: knowledge.InceptionGreenfield, - IdeaText: "a CLI that summarizes build logs", - IdeaSlug: "idea-cli-build-logs", - Questions: []knowledge.Question{ - {ID: "q1", Text: "Which language?", Category: "language"}, - }, - Answers: map[string]string{"q1": "Go"}, - FactSlugs: []string{"idea-cli-build-logs"}, - StartedAt: time.Now(), - }) - - s := New(&config.Config{}, slog.Default()) - s.SetInception(knowledge.NewInceptionEngine(dataDir, nil, nil)) - - idea, phase, mode, answers, slug, repoURL := s.inceptionVars() - if idea != "a CLI that summarizes build logs" { - t.Errorf("idea = %q, want the greenfield idea text", idea) - } - if phase != string(knowledge.PhaseCapture) { - t.Errorf("phase = %q, want %q", phase, knowledge.PhaseCapture) - } - if mode != string(knowledge.InceptionGreenfield) { - t.Errorf("mode = %q, want %q", mode, knowledge.InceptionGreenfield) - } - if slug != "idea-cli-build-logs" { - t.Errorf("slug = %q, want idea-cli-build-logs", slug) - } - if repoURL != "" { - t.Errorf("repoURL = %q, want empty for greenfield", repoURL) - } - if !strings.Contains(answers, "Which language?") || !strings.Contains(answers, "Go") { - t.Errorf("answers = %q, want rendered question and answer", answers) - } -} - -func TestInceptionVars_BrownfieldIdeaFallsBackToRepoURL(t *testing.T) { - dataDir := t.TempDir() - writeInceptionState(t, dataDir, knowledge.InceptionState{ - Phase: knowledge.PhaseCapture, - Mode: knowledge.InceptionBrownfield, - IdeaText: "", // crafted: force the RepoURL fallback branch - IdeaSlug: "idea-brownfield-repo", - RepoURL: "https://github.com/example/legacy", - Answers: map[string]string{}, - FactSlugs: []string{}, - StartedAt: time.Now(), - }) - - s := New(&config.Config{}, slog.Default()) - s.SetInception(knowledge.NewInceptionEngine(dataDir, nil, nil)) - - idea, _, mode, answers, _, repoURL := s.inceptionVars() - if mode != string(knowledge.InceptionBrownfield) { - t.Errorf("mode = %q, want %q", mode, knowledge.InceptionBrownfield) - } - if repoURL != "https://github.com/example/legacy" { - t.Errorf("repoURL = %q, want the brownfield repo URL", repoURL) - } - if idea != repoURL { - t.Errorf("idea = %q, want fallback to repoURL %q when IdeaText is empty", idea, repoURL) - } - if answers != "" { - t.Errorf("answers = %q, want empty with no recorded answers", answers) - } -} - -func TestInceptionVars_GreenfieldEmptyIdeaDoesNotFallBack(t *testing.T) { - dataDir := t.TempDir() - writeInceptionState(t, dataDir, knowledge.InceptionState{ - Phase: knowledge.PhaseCapture, - Mode: knowledge.InceptionGreenfield, - IdeaText: "", - IdeaSlug: "idea-empty", - RepoURL: "https://github.com/example/should-not-leak", - Answers: map[string]string{}, - FactSlugs: []string{}, - StartedAt: time.Now(), - }) - - s := New(&config.Config{}, slog.Default()) - s.SetInception(knowledge.NewInceptionEngine(dataDir, nil, nil)) - - idea, _, _, _, _, _ := s.inceptionVars() - if idea != "" { - t.Errorf("idea = %q, want empty: RepoURL fallback is brownfield-only", idea) - } -} - // --- remoteAgentsRepoRoot (GitHub fallback, #17090) --- type fakeAgentsMdFetcher struct { diff --git a/src/pkg/scheduler/scheduler.go b/src/pkg/scheduler/scheduler.go index 565d699fd0..6bf62d3a8d 100644 --- a/src/pkg/scheduler/scheduler.go +++ b/src/pkg/scheduler/scheduler.go @@ -19,7 +19,6 @@ type Scheduler struct { surgeDuration func() (time.Duration, bool) cfg *config.Config primer *knowledge.Primer - inception *knowledge.InceptionEngine lastActionable *github.ActionableResult logger *slog.Logger primerCapLogged sync.Map // agent|cap_bytes -> omitted fact count last logged at INFO @@ -162,21 +161,6 @@ func (s *Scheduler) GetPrimer() *knowledge.Primer { return s.primer } -// SetInception attaches an inception engine so kick templates can inject -// ideation state via ${INCEPTION_*} variables. -func (s *Scheduler) SetInception(ie *knowledge.InceptionEngine) { - s.mu.Lock() - defer s.mu.Unlock() - s.inception = ie -} - -// GetInception returns the attached inception engine, or nil if none is set. -func (s *Scheduler) GetInception() *knowledge.InceptionEngine { - s.mu.RLock() - defer s.mu.RUnlock() - return s.inception -} - // SetLastActionable caches the latest actionable result so manual kicks // (via the dashboard API) can prime knowledge from the same issue set. func (s *Scheduler) SetLastActionable(a *github.ActionableResult) { diff --git a/src/pkg/scheduler/scheduler_mutex_test.go b/src/pkg/scheduler/scheduler_mutex_test.go index 7f0fbafea5..856c10cdd2 100644 --- a/src/pkg/scheduler/scheduler_mutex_test.go +++ b/src/pkg/scheduler/scheduler_mutex_test.go @@ -23,17 +23,6 @@ func TestGetSetPrimer(t *testing.T) { } } -func TestGetSetInception(t *testing.T) { - s := New(&config.Config{}, slog.Default()) - if s.GetInception() != nil { - t.Error("initial inception should be nil") - } - s.SetInception(nil) - if s.GetInception() != nil { - t.Error("inception should still be nil") - } -} - func TestGetSetLastActionable(t *testing.T) { s := New(&config.Config{}, slog.Default()) if s.GetLastActionable() != nil { diff --git a/src/pkg/scheduler/templates.go b/src/pkg/scheduler/templates.go index 2deab32b28..1d3ccefd11 100644 --- a/src/pkg/scheduler/templates.go +++ b/src/pkg/scheduler/templates.go @@ -11,7 +11,6 @@ import ( "github.com/hivecommons/hive/pkg/config" "github.com/hivecommons/hive/pkg/github" - "github.com/hivecommons/hive/pkg/knowledge" "github.com/hivecommons/hive/pkg/policies" "github.com/hivecommons/hive/pkg/resolve" ) @@ -263,32 +262,6 @@ func (s *Scheduler) substituteTemplateWithPolicy(template string, actionable *gi return s.substituteTemplateWithVars(template, actionable, agentName, issues, nil) } -// inceptionVars extracts template variable values from the inception engine. -// Returns empty strings when no inception is active — templates render cleanly. -func (s *Scheduler) inceptionVars() (idea, phase, mode, answers, slug, repoURL string) { - s.mu.RLock() - inception := s.inception - s.mu.RUnlock() - if inception == nil { - return - } - state := inception.GetState() - if state == nil { - return - } - phase = string(state.Phase) - mode = string(state.Mode) - slug = state.IdeaSlug - repoURL = state.RepoURL - answers = s.inception.FormatAnswersForPrompt() - - idea = state.IdeaText - if idea == "" && state.Mode == knowledge.InceptionBrownfield { - idea = state.RepoURL - } - return -} - // substituteTemplateWithVars is substituteTemplateWithPolicy plus caller-supplied // ${VAR}s, for a template whose values only one call site can compute. // @@ -397,8 +370,6 @@ func (s *Scheduler) substituteTemplateWithVars(template string, actionable *gith } s.logKnowledgeInjection(agentName, knowledgeInj, len(agentsSection), len(skillsSection)) - inceptionIdea, inceptionPhase, inceptionMode, inceptionAnswers, inceptionSlug, inceptionRepoURL := s.inceptionVars() - // The merge-eligible and CI-failing lists are read from hive-wide metrics // files, so they need the same narrowing: a scoped agent asked to fix red CI // must not be handed a red PR on a repo it cannot push to (#6204). @@ -444,14 +415,18 @@ func (s *Scheduler) substituteTemplateWithVars(template string, actionable *gith "AGENT_ROLES": lit(agentRoles), "ENABLED_AGENTS": lit(agentList), "KNOWLEDGE": lit(knowledgeSection), - "INCEPTION_IDEA": lit(inceptionIdea), - "INCEPTION_PHASE": lit(inceptionPhase), - "INCEPTION_MODE": lit(inceptionMode), - "INCEPTION_ANSWERS": lit(inceptionAnswers), - "INCEPTION_SLUG": lit(inceptionSlug), - "INCEPTION_REPO_URL": lit(inceptionRepoURL), - "MERGE_ELIGIBLE": lit(mergeEligibleList), - "CI_FAILING": lit(ciFailingList), + // The ${INCEPTION_*} family belonged to the retired inception + // workflow. It always renders empty so an operator's custom template + // that still names it (the brainstorm "Normal Ideation Mode" branch + // keyed off an empty idea) keeps rendering cleanly for one release. + "INCEPTION_IDEA": lit(""), + "INCEPTION_PHASE": lit(""), + "INCEPTION_MODE": lit(""), + "INCEPTION_ANSWERS": lit(""), + "INCEPTION_SLUG": lit(""), + "INCEPTION_REPO_URL": lit(""), + "MERGE_ELIGIBLE": lit(mergeEligibleList), + "CI_FAILING": lit(ciFailingList), }} // Caller-supplied vars lose a name clash: one already claimed by a built-in // above is left alone, so no call site can redefine ${GH_AUTH}. diff --git a/src/policies/README.md b/src/policies/README.md index cace5a9319..0709c146e3 100644 --- a/src/policies/README.md +++ b/src/policies/README.md @@ -30,7 +30,7 @@ Examples in the current packs: - `dedupe-issues.md` is the L5/L6 `dedupe` lane: a daily sweep over every open issue and PR that files and then updates in place one consolidation checklist issue per repository (hivecommons/hive#11582); it never closes or edits anyone else's items. - `redteam-holdgated.md` is the opt-in L5/L6 `redteam` lane (hivecommons/hive#17420), at both levels: it plays a malicious contributor and adds measured attack cases to the `ioscan` red-team corpus in `hold`-labelled PRs, never posting attack text anywhere else. - `supervisor-nogithub.md` is the supervisor policy from L2 through L6; it keeps orchestration separate from GitHub mutation. -- `brainstorm-advisory.md` is the only brainstorm template referenced by v4, including L1 inception. `brainstorm-inception.md` is mentioned only by stale documentation from the retired v2 line, so operators should not create or rely on that filename unless they also set `kick_template` to it. +- `brainstorm-advisory.md` is the only brainstorm template referenced by v4. It is ideation only: the inception workflow it used to drive was retired in favour of Inception (spek) sessions. `brainstorm-inception.md` is mentioned only by stale documentation from the retired v2 line, so operators should not create or rely on that filename unless they also set `kick_template` to it. ## Customizing prompts @@ -94,12 +94,12 @@ The complete built-in scheduler set in v4 is: | `${ENABLED_AGENTS}` | Formatted enabled-agent list. | Alias of `${AGENT_LIST}`. | | `${AGENT_ROLES}` | Formatted role/metadata summary for configured agents. | Built from current config. | | `${KNOWLEDGE}` | Knowledge priming section for relevant issues. | Populated by configured knowledge layers; otherwise renders the scheduler's empty/none text. | -| `${INCEPTION_IDEA}` | Current inception idea text. | Empty when no inception run is active. | -| `${INCEPTION_PHASE}` | Current inception phase. | Empty when inactive. | -| `${INCEPTION_MODE}` | Current inception mode. | Empty when inactive. | -| `${INCEPTION_ANSWERS}` | Collected inception answers. | Empty when inactive. | -| `${INCEPTION_SLUG}` | Inception slug. | Empty when inactive. | -| `${INCEPTION_REPO_URL}` | Inception repository URL. | Empty when inactive. | +| `${INCEPTION_IDEA}` | Deprecated: the inception workflow was retired. | Always empty; kept for one release so custom templates still render. | +| `${INCEPTION_PHASE}` | Deprecated. | Always empty. | +| `${INCEPTION_MODE}` | Deprecated. | Always empty. | +| `${INCEPTION_ANSWERS}` | Deprecated. | Always empty. | +| `${INCEPTION_SLUG}` | Deprecated. | Always empty. | +| `${INCEPTION_REPO_URL}` | Deprecated. | Always empty. | | `${MERGE_ELIGIBLE}` | Formatted merge-eligible PR list from `/var/run/hive-metrics/merge-eligible.json`. | Renders `(none)` when the file is absent, invalid, or empty. | | `${CI_FAILING}` | Formatted failing-CI PR list from `/var/run/hive-metrics/ci-failing.json`. Held red PRs (`hold` label) are counted but not listed here: a held PR is repaired only by the agent that opened it, via the FIX-BEFORE-NEW block the scheduler prepends to that agent's kick, which marks it `held for human review — fix CI, do not remove the hold` ([#7438](https://github.com/hivecommons/hive/issues/7438)). Red PRs already deferred to a still-open shared-CI incident (`deferred_incident`) are listed under a separate `DEFERRED TO OPEN SHARED-CI INCIDENTS` heading with no repair instructions, and the FIX-BEFORE-NEW block omits them ([#10528](https://github.com/hivecommons/hive/issues/10528)). | Renders `(none)` when the file is absent, invalid, or empty. | diff --git a/src/policies/brainstorm-advisory.md b/src/policies/brainstorm-advisory.md index 23866af8cb..431ad1f4cf 100644 --- a/src/policies/brainstorm-advisory.md +++ b/src/policies/brainstorm-advisory.md @@ -9,123 +9,14 @@ You are the **brainstorm** agent. Advisory mode only — beads, never GitHub iss - Write heartbeat entries - Search GitHub - Read other policy files -- Do general ideation or repo analysis -**Idea**: ${INCEPTION_IDEA} -**Phase**: ${INCEPTION_PHASE} -**Mode**: ${INCEPTION_MODE} - -If the Idea field above is empty, skip to the "Normal Ideation Mode" section at the bottom. - -Your ONLY task this kick is to process the inception idea above. Start immediately with the phase-specific instructions below. Do NOT do anything else first. - -### If phase is `capture` — generate clarification questions - -⚠️ **DO NOT run spec-kit, specify, or any init commands during capture phase.** -⚠️ **DO NOT clone repos, read files, or do any setup.** -⚠️ Your ONLY action is to create `bd create` bead commands below. Nothing else. - -The user submitted the idea above. You MUST generate exactly 5–7 targeted clarification questions. The inception engine will NOT advance until at least 5 question beads are recorded. Use community KB patterns (below) to infer smart defaults. - -**Start creating beads IMMEDIATELY — do not think, plan, or run other commands first.** - -Required categories (create ALL of these as separate beads): -1. **language** — what language/runtime (only if not inferable from the idea) -2. **users** — who are the primary users and how will they use it -3. **features** — the 2–3 must-have features -4. **constraints** — what it must NOT do, boundaries, non-functional requirements -5. **testing** — how will you know it's working, success criteria -6. **deployment** — how and where will this run (container, CLI, serverless, etc.) -7. **storage** — what data does it manage and how is it persisted - -For EACH question, run these two commands (one bead per question): - -```bash -bd create --title "Clarification: <question text>" --type advisory --priority 2 \ - --actor brainstorm --external-ref "inception/${INCEPTION_SLUG}" -``` - -Then immediately update the bead with metadata: - -```bash -bd update <bead-id> --set-metadata question_id="<category>" \ - --set-metadata default="<your smart default>" \ - --set-metadata category="<language|users|features|constraints|testing|deployment|storage>" -``` - -Create all 5–7 beads before doing anything else. Do NOT run specify, spec-kit, mkdir, or any other commands. - -**After creating all beads, output a summary table in EXACTLY this format:** - -``` -│ # │ Category │ Question │ Smart Default │ -│ 1 │ users │ <question text> │ <default value> │ -│ 2 │ features │ <question text> │ <default value> │ -│ 3 │ constraints │ <question text> │ <default value> │ -│ 4 │ testing │ <question text> │ <default value> │ -│ 5 │ deployment │ <question text> │ <default value> │ -``` - -This table format is REQUIRED — the inception engine parses it to detect questions. Use │ (box-drawing character) as the column delimiter. Include Category, Question, and Smart Default columns. - -### If phase is `clarify` — review answers - -User answers: - -${INCEPTION_ANSWERS} - -If critical info is still missing, create follow-up question beads. Otherwise produce structured facts. - -### If phase is `structure` — produce KB facts from the idea and answers - -Using the idea and user answers, create structured knowledge base fact beads. - -⚠️ **Create ALL fact beads FIRST, before running any other commands.** -⚠️ Do NOT run spec-kit/specify until all fact beads are created. - -**Create KB fact beads** — one bead per fact, based on the idea and answers: - -- 1 **vision** fact — from the project brief: what this project is and why -- 1 **constitution** fact — from CONSTITUTION.md: language, architecture, testing philosophy, code style, dependency philosophy -- 2–5 **requirement** facts — from SPEC.md: what the system must do -- 1–3 **constraint** facts — from SPEC.md constraints: boundaries and non-functional requirements -- 1–2 **stakeholder** facts — who uses this and their needs -- 2–5 **acceptance** facts — from PLAN.md: testable success criteria - -```bash -bd create --title "<fact title>" --type advisory --priority 1 \ - --actor brainstorm --external-ref "inception/${INCEPTION_SLUG}" -bd update <bead-id> --set-metadata fact_type="<vision|constitution|requirement|constraint|stakeholder|acceptance>" -bd update <bead-id> --set-metadata fact_body="<detailed content from spec-kit artifact>" -``` - -Optionally, initialize a spec-kit project for the scaffold phase: - -```bash -mkdir -p /tmp/inception-specs && cd /tmp/inception-specs -/usr/local/bin/specify init --here --ai copilot --no-git --force 2>/dev/null || true -``` - -### If phase is `scaffold` — generate bootstrap files from spec-kit + facts - -Include the spec-kit artifacts directly as scaffold output: -- `specs/CONSTITUTION.md` — immutable project principles (from spec-kit) -- `specs/SPEC.md` — structured requirements (from spec-kit) -- `specs/PLAN.md` — implementation steps (from spec-kit) -- `specs/TASKS.md` — concrete task breakdown (from spec-kit) -- `README.md` — from vision + requirements -- `CLAUDE.md` — from constitution + constraints -- Test stubs — from acceptance criteria -- `.github/workflows/ci.yml` — from constitution language -- `CONTRIBUTING.md` — from constitution code style - -Record each file as a bead with content in metadata. +Interactive project inception (turning a raw idea into specs, plans and a starting project) now happens in Inception (spek) sessions in the dashboard, not through this agent. --- -## Normal Ideation Mode (no inception active) +## Ideation -If no inception idea is provided above, do ongoing ideation: +Do ongoing ideation: - **Feature proposals** — based on gaps in the codebase, community patterns, or KB insights - **Architecture improvements** — refactoring opportunities, performance bottlenecks, tech debt @@ -146,7 +37,8 @@ bd update <bead-id> --set-metadata detail="<detailed proposal>" 1. **DO NOT create PRs, push code, or merge anything** 2. **DO NOT create GitHub issues** — findings go to beads only -3. **Only close your own beads** — where `actor` is `brainstorm` +3. **DO NOT clone repos** or run setup/init commands — ideation works from the KB and the kick context +4. **Only close your own beads** — where `actor` is `brainstorm` ## Reaping @@ -154,8 +46,6 @@ bd update <bead-id> --set-metadata detail="<detailed proposal>" bd list --status=open --actor=brainstorm --json 2>/dev/null ``` -⚠️ **DO NOT close beads with external_ref starting with "inception/"** — these are active inception question/fact beads managed by the inception engine. Only close non-inception beads that are genuinely stale. - -Close stale beads (non-inception only). Print: `Reap: <N> open, <M> closed this cycle` +Beads with an external_ref starting with "inception/" were left by the retired inception workflow; leave them open unless an operator asks you to close them. Close other stale beads. Print: `Reap: <N> open, <M> closed this cycle` ${KNOWLEDGE} diff --git a/src/test/e2e_helpers_test.go b/src/test/e2e_helpers_test.go new file mode 100644 index 0000000000..ea01154dbe --- /dev/null +++ b/src/test/e2e_helpers_test.go @@ -0,0 +1,155 @@ +//go:build integration + +// The e2e suite talks to a live hive instance over the network. It only builds with `-tags integration` so that a plain +// `go test ./...` never blocks on an unreachable endpoint (see issue #4402). +// +// To run it: +// +// HIVE_URL=http://<host>:<port> HIVE_TOKEN=<token> go test -tags integration ./test/... + +package test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "testing" + "time" +) + +var ( + hiveURL = os.Getenv("HIVE_URL") + hiveToken = os.Getenv("HIVE_TOKEN") +) + +// TestMain gates the whole suite: it requires HIVE_URL to be set and the +// endpoint to answer a fast TCP dial. Otherwise the suite is skipped instead +// of every request hanging until the per-package panic timeout. +func TestMain(m *testing.M) { + if hiveURL == "" { + fmt.Println("SKIP: HIVE_URL not set; e2e suite requires a live hive endpoint") + os.Exit(0) + } + if err := probeEndpoint(hiveURL, 2*time.Second); err != nil { + fmt.Printf("SKIP: hive endpoint %s unreachable (%v); skipping e2e suite\n", hiveURL, err) + os.Exit(0) + } + os.Exit(m.Run()) +} + +// probeEndpoint does a fast TCP dial against the host:port of rawURL. +func probeEndpoint(rawURL string, timeout time.Duration) error { + u, err := url.Parse(rawURL) + if err != nil { + return fmt.Errorf("invalid HIVE_URL: %w", err) + } + host := u.Host + if u.Port() == "" { + switch u.Scheme { + case "https": + host = net.JoinHostPort(u.Hostname(), "443") + default: + host = net.JoinHostPort(u.Hostname(), "80") + } + } + conn, err := net.DialTimeout("tcp", host, timeout) + if err != nil { + return err + } + conn.Close() + return nil +} + +type apiClient struct { + baseURL string + token string + client *http.Client +} + +func newAPIClient() *apiClient { + return &apiClient{ + baseURL: hiveURL, + token: hiveToken, + client: &http.Client{Timeout: 30 * time.Second}, + } +} + +func (c *apiClient) get(path string) (map[string]interface{}, int, error) { + req, err := http.NewRequest("GET", c.baseURL+path, nil) + if err != nil { + return nil, 0, err + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.client.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + var result map[string]interface{} + json.Unmarshal(body, &result) + return result, resp.StatusCode, nil +} + +func (c *apiClient) post(path string, payload interface{}) (map[string]interface{}, int, error) { + var bodyReader io.Reader + if payload != nil { + data, err := json.Marshal(payload) + if err != nil { + return nil, 0, err + } + bodyReader = bytes.NewReader(data) + } + req, err := http.NewRequest("POST", c.baseURL+path, bodyReader) + if err != nil { + return nil, 0, err + } + req.Header.Set("Content-Type", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.client.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + var result map[string]interface{} + json.Unmarshal(body, &result) + return result, resp.StatusCode, nil +} + +func (c *apiClient) put(path string, payload interface{}) (map[string]interface{}, int, error) { + var bodyReader io.Reader + if payload != nil { + data, err := json.Marshal(payload) + if err != nil { + return nil, 0, err + } + bodyReader = bytes.NewReader(data) + } + req, err := http.NewRequest("PUT", c.baseURL+path, bodyReader) + if err != nil { + return nil, 0, err + } + req.Header.Set("Content-Type", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.client.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + var result map[string]interface{} + json.Unmarshal(body, &result) + return result, resp.StatusCode, nil +} diff --git a/src/test/inception_e2e_test.go b/src/test/inception_e2e_test.go deleted file mode 100644 index a929f42c5e..0000000000 --- a/src/test/inception_e2e_test.go +++ /dev/null @@ -1,385 +0,0 @@ -//go:build integration - -package test - -import ( - "fmt" - "strings" - "testing" - "time" -) - -var testIdeas = []string{ - "A Go CLI tool that recursively scans file permissions and outputs JSON/Markdown reports", - "A Python web scraper that extracts product prices from e-commerce sites and tracks changes", - "A TypeScript React dashboard for monitoring Kubernetes cluster health across namespaces", - "A Go library for parsing and validating YAML configuration files with schema support", - "A Python CLI that analyzes Git repositories for security vulnerabilities in dependencies", - "A TypeScript API server for managing todo lists with real-time WebSocket sync", - "A Go operator that auto-scales Kubernetes deployments based on custom metrics", - "A Python data pipeline that processes CSV files and loads them into PostgreSQL", - "A TypeScript CLI that generates OpenAPI specs from TypeScript interfaces", - "A Go microservice that proxies HTTP requests with rate limiting and caching", -} - -const totalPasses = 10000 - -func TestInceptionE2E(t *testing.T) { - if testing.Short() { - t.Skip("skipping e2e in short mode") - } - - client := newAPIClient() - - // Verify hive is reachable - _, code, err := client.get("/api/version") - if err != nil || code != 200 { - t.Fatalf("hive not reachable at %s: %v (code=%d)", hiveURL, err, code) - } - - passed := 0 - failed := 0 - var failures []PassResult - - for pass := 1; pass <= totalPasses; pass++ { - idea := testIdeas[(pass-1)%len(testIdeas)] - idea = fmt.Sprintf("%s (pass %d)", idea, pass) - - t.Run(fmt.Sprintf("Pass_%d", pass), func(t *testing.T) { - start := time.Now() - result := runSinglePass(t, client, pass, idea) - result.Duration = time.Since(start).String() - - logResult(t, result) - - if result.Status == "fail" { - failed++ - failures = append(failures, result) - t.Errorf("Pass %d FAILED at phase=%s check=%s: %s", pass, result.Phase, result.Check, result.Error) - } else { - passed++ - } - - if pass%100 == 0 { - t.Logf("Progress: %d/%d (passed=%d, failed=%d)", pass, totalPasses, passed, failed) - } - }) - } - - t.Logf("FINAL: %d/%d passed, %d failed", passed, totalPasses, failed) - if failed > 0 { - t.Logf("Failure summary:") - for _, f := range failures { - t.Logf(" Pass %d: [%s] %s at %s — %s", f.Pass, f.Category, f.Check, f.Phase, f.Error) - } - } -} - -func runSinglePass(t *testing.T, client *apiClient, pass int, idea string) PassResult { - result := PassResult{ - Pass: pass, - Idea: idea, - Timestamp: time.Now(), - } - - // Step 0: Restart brainstorm agent for clean context - result.Phase = "restart" - result.Check = "restart_ok" - client.post("/api/restart/brainstorm", nil) - time.Sleep(5 * time.Second) - - // Step 1: Reset - result.Phase = "reset" - result.Check = "reset_ok" - data, code, err := client.post("/api/inception/reset", nil) - if err != nil { - return fail(result, "api_error", fmt.Sprintf("reset failed: %v", err)) - } - if code != 200 { - return fail(result, "api_error", fmt.Sprintf("reset returned %d: %v", code, data)) - } - - // Step 2: Start inception - result.Phase = "capture" - result.Check = "start_ok" - data, code, err = client.post("/api/inception/start", map[string]string{"idea": idea}) - if err != nil { - return fail(result, "api_error", fmt.Sprintf("start failed: %v", err)) - } - if code != 200 { - return fail(result, "api_error", fmt.Sprintf("start returned %d: %v", code, data)) - } - - // Verify state - result.Check = "start_state" - state, err := client.inceptionState() - if err != nil { - return fail(result, "api_error", fmt.Sprintf("state check failed: %v", err)) - } - if state == nil { - return fail(result, "assertion", "state is nil after start") - } - if state["phase"] != "capture" { - return fail(result, "assertion", fmt.Sprintf("expected phase=capture, got %v", state["phase"])) - } - if state["idea_text"] == nil || state["idea_text"].(string) == "" { - return fail(result, "assertion", "idea_text is empty after start") - } - - // CDP: verify capture phase UI - if cdpErr := verifyCDPPhase("capture", pass); cdpErr != "" { - t.Logf("Pass %d CDP warning (capture): %s", pass, cdpErr) - } - - // Step 2.3: Verify brainstorm agent actually started (not stuck at no output) - result.Check = "agent_started" - { - const agentStartWait = 30 * time.Second - const agentStartPoll = 5 * time.Second - deadline := time.Now().Add(agentStartWait) - started := false - for time.Now().Before(deadline) { - lines, _ := client.paneOutput("brainstorm") - if len(lines) > 2 { - started = true - break - } - time.Sleep(agentStartPoll) - } - if !started { - return fail(result, "agent_error", "brainstorm agent has no output after 30s — RestartWithBootstrap may have failed") - } - } - - // Step 2.5: Verify brainstorm agent is processing the inception idea - result.Phase = "capture" - result.Check = "agent_on_task" - { - const agentCheckAttempts = 6 - const agentCheckInterval = 10 * time.Second - agentOnTask := false - for attempt := 0; attempt < agentCheckAttempts; attempt++ { - time.Sleep(agentCheckInterval) - agentLines, _ := client.paneOutput("brainstorm") - agentText := strings.ToLower(strings.Join(agentLines, " ")) - ideaWords := strings.Fields(strings.ToLower(idea)) - matchCount := 0 - for _, w := range ideaWords { - if len(w) > 4 && strings.Contains(agentText, w) { - matchCount++ - } - } - if matchCount >= 2 || strings.Contains(agentText, "inception") || strings.Contains(agentText, "clarif") { - agentOnTask = true - break - } - } - if !agentOnTask { - agentLines, _ := client.paneOutput("brainstorm") - lastLine := "" - if len(agentLines) > 0 { - lastLine = agentLines[len(agentLines)-1] - } - return fail(result, "agent_error", fmt.Sprintf("brainstorm agent not processing inception idea after 60s (last: %s)", lastLine)) - } - } - - // Step 3: Wait for clarify phase (bead watcher detects question beads) - result.Phase = "capture_to_clarify" - result.Check = "phase_advance" - state, err = client.waitForPhase("clarify", 900*time.Second) - if err != nil { - // Check agent output for errors - lines, _ := client.paneOutput("brainstorm") - agentStatus := summarizeAgentOutput(lines) - return fail(result, "timeout", fmt.Sprintf("capture→clarify: %v (agent: %s)", err, agentStatus)) - } - - // Verify questions - result.Check = "questions_populated" - questions, _ := state["questions"].([]interface{}) - const minExpectedQuestions = 5 - if len(questions) < minExpectedQuestions { - return fail(result, "assertion", fmt.Sprintf("expected >=%d questions, got %d", minExpectedQuestions, len(questions))) - } - - // Verify question structure - result.Check = "question_structure" - for i, q := range questions { - qm, ok := q.(map[string]interface{}) - if !ok { - return fail(result, "assertion", fmt.Sprintf("question %d is not a map", i)) - } - if qm["id"] == nil || qm["id"].(string) == "" { - return fail(result, "assertion", fmt.Sprintf("question %d missing id", i)) - } - if qm["text"] == nil || qm["text"].(string) == "" { - return fail(result, "assertion", fmt.Sprintf("question %d missing text", i)) - } - } - - // CDP: verify clarify phase UI (questions visible) - if cdpErr := verifyCDPPhase("clarify", pass); cdpErr != "" { - t.Logf("Pass %d CDP warning (clarify): %s", pass, cdpErr) - } - - // Step 4: Submit answers (use defaults) — always submit, even if phase - // already advanced past clarify. The API accepts late answers and sets - // PhaseChangedAt which the watcher needs to detect post-answer fact beads. - result.Phase = "clarify" - result.Check = "submit_answers" - { - answers := make(map[string]string) - for _, q := range questions { - qm := q.(map[string]interface{}) - id := qm["id"].(string) - def, _ := qm["default"].(string) - if def == "" { - def = "default answer for " + id - } - answers[id] = def - } - data, code, err = client.post("/api/inception/answer", map[string]interface{}{"answers": answers}) - if err != nil { - return fail(result, "api_error", fmt.Sprintf("answer failed: %v", err)) - } - if code != 200 { - return fail(result, "api_error", fmt.Sprintf("answer returned %d: %v", code, data)) - } - } - - // Step 5: Wait for scaffold phase (bead watcher detects fact beads) - result.Phase = "structure_to_scaffold" - result.Check = "phase_advance" - state, err = client.waitForPhase("scaffold", 900*time.Second) - if err != nil { - lines, _ := client.paneOutput("brainstorm") - agentStatus := summarizeAgentOutput(lines) - return fail(result, "timeout", fmt.Sprintf("structure→scaffold: %v (agent: %s)", err, agentStatus)) - } - - // CDP: verify scaffold phase UI - if cdpErr := verifyCDPPhase("scaffold", pass); cdpErr != "" { - t.Logf("Pass %d CDP warning (scaffold): %s", pass, cdpErr) - } - - // Step 6: Verify scaffold - result.Phase = "scaffold" - result.Check = "scaffold_files" - scaffoldData, code, err := client.get("/api/inception/scaffold") - if err != nil || code != 200 { - return fail(result, "api_error", fmt.Sprintf("scaffold returned %d: %v", code, err)) - } - - scaffold, _ := scaffoldData["scaffold"].(map[string]interface{}) - if scaffold == nil { - return fail(result, "missing_content", "scaffold is nil") - } - files, _ := scaffold["files"].([]interface{}) - if len(files) == 0 { - return fail(result, "missing_content", "scaffold has no files") - } - - // Check each file has content - result.Check = "scaffold_content" - for _, f := range files { - fm := f.(map[string]interface{}) - path, _ := fm["path"].(string) - content, _ := fm["content"].(string) - if content == "" { - return fail(result, "missing_content", fmt.Sprintf("scaffold file %s has empty content", path)) - } - } - - // Check required files exist - result.Check = "required_files" - fileContents := make(map[string]string) - for _, f := range files { - fm := f.(map[string]interface{}) - path, _ := fm["path"].(string) - content, _ := fm["content"].(string) - fileContents[path] = content - } - requiredFiles := []string{"README.md", "AGENTS.md", "CONTRIBUTING.md", ".github/workflows/ci.yml"} - for _, req := range requiredFiles { - if _, ok := fileContents[req]; !ok { - return fail(result, "missing_content", fmt.Sprintf("missing required file: %s", req)) - } - } - - // Verify content is project-specific, not boilerplate - result.Check = "content_quality" - readme := fileContents["README.md"] - if len(readme) < 200 { - return fail(result, "missing_content", fmt.Sprintf("README.md too short (%d chars) — boilerplate, not project-specific", len(readme))) - } - if strings.HasPrefix(strings.TrimSpace(readme), "# Project\n") { - return fail(result, "missing_content", fmt.Sprintf("README.md starts with generic '# Project' — should have project name from vision")) - } - agentsMD := fileContents["AGENTS.md"] - if len(agentsMD) < 200 { - return fail(result, "missing_content", fmt.Sprintf("AGENTS.md too short (%d chars) — should have architecture, requirements, constraints", len(agentsMD))) - } - ciYml := fileContents[".github/workflows/ci.yml"] - if !strings.Contains(ciYml, "steps:") { - return fail(result, "missing_content", "ci.yml missing 'steps:' — likely empty or broken") - } - - // Step 7: Approve - result.Phase = "approve" - result.Check = "approve_ok" - data, code, err = client.post("/api/inception/approve", nil) - if err != nil || code != 200 { - return fail(result, "api_error", fmt.Sprintf("approve returned %d: %v", code, err)) - } - - // Verify complete - result.Check = "phase_complete" - state, err = client.inceptionState() - if err != nil { - return fail(result, "api_error", fmt.Sprintf("final state check: %v", err)) - } - if state == nil || state["phase"] != "complete" { - return fail(result, "assertion", fmt.Sprintf("expected phase=complete, got %v", state)) - } - - // CDP: verify complete phase UI - if cdpErr := verifyCDPPhase("complete", pass); cdpErr != "" { - t.Logf("Pass %d CDP warning (complete): %s", pass, cdpErr) - } - - // Step 8: Check agent output for errors - result.Phase = "agent_health" - result.Check = "no_errors" - lines, _ := client.paneOutput("brainstorm") - for _, line := range lines { - lower := strings.ToLower(line) - if strings.Contains(lower, "panic:") || strings.Contains(lower, "fatal error:") { - return fail(result, "agent_error", fmt.Sprintf("agent output contains error: %s", line)) - } - } - - // All checks passed - result.Status = "pass" - result.Phase = "complete" - result.Check = "all_checks" - return result -} - -func fail(result PassResult, category, errMsg string) PassResult { - result.Status = "fail" - result.Category = category - result.Error = errMsg - return result -} - -func summarizeAgentOutput(lines []string) string { - if len(lines) == 0 { - return "no output" - } - last := lines[len(lines)-1] - if len(last) > 100 { - last = last[:100] - } - return fmt.Sprintf("%d lines, last: %s", len(lines), last) -} diff --git a/src/test/inception_helpers_test.go b/src/test/inception_helpers_test.go deleted file mode 100644 index 0103fdb039..0000000000 --- a/src/test/inception_helpers_test.go +++ /dev/null @@ -1,326 +0,0 @@ -//go:build integration - -// The inception e2e/regression suite talks to a live hive instance over the -// network. It only builds with `-tags integration` so that a plain -// `go test ./...` never blocks on an unreachable endpoint (see issue #4402). -// -// To run it: -// -// HIVE_URL=http://<host>:<port> HIVE_TOKEN=<token> go test -tags integration ./test/... - -package test - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - "os" - "os/exec" - "strings" - "testing" - "time" -) - -var ( - hiveURL = os.Getenv("HIVE_URL") - hiveToken = os.Getenv("HIVE_TOKEN") - cdpURL = envOr("CDP_URL", "ws://127.0.0.1:9222") - screenshotDir = envOr("SCREENSHOT_DIR", "/tmp/inception-e2e") -) - -func envOr(key, fallback string) string { - if v := os.Getenv(key); v != "" { - return v - } - return fallback -} - -// TestMain gates the whole suite: it requires HIVE_URL to be set and the -// endpoint to answer a fast TCP dial. Otherwise the suite is skipped instead -// of every request hanging until the per-package panic timeout. -func TestMain(m *testing.M) { - if hiveURL == "" { - fmt.Println("SKIP: HIVE_URL not set; inception e2e suite requires a live hive endpoint") - os.Exit(0) - } - if err := probeEndpoint(hiveURL, 2*time.Second); err != nil { - fmt.Printf("SKIP: hive endpoint %s unreachable (%v); skipping inception e2e suite\n", hiveURL, err) - os.Exit(0) - } - os.Exit(m.Run()) -} - -// probeEndpoint does a fast TCP dial against the host:port of rawURL. -func probeEndpoint(rawURL string, timeout time.Duration) error { - u, err := url.Parse(rawURL) - if err != nil { - return fmt.Errorf("invalid HIVE_URL: %w", err) - } - host := u.Host - if u.Port() == "" { - switch u.Scheme { - case "https": - host = net.JoinHostPort(u.Hostname(), "443") - default: - host = net.JoinHostPort(u.Hostname(), "80") - } - } - conn, err := net.DialTimeout("tcp", host, timeout) - if err != nil { - return err - } - conn.Close() - return nil -} - -type apiClient struct { - baseURL string - token string - client *http.Client -} - -func newAPIClient() *apiClient { - return &apiClient{ - baseURL: hiveURL, - token: hiveToken, - client: &http.Client{Timeout: 30 * time.Second}, - } -} - -func (c *apiClient) get(path string) (map[string]interface{}, int, error) { - req, err := http.NewRequest("GET", c.baseURL+path, nil) - if err != nil { - return nil, 0, err - } - if c.token != "" { - req.Header.Set("Authorization", "Bearer "+c.token) - } - resp, err := c.client.Do(req) - if err != nil { - return nil, 0, err - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - var result map[string]interface{} - json.Unmarshal(body, &result) - return result, resp.StatusCode, nil -} - -func (c *apiClient) post(path string, payload interface{}) (map[string]interface{}, int, error) { - var bodyReader io.Reader - if payload != nil { - data, err := json.Marshal(payload) - if err != nil { - return nil, 0, err - } - bodyReader = bytes.NewReader(data) - } - req, err := http.NewRequest("POST", c.baseURL+path, bodyReader) - if err != nil { - return nil, 0, err - } - req.Header.Set("Content-Type", "application/json") - if c.token != "" { - req.Header.Set("Authorization", "Bearer "+c.token) - } - resp, err := c.client.Do(req) - if err != nil { - return nil, 0, err - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - var result map[string]interface{} - json.Unmarshal(body, &result) - return result, resp.StatusCode, nil -} - -func (c *apiClient) put(path string, payload interface{}) (map[string]interface{}, int, error) { - var bodyReader io.Reader - if payload != nil { - data, err := json.Marshal(payload) - if err != nil { - return nil, 0, err - } - bodyReader = bytes.NewReader(data) - } - req, err := http.NewRequest("PUT", c.baseURL+path, bodyReader) - if err != nil { - return nil, 0, err - } - req.Header.Set("Content-Type", "application/json") - if c.token != "" { - req.Header.Set("Authorization", "Bearer "+c.token) - } - resp, err := c.client.Do(req) - if err != nil { - return nil, 0, err - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - var result map[string]interface{} - json.Unmarshal(body, &result) - return result, resp.StatusCode, nil -} - -func (c *apiClient) inceptionState() (map[string]interface{}, error) { - data, code, err := c.get("/api/inception/state") - if err != nil { - return nil, err - } - if code != 200 { - return nil, fmt.Errorf("inception state returned %d", code) - } - state, _ := data["state"].(map[string]interface{}) - return state, nil -} - -var phaseOrder = []string{"capture", "clarify", "structure", "scaffold", "complete"} - -func phaseIndex(phase string) int { - for i, p := range phaseOrder { - if p == phase { - return i - } - } - return -1 -} - -func (c *apiClient) waitForPhase(phase string, timeout time.Duration) (map[string]interface{}, error) { - targetIdx := phaseIndex(phase) - deadline := time.Now().Add(timeout) - for time.Now().Before(deadline) { - state, err := c.inceptionState() - if err != nil { - time.Sleep(2 * time.Second) - continue - } - if state != nil { - currentPhase, _ := state["phase"].(string) - currentIdx := phaseIndex(currentPhase) - if currentIdx >= targetIdx { - return state, nil - } - } - time.Sleep(3 * time.Second) - } - state, _ := c.inceptionState() - currentPhase := "nil" - if state != nil { - if p, ok := state["phase"].(string); ok { - currentPhase = p - } - } - return nil, fmt.Errorf("timeout waiting for phase %q (current: %s) after %v", phase, currentPhase, timeout) -} - -func (c *apiClient) paneOutput(agent string) ([]string, error) { - data, code, err := c.get("/api/pane/" + agent) - if err != nil { - return nil, err - } - if code != 200 { - return nil, fmt.Errorf("pane returned %d", code) - } - linesRaw, _ := data["lines"].([]interface{}) - var lines []string - for _, l := range linesRaw { - if s, ok := l.(string); ok { - lines = append(lines, s) - } - } - return lines, nil -} - -func cdpEval(wsURL, expr string) (string, error) { - msg := fmt.Sprintf(`{"id":1,"method":"Runtime.evaluate","params":{"expression":"%s"}}`, strings.ReplaceAll(expr, `"`, `\"`)) - cmd := exec.Command("websocat", "-n1", wsURL) - cmd.Stdin = strings.NewReader(msg) - out, err := cmd.Output() - if err != nil { - return "", fmt.Errorf("websocat: %w", err) - } - var result map[string]interface{} - json.Unmarshal(out, &result) - if r, ok := result["result"].(map[string]interface{}); ok { - if rr, ok := r["result"].(map[string]interface{}); ok { - if v, ok := rr["value"].(string); ok { - return v, nil - } - } - } - return string(out), nil -} - -func cdpScreenshot(wsURL, name string) error { - msg := `{"id":1,"method":"Page.captureScreenshot","params":{"format":"jpeg","quality":70}}` - cmd := exec.Command("websocat", "-n1", "-B", "10000000", wsURL) - cmd.Stdin = strings.NewReader(msg) - out, err := cmd.Output() - if err != nil { - return err - } - var result map[string]interface{} - json.Unmarshal(out, &result) - if r, ok := result["result"].(map[string]interface{}); ok { - if data, ok := r["data"].(string); ok { - return os.WriteFile(fmt.Sprintf("%s/%s.jpg", screenshotDir, name), []byte(data), 0644) - } - } - return fmt.Errorf("no screenshot data in response") -} - -func getCDPWebSocket() string { - resp, err := http.Get(cdpURL + "/json/list") - if err != nil { - return "" - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - var tabs []map[string]interface{} - json.Unmarshal(body, &tabs) - for _, t := range tabs { - if url, ok := t["url"].(string); ok && strings.Contains(url, "3003") { - if ws, ok := t["webSocketDebuggerUrl"].(string); ok { - return ws - } - } - } - return "" -} - -// verifyCDPPhase used to check the dashboard's Inception wizard panel at each -// phase over CDP. The wizard UI was removed (the dashboard's Inception is now -// the Inception (spek) sessions section), so there is no per-phase panel left -// to check; the suite verifies inception through /api/inception/* only. -func verifyCDPPhase(phase string, pass int) string { - return "" -} - -// PassResult records the outcome of a single pass -type PassResult struct { - Pass int `json:"pass"` - Idea string `json:"idea"` - Phase string `json:"phase"` - Check string `json:"check"` - Status string `json:"status"` // "pass" or "fail" - Error string `json:"error,omitempty"` - Category string `json:"category,omitempty"` - Duration string `json:"duration"` - Timestamp time.Time `json:"timestamp"` -} - -func logResult(t *testing.T, result PassResult) { - data, _ := json.Marshal(result) - f, err := os.OpenFile("/tmp/inception-e2e/results.jsonl", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - t.Logf("failed to log result: %v", err) - return - } - defer f.Close() - f.Write(data) - f.WriteString("\n") -} diff --git a/src/test/inception_regression_test.go b/src/test/inception_regression_test.go deleted file mode 100644 index ee33bcf7ef..0000000000 --- a/src/test/inception_regression_test.go +++ /dev/null @@ -1,413 +0,0 @@ -//go:build integration - -package test - -import ( - "strings" - "testing" -) - -// Regression tests added as bugs are found during e2e passes. -// Each test is named TestRegression_PassN_Description. - -func TestRegression_Pass0_EmptyIdeaReturns400(t *testing.T) { - client := newAPIClient() - _, code, _ := client.post("/api/inception/start", map[string]string{"idea": ""}) - if code != 400 { - t.Errorf("empty idea should return 400, got %d", code) - } -} - -func TestRegression_Pass0_ResetWithNoState(t *testing.T) { - client := newAPIClient() - data, code, err := client.post("/api/inception/reset", nil) - if err != nil { - t.Fatalf("reset failed: %v", err) - } - if code != 200 { - t.Errorf("reset with no state should return 200, got %d: %v", code, data) - } -} - -func TestRegression_Pass1_BeadStoreReloadsFromDisk(t *testing.T) { - // The bead store must reload from disk each poll cycle because - // the brainstorm agent writes directly via the bd CLI, not via - // the in-memory store. Without reload, the watcher never sees - // new beads and the phase never advances. - // This is verified by the e2e test: if capture→clarify works, - // the reload is functioning. - client := newAPIClient() - _, code, _ := client.get("/api/inception/state") - if code != 200 { - t.Skipf("hive not reachable, skipping: code=%d", code) - } -} - -func TestRegression_Pass2_WatcherIgnoresOldBeads(t *testing.T) { - // Old inception beads from previous passes must not trigger phase - // advances in the current pass. The watcher must filter by - // bead.CreatedAt >= state.StartedAt. - // This is verified by running multiple consecutive e2e passes — - // if pass 2+ starts in clarify instead of capture, old beads leaked. - client := newAPIClient() - _, code, _ := client.get("/api/inception/state") - if code != 200 { - t.Skipf("hive not reachable, skipping: code=%d", code) - } -} - -func TestRegression_ApproveInCapturePhase(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "test"}) - data, code, _ := client.post("/api/inception/approve", nil) - if code == 200 { - t.Errorf("approve in capture should fail, got 200: %v", data) - } -} - -func TestRegression_DownloadWithNoInception(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - _, code, _ := client.get("/api/inception/download") - if code == 500 { - t.Errorf("download with no inception should return 404, got 500") - } -} - -func TestRegression_ScaffoldReturns404NotState(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - _, code, _ := client.get("/api/inception/scaffold") - if code == 500 { - t.Errorf("scaffold with no state should return 404, got 500") - } - if code != 404 { - t.Logf("scaffold with no state returned %d (expected 404)", code) - } -} - -func TestRegression_ApproveRequiresScaffoldPhase(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "test"}) - data, code, _ := client.post("/api/inception/approve", nil) - if code == 200 { - t.Errorf("approve in capture phase should fail, got 200: %v", data) - } -} - -func TestRegression_Pass0_StateWithNoInception(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - data, code, err := client.get("/api/inception/state") - if err != nil { - t.Fatalf("state check failed: %v", err) - } - if code != 200 { - t.Errorf("state with no inception should return 200, got %d", code) - } - active, _ := data["active"].(bool) - if active { - t.Error("expected active=false when no inception in progress") - } -} - -func TestRegression_Bug39_ConcurrentStartRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - _, code1, _ := client.post("/api/inception/start", map[string]string{"idea": "first idea"}) - if code1 != 200 { - t.Skipf("first start failed: %d", code1) - } - _, code2, _ := client.post("/api/inception/start", map[string]string{"idea": "second idea"}) - if code2 == 200 { - t.Error("concurrent start should be rejected when inception is already in progress") - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug40_InvalidFactTypeRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - _, code, _ := client.post("/api/inception/start", map[string]string{"idea": "test invalid facts"}) - if code != 200 { - t.Skipf("start failed: %d", code) - } - data, code, _ := client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{ - {"type": "invalid_type", "title": "Bad", "body": "Should fail"}, - }, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("RecordFacts should reject invalid fact types") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug41_EmptyFactBodyRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "empty body test"}) - data, code, _ := client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{ - {"type": "vision", "title": "My Vision", "body": ""}, - }, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("RecordFacts should reject facts with empty body") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug42_EmptyFactTitleRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "empty title test"}) - data, code, _ := client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{ - {"type": "requirement", "title": "", "body": "Some body"}, - }, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("RecordFacts should reject facts with empty title") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug44_DuplicateQuestionIDsRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "dupe question test"}) - data, code, _ := client.post("/api/inception/questions", map[string]interface{}{ - "questions": []map[string]string{ - {"id": "q1", "text": "First?", "category": "tech", "default": "a"}, - {"id": "q1", "text": "Duplicate!", "category": "tech", "default": "b"}, - }, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("SetQuestions should reject duplicate question IDs") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug45_WikiNameTooLongRejected(t *testing.T) { - client := newAPIClient() - longName := "" - for i := 0; i < 100; i++ { - longName += "AAAAA" - } - data, code, _ := client.put("/api/inception/wiki-name", map[string]string{"name": longName}) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("wiki rename should reject names > 80 characters") - } - } -} - -func TestRegression_Bug48_PhaseChangedAtOmitsZero(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "timestamp test"}) - data, _, _ := client.get("/api/inception/state") - state, _ := data["state"].(map[string]interface{}) - if state == nil { - t.Skip("no state") - } - pca, exists := state["phase_changed_at"] - if exists && pca == "0001-01-01T00:00:00Z" { - t.Error("phase_changed_at should be omitted when zero, not serialized as year 0001") - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug50_IdeationFactsFallbackToWiki(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "fallback facts test"}) - // Advance to clarify by setting questions - client.post("/api/inception/questions", map[string]interface{}{ - "questions": []map[string]string{ - {"id": "q1", "text": "What language?", "category": "tech", "default": "Go"}, - }, - }) - // Advance to structure by submitting answers - client.post("/api/inception/answer", map[string]interface{}{ - "answers": map[string]string{"q1": "Go"}, - }) - // Now record facts (requires structure phase) - client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{ - {"type": "vision", "title": "Test Vision", "body": "A test project vision statement"}, - }, - }) - data, code, _ := client.get("/api/inception/ideation-facts") - if code != 200 { - t.Skipf("ideation-facts returned %d", code) - } - facts, _ := data["facts"].([]interface{}) - if len(facts) == 0 { - t.Error("ideation-facts should return facts from wiki vault when KB layer is empty") - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug52_StaleWikiFactsClearedOnStart(t *testing.T) { - client := newAPIClient() - // First inception: record facts - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "first project"}) - client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{ - {"type": "vision", "title": "First Vision", "body": "First project description"}, - }, - }) - // Second inception: start new idea - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "second project"}) - // Scaffold should NOT contain facts from first inception - data, code, _ := client.get("/api/inception/scaffold") - if code != 200 { - t.Skipf("scaffold returned %d", code) - } - scaffold, _ := data["scaffold"].(map[string]interface{}) - if scaffold != nil { - files, _ := scaffold["files"].([]interface{}) - for _, f := range files { - fm, _ := f.(map[string]interface{}) - content, _ := fm["content"].(string) - if strings.Contains(content, "First Vision") || strings.Contains(content, "First project") { - t.Error("scaffold contains facts from previous inception — stale wiki not cleared") - } - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug55_EmptyQuestionTextRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "empty text test"}) - data, code, _ := client.post("/api/inception/questions", map[string]interface{}{ - "questions": []map[string]string{ - {"id": "q1", "text": "", "category": "tech", "default": "Go"}, - }, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("SetQuestions should reject questions with empty text") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug56_UnknownAnswerIDRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "unknown id test"}) - client.post("/api/inception/questions", map[string]interface{}{ - "questions": []map[string]string{ - {"id": "q1", "text": "What lang?", "category": "tech", "default": "Go"}, - }, - }) - data, code, _ := client.post("/api/inception/answer", map[string]interface{}{ - "answers": map[string]string{"nonexistent": "value"}, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("SubmitAnswers should reject answer keys that don't match any question ID") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug58_EmptyFactsArrayRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "empty facts test"}) - data, code, _ := client.post("/api/inception/facts", map[string]interface{}{ - "facts": []map[string]string{}, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("RecordFacts should reject empty facts array") - } - } - // Verify phase did NOT advance - stateData, _, _ := client.get("/api/inception/state") - state, _ := stateData["state"].(map[string]interface{}) - if state != nil && state["phase"] == "scaffold" { - t.Error("phase should not advance to scaffold with empty facts") - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug63_WhitespaceIdeaRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - _, code, _ := client.post("/api/inception/start", map[string]string{"idea": " "}) - if code == 200 { - state, _ := client.inceptionState() - if state != nil { - t.Error("whitespace-only idea should be rejected") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug62_ImportOnlyMdFiles(t *testing.T) { - // The import handler should only accept .md files from the zip. - // Non-markdown files (like passwd, .json, .txt) should be skipped. - // This test would need a zip upload which the test client doesn't - // support directly, so we verify via the has-files endpoint. - client := newAPIClient() - _, code, _ := client.get("/api/inception/has-files") - if code != 200 { - t.Skipf("has-files not available: %d", code) - } -} - -func TestRegression_Bug67_EmptyQuestionsRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - client.post("/api/inception/start", map[string]string{"idea": "empty questions test"}) - data, code, _ := client.post("/api/inception/questions", map[string]interface{}{ - "questions": []map[string]string{}, - }) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("SetQuestions should reject empty questions array") - } - } - client.post("/api/inception/reset", nil) -} - -func TestRegression_Bug68_BareStringRepoURLRejected(t *testing.T) { - client := newAPIClient() - client.post("/api/inception/reset", nil) - data, code, _ := client.post("/api/inception/scan", map[string]string{"repo_url": "not-a-url"}) - if code == 200 { - ok, _ := data["ok"].(bool) - if ok { - t.Error("brownfield scan should reject non-URL repo_url") - } - } - client.post("/api/inception/reset", nil) -}