diff --git a/api.go b/api.go index 8e964f8..bbdd068 100644 --- a/api.go +++ b/api.go @@ -237,7 +237,7 @@ func writeJSON(w http.ResponseWriter, code int, v any) { // statusForError maps a DataSource error to an HTTP status code: not-found // sentinels become 404, everything else 500. func statusForError(err error) int { - if errors.Is(err, ErrRunNotFound) || errors.Is(err, ErrJobNotFound) || errors.Is(err, ErrAgentNotFound) || errors.Is(err, ErrPipelineRunNotFound) || errors.Is(err, ErrPipelineNotFound) || errors.Is(err, ErrOrgRoleNotFound) || errors.Is(err, ErrChatThreadNotFound) || errors.Is(err, ErrWorkflowNotFound) { + if errors.Is(err, ErrRunNotFound) || errors.Is(err, ErrJobNotFound) || errors.Is(err, ErrAgentNotFound) || errors.Is(err, ErrPipelineRunNotFound) || errors.Is(err, ErrPipelineNotFound) || errors.Is(err, ErrOrgRoleNotFound) || errors.Is(err, ErrWorkflowNotFound) { return http.StatusNotFound } return http.StatusInternalServerError @@ -890,30 +890,6 @@ func (s *server) handleLearningSkills(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, skills) } -// handleLearningKnowledge serves GET /api/learning/knowledge -> Knowledge, the -// memory brain graph. Mirrors handleRuns; every list is coerced non-nil so the -// client always sees JSON arrays. -func (s *server) handleLearningKnowledge(w http.ResponseWriter, r *http.Request) { - k, err := s.ds.Knowledge(r.Context()) - if err != nil { - http.Error(w, err.Error(), statusForError(err)) - return - } - if k.Agents == nil { - k.Agents = []KnowledgeAgent{} - } - if k.Facts == nil { - k.Facts = []KnowledgeFact{} - } - if k.Clusters == nil { - k.Clusters = []KnowledgeCluster{} - } - if k.Edges == nil { - k.Edges = []KnowledgeEdge{} - } - writeJSON(w, http.StatusOK, k) -} - // handlePipelines serves GET /api/pipelines -> []PipelineSummary, the declared // pipelines with their schedule state and recent run outcomes. Mirrors // handleRuns; the list and every element's Recent are coerced non-nil so the @@ -999,56 +975,6 @@ func (s *server) handlePipelineRun(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, run) } -// handleChatThreads serves GET /api/chat/threads -> []ChatThreadSummary, the -// chat threads with their activity rollups (gitmoot #534). Mirrors handleRuns; -// the list and every element's Participants are coerced non-nil so the client -// always sees JSON arrays. -func (s *server) handleChatThreads(w http.ResponseWriter, r *http.Request) { - threads, err := s.ds.ChatThreads(r.Context()) - if err != nil { - http.Error(w, err.Error(), statusForError(err)) - return - } - if threads == nil { - threads = []ChatThreadSummary{} - } - for i := range threads { - if threads[i].Participants == nil { - threads[i].Participants = []string{} - } - } - writeJSON(w, http.StatusOK, threads) -} - -// handleChatThread serves GET /api/chat/thread?id= -> ChatThreadDetail, one -// thread's summary plus its full message history. Unknown ids map to 404 -// (mirrors handleJob). Messages and Participants are coerced non-nil so the -// client always sees JSON arrays; a message's Refs stays omitempty (optional -// per message), so the client reads it defensively. -func (s *server) handleChatThread(w http.ResponseWriter, r *http.Request) { - id := r.URL.Query().Get("id") - if id == "" { - http.Error(w, "missing thread id", http.StatusBadRequest) - return - } - detail, err := s.ds.ChatThread(r.Context(), id) - if err != nil { - http.Error(w, err.Error(), statusForError(err)) - return - } - if detail == nil { - http.Error(w, ErrChatThreadNotFound.Error(), http.StatusNotFound) - return - } - if detail.Messages == nil { - detail.Messages = []ChatMessage{} - } - if detail.Participants == nil { - detail.Participants = []string{} - } - writeJSON(w, http.StatusOK, detail) -} - // handleAttention serves GET /api/attention -> Attention, the "Needs a human" // view (gitmoot #528). Mirrors handleRuns; every list is coerced non-nil so the // client always sees JSON arrays. diff --git a/api_test.go b/api_test.go index d82285a..9ab21fc 100644 --- a/api_test.go +++ b/api_test.go @@ -1251,24 +1251,6 @@ func TestHandleAgents(t *testing.T) { if registered == 0 { t.Fatalf("registered agents = 0, want > 0") } - - // The MemoryEnabled chip mirrors the agent's config memory switch. The seeded - // fake feed spans both branches: at least one enrolled row and one not, so the - // serialized boolean is exercised in both directions. - byName := map[string]AgentSummary{} - for _, a := range agents { - byName[a.Name] = a - } - if !byName[fakeTemplatedAgent].MemoryEnabled { - t.Fatalf("expected %q to carry MemoryEnabled=true (memory chip)", fakeTemplatedAgent) - } - if byName["ci-runner"].MemoryEnabled { - t.Fatalf("expected ci-runner MemoryEnabled=false (not enrolled)") - } - // A config with memory OFF must still surface MemoryEnabled=false. - if byName["implementer"].MemoryEnabled { - t.Fatalf("expected implementer MemoryEnabled=false (config memory off)") - } } func TestHandleAgent(t *testing.T) { @@ -1292,24 +1274,15 @@ func TestHandleAgent(t *testing.T) { if detail.Template.ID == "" { t.Fatalf("template missing id: %+v", detail.Template) } - // The seeded templated agent carries a config section (memory on) and a - // non-empty memory pool, so the detail's config/memory fields are exercised. + // The seeded templated agent carries an [agents.] config section, so the + // detail's config projection is exercised. if detail.Config == nil { t.Fatalf("expected a config section for %q", fakeTemplatedAgent) } - if !detail.Config.Memory { - t.Fatalf("expected config.memory=true for %q: %+v", fakeTemplatedAgent, detail.Config) - } - if !detail.MemoryEnabled { - t.Fatalf("expected MemoryEnabled=true on the detail's embedded summary") - } // Pool knobs are populated (parse-time defaults are folded in server-side). if detail.Config.MaxBackground == 0 || detail.Config.IdleTimeout == "" || detail.Config.JobTimeout == "" { t.Fatalf("expected config pool knobs populated: %+v", detail.Config) } - if detail.MemoryFacts <= 0 || detail.MemoryObservations <= 0 { - t.Fatalf("expected non-zero memory counts: facts=%d observations=%d", detail.MemoryFacts, detail.MemoryObservations) - } // The per-agent detail carries the template's full prompt body (multi-line). if !strings.Contains(detail.Template.Content, "\n") || !strings.Contains(detail.Template.Content, "Researcher agent") { t.Fatalf("template content missing/not the multi-line prompt body: %q", detail.Template.Content) @@ -1379,45 +1352,10 @@ func TestHandleAgentNoTemplate(t *testing.T) { if len(detail.Versions) != 0 { t.Fatalf("len(Versions) = %d, want 0 for a template-less agent", len(detail.Versions)) } - // ci-runner has neither a config section nor an enrolled memory pool, so its - // detail omits Config entirely and reports zero memory counts. + // ci-runner has no [agents.] section, so its detail omits Config entirely. if detail.Config != nil { t.Fatalf("expected nil config for ci-runner (no config section): %+v", detail.Config) } - if detail.MemoryEnabled { - t.Fatalf("expected MemoryEnabled=false for ci-runner") - } - if detail.MemoryFacts != 0 || detail.MemoryObservations != 0 { - t.Fatalf("expected zero memory counts for ci-runner: facts=%d observations=%d", detail.MemoryFacts, detail.MemoryObservations) - } -} - -// TestHandleAgentMemoryWithConfig covers the branch where a memory-enrolled agent -// (MemoryEnabled chip + a non-empty pool) carries its [agents.] config -// section. This mirrors the live webDataSource, which sets MemoryEnabled and -// Config together in one comma-ok block, so memory-on always implies a non-nil -// config — the fake feed must not present a memory-on/no-config state the real -// backend can never emit. -func TestHandleAgentMemoryWithConfig(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - var detail AgentDetail - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/agent/reviewer-kimi"), &detail); err != nil { - t.Fatalf("decode: %v", err) - } - if !detail.MemoryEnabled { - t.Fatalf("expected reviewer-kimi MemoryEnabled=true") - } - if detail.Config == nil { - t.Fatalf("expected non-nil config for reviewer-kimi (enrolled agents always carry a config section)") - } - if !detail.Config.Memory { - t.Fatalf("expected reviewer-kimi config memory on: %+v", detail.Config) - } - if detail.MemoryFacts <= 0 || detail.MemoryObservations <= 0 { - t.Fatalf("expected non-zero memory counts: facts=%d observations=%d", detail.MemoryFacts, detail.MemoryObservations) - } } func TestHandleAgentNotFound(t *testing.T) { @@ -1908,20 +1846,10 @@ func TestHandleConfig(t *testing.T) { kind string isDefault bool }{ - "chat.auto_respond": {"false", "false", "flag", true}, - "github.rate_limit_per_hour": {"4200", "4500", "int", false}, - "memory.cluster_depth_cap": {"3", "3", "int", true}, - "memory.cluster_fanout": {"6", "6", "int", true}, - "memory.distill_enabled": {"false", "false", "flag", true}, - "memory.groom_split_llm": {"true", "false", "flag", false}, - "memory.groom_split_max_per_run": {"8", "4", "int", false}, - "memory.groom_split_model": {`"gpt-5.6-sol"`, `""`, "string", false}, - "memory.groom_split_runtime": {`"codex"`, `"codex"`, "string", true}, - "memory.max_entries": {"1200", "1000", "int", false}, - "memory.token_budget": {"12000", "12000", "int", true}, - "orchestrate.blocked_ttl": {`"30m"`, `"30m"`, "duration", true}, - "skillopt.auto_promote": {"false", "false", "flag", true}, - "skillopt.pace_gate": {"true", "true", "flag", true}, + "github.rate_limit_per_hour": {"4200", "4500", "int", false}, + "orchestrate.blocked_ttl": {`"30m"`, `"30m"`, "duration", true}, + "skillopt.auto_promote": {"false", "false", "flag", true}, + "skillopt.pace_gate": {"true", "true", "flag", true}, } gotKnobs := map[string]bool{} for si, section := range cfg.Sections { @@ -2300,316 +2228,6 @@ func TestHandleLearningSkillsDeterministic(t *testing.T) { } } -func TestHandleLearningKnowledge(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - var k Knowledge - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/learning/knowledge"), &k); err != nil { - t.Fatalf("decode: %v", err) - } - if k.Agents == nil || k.Facts == nil || k.Clusters == nil || k.Edges == nil { - t.Fatalf("knowledge slices must be non-nil: %+v", k) - } - - // Exactly three enrolled agents; every agent is enrolled and named. - agentNames := map[string]bool{} - enrolled := 0 - for _, a := range k.Agents { - if a.Name == "" { - t.Fatalf("knowledge agent missing name: %+v", a) - } - agentNames[a.Name] = true - if a.Enrolled { - enrolled++ - } - } - if enrolled != 3 { - t.Fatalf("enrolled agents = %d, want 3", enrolled) - } - // Agents sorted by name asc. - for i := 1; i < len(k.Agents); i++ { - if k.Agents[i-1].Name > k.Agents[i].Name { - t.Fatalf("agents not name-sorted: %+v", k.Agents) - } - } - - // Facts: enough to fill the graph, witnesses within 1..7, two superseded - // facts, facts span more than one repo scope plus a general scope. - if len(k.Facts) < 8 { - t.Fatalf("len(Facts) = %d, want >= 8", len(k.Facts)) - } - factIDs := map[string]bool{} - superseded, generalScope := 0, 0 - repoUnclusteredGhost := "" - repos := map[string]bool{} - for _, fct := range k.Facts { - if fct.ID == "" || fct.Content == "" || fct.Owner == "" { - t.Fatalf("fact missing id/content/owner: %+v", fct) - } - if !agentNames[fct.Owner] { - t.Fatalf("fact %s owner %q is not an enrolled agent", fct.ID, fct.Owner) - } - if fct.Witnesses < 1 || fct.Witnesses > 7 { - t.Fatalf("fact %s witnesses = %d, want 1..7", fct.ID, fct.Witnesses) - } - factIDs[fct.ID] = true - if fct.Superseded { - superseded++ - if fct.Repo != "" && fct.Cluster == "" { - repoUnclusteredGhost = fct.ID - } - } - if fct.Repo == "" { - generalScope++ - } else { - repos[fct.Repo] = true - } - } - if superseded != 2 { - t.Fatalf("superseded facts = %d, want exactly 2", superseded) - } - if repoUnclusteredGhost == "" { - t.Fatal("fixture missing repo-scoped superseded fact without a cluster") - } - if len(repos) < 2 { - t.Fatalf("repo-scoped facts span %d repos, want >= 2", len(repos)) - } - if generalScope < 2 { - t.Fatalf("general-scope facts = %d, want >= 2", generalScope) - } - - // Edges: only the three real kinds, at least one of each; owner/category - // sources and supersede endpoints reference known facts; owner targets are - // enrolled agents. - // Clusters (gitmoot #763, #779): every cluster has an id/label and a positive - // count. Leaf counts match direct fact assignments; parent counts aggregate - // their children. Facts always attach to leaves and parent ids are valid. - clusterIDs := map[string]bool{} - clusterMembers := map[string]int{} - clusterByID := map[string]KnowledgeCluster{} - childrenByParent := map[string][]string{} - if len(k.Clusters) == 0 { - t.Fatalf("expected >=1 cluster, got 0") - } - for _, c := range k.Clusters { - if c.ID == "" || c.Label == "" { - t.Fatalf("cluster missing id/label: %+v", c) - } - if clusterIDs[c.ID] { - t.Fatalf("duplicate cluster id %q", c.ID) - } - clusterIDs[c.ID] = true - clusterByID[c.ID] = c - if c.ParentID != "" { - childrenByParent[c.ParentID] = append(childrenByParent[c.ParentID], c.ID) - } - } - for _, c := range k.Clusters { - if c.ParentID != "" && !clusterIDs[c.ParentID] { - t.Fatalf("cluster %s parent_id %q is not a known cluster", c.ID, c.ParentID) - } - } - clusterOf := map[string]string{} - for _, fct := range k.Facts { - if fct.Cluster == "" { - continue - } - if !clusterIDs[fct.Cluster] { - t.Fatalf("fact %s cluster %q is not a known cluster", fct.ID, fct.Cluster) - } - clusterMembers[fct.Cluster]++ - clusterOf[fct.ID] = fct.Cluster - if len(childrenByParent[fct.Cluster]) != 0 { - t.Fatalf("fact %s attaches to parent cluster %q, want a leaf", fct.ID, fct.Cluster) - } - // Provenance is one of source job / source file, never both. - if fct.SourceJob != "" && fct.SourceFile != "" { - t.Fatalf("fact %s carries both sourceJob and sourceFile", fct.ID) - } - // Linked fact ids must reference known facts (no dangling wikilinks). - for _, id := range fct.Links { - if !factIDs[id] { - t.Fatalf("fact %s links to unknown fact %q", fct.ID, id) - } - } - } - var subtreeMembers func(string, map[string]bool) int - subtreeMembers = func(id string, seen map[string]bool) int { - if seen[id] { - return 0 - } - seen[id] = true - total := clusterMembers[id] - for _, childID := range childrenByParent[id] { - total += subtreeMembers(childID, seen) - } - return total - } - for _, c := range k.Clusters { - want := subtreeMembers(c.ID, map[string]bool{}) - if c.Count != want { - t.Fatalf("cluster %s count = %d, want recursive hierarchy member total %d", c.ID, c.Count, want) - } - if c.Count <= 0 { - t.Fatalf("cluster %s has non-positive count %d", c.ID, c.Count) - } - if c.Medoid != "" { - medoidCluster := clusterOf[c.Medoid] - cur, found := medoidCluster, medoidCluster == c.ID - for steps := 0; !found && cur != "" && steps <= len(k.Clusters); steps++ { - cur = clusterByID[cur].ParentID - found = cur == c.ID - } - if !found { - t.Fatalf("cluster %s medoid %q is not one of its descendant facts", c.ID, c.Medoid) - } - } - } - if got := len(childrenByParent["cluster:4"]); got != 2 { - t.Fatalf("cluster:4 children = %d, want 2", got) - } - if clusterByID["cluster:3:delivery:build"].ParentID != "cluster:3:delivery" || clusterByID["cluster:3:delivery"].ParentID != "cluster:3" { - t.Fatalf("default fixture missing depth-three chain: %+v", clusterByID) - } - // Clusters sorted by id asc (deterministic ordering for the sig-skip). - for i := 1; i < len(k.Clusters); i++ { - if k.Clusters[i-1].ID > k.Clusters[i].ID { - t.Fatalf("clusters not id-sorted: %+v", k.Clusters) - } - } - - // Edges: the five real kinds, at least one of each; owner/category/cluster - // sources and supersede endpoints reference known facts; owner targets are - // enrolled agents; cluster targets are known clusters. Link edges are scored - // undirected fact pairs emitted exactly once. - kinds := map[string]int{} - linkPairs := map[string]bool{} - crossRepoLinks := 0 - ghostSupersede := false - for _, e := range k.Edges { - switch e.Kind { - case "owner", "category", "cluster", "supersede", "link": - default: - t.Fatalf("edge has unexpected kind %q: %+v", e.Kind, e) - } - kinds[e.Kind]++ - if !factIDs[e.Source] { - t.Fatalf("edge source %q is not a known fact", e.Source) - } - switch e.Kind { - case "owner": - if !agentNames[e.Target] { - t.Fatalf("owner edge target %q is not an enrolled agent", e.Target) - } - case "cluster": - if !clusterIDs[e.Target] { - t.Fatalf("cluster edge target %q is not a known cluster", e.Target) - } - case "supersede": - if !factIDs[e.Target] { - t.Fatalf("supersede edge target %q is not a known fact", e.Target) - } - if e.Target == repoUnclusteredGhost { - ghostSupersede = true - } - case "link": - if !factIDs[e.Target] { - t.Fatalf("link edge target %q is not a known fact", e.Target) - } - if e.Score <= 0 || e.Score > 1 { - t.Fatalf("link edge score = %v, want (0,1]: %+v", e.Score, e) - } - a, b := e.Source, e.Target - if a > b { - a, b = b, a - } - pair := a + "|" + b - if linkPairs[pair] { - t.Fatalf("duplicate undirected link pair %q", pair) - } - linkPairs[pair] = true - var sourceRepo, targetRepo string - for _, fact := range k.Facts { - if fact.ID == e.Source { - sourceRepo = fact.Repo - } - if fact.ID == e.Target { - targetRepo = fact.Repo - } - } - if sourceRepo != targetRepo { - crossRepoLinks++ - } - } - } - for _, kind := range []string{"owner", "category", "cluster", "supersede", "link"} { - if kinds[kind] == 0 { - t.Fatalf("expected at least one %q edge: %+v", kind, kinds) - } - } - if crossRepoLinks == 0 { - t.Fatal("expected at least one cross-repo link edge") - } - if !ghostSupersede { - t.Fatalf("expected supersede edge targeting repo-scoped unclustered ghost %q", repoUnclusteredGhost) - } - // One owner + one category edge per fact; one cluster edge per clustered fact. - if kinds["owner"] != len(k.Facts) { - t.Fatalf("owner edges = %d, want one per fact (%d)", kinds["owner"], len(k.Facts)) - } - if kinds["category"] != len(k.Facts) { - t.Fatalf("category edges = %d, want one per fact (%d)", kinds["category"], len(k.Facts)) - } - clustered := 0 - for _, fct := range k.Facts { - if fct.Cluster != "" { - clustered++ - } - } - if kinds["cluster"] != clustered { - t.Fatalf("cluster edges = %d, want one per clustered fact (%d)", kinds["cluster"], clustered) - } -} - -func TestHandleLearningKnowledgeFlatFixture(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSourceFlatKnowledge())) - defer srv.Close() - - var k Knowledge - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/learning/knowledge"), &k); err != nil { - t.Fatalf("decode: %v", err) - } - if len(k.Clusters) != 7 { - t.Fatalf("base fixture clusters = %d, want 7", len(k.Clusters)) - } - byID := map[string]KnowledgeCluster{} - for _, c := range k.Clusters { - byID[c.ID] = c - } - if byID["cluster:3:delivery:build"].ParentID != "cluster:3:delivery" || byID["cluster:3:delivery"].ParentID != "cluster:3" { - t.Fatalf("base fixture missing depth-three chain: %+v", byID) - } - if byID["cluster:4"].ParentID != "" { - t.Fatalf("base fixture unexpectedly carries the default cluster:4 split: %+v", byID["cluster:4"]) - } - for _, fct := range k.Facts { - if fct.ID == "fact:4" && fct.Cluster != "cluster:4" { - t.Fatalf("flat fixture fact:4 cluster = %q, want cluster:4", fct.Cluster) - } - } -} - -func TestHandleLearningKnowledgeDeterministic(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - url := srv.URL + "/api/learning/knowledge" - if a, b := getRaw(t, url), getRaw(t, url); !bytes.Equal(a, b) { - t.Fatalf("knowledge not byte-stable across calls\nfirst: %s\nsecond: %s", a, b) - } -} - // realPipelineStates is the set of run states the live pipeline store can emit; // the fake feed must never present a run state outside it. var realPipelineStates = map[string]bool{ @@ -3225,185 +2843,3 @@ func TestStateResponseIsIndented(t *testing.T) { t.Fatalf("expected indented JSON, got: %q", string(buf[:n])) } } - -// realChatMessageKinds is the set of message kinds the live chat store can emit; -// the fake feed must not invent shapes the client will not otherwise see. -var realChatMessageKinds = map[string]bool{ - "chat": true, - "system": true, - "job_result": true, - "promotion_request": true, -} - -var realChatAuthorKinds = map[string]bool{ - "human": true, - "agent": true, - "system": true, -} - -func TestHandleChatThreads(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - var threads []ChatThreadSummary - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/chat/threads"), &threads); err != nil { - t.Fatalf("decode: %v", err) - } - if len(threads) < 3 { - t.Fatalf("len(threads) = %d, want >= 3", len(threads)) - } - - // Sorted most-recently-active first (UpdatedAt desc). - for i := 1; i < len(threads); i++ { - if threads[i-1].UpdatedAt < threads[i].UpdatedAt { - t.Fatalf("threads not UpdatedAt-desc sorted: %+v", threads) - } - } - - var haveOpen, haveArchived, haveUnread bool - for _, th := range threads { - if th.ID == "" || th.Name == "" { - t.Fatalf("thread missing id/name: %+v", th) - } - if th.State != "open" && th.State != "archived" { - t.Fatalf("thread %q has unexpected state %q", th.ID, th.State) - } - if th.State == "open" { - haveOpen = true - } - if th.State == "archived" { - haveArchived = true - } - if th.UnreadMentions > 0 { - haveUnread = true - } - if th.MessageCount <= 0 { - t.Fatalf("thread %q has non-positive messageCount %d", th.ID, th.MessageCount) - } - if th.LastKind != "" && !realChatMessageKinds[th.LastKind] { - t.Fatalf("thread %q has unexpected lastKind %q", th.ID, th.LastKind) - } - if th.Participants == nil { - t.Fatalf("thread %q participants is nil (want [])", th.ID) - } - } - if !haveOpen || !haveArchived || !haveUnread { - t.Fatalf("fixture must cover open+archived+unread; got open=%v archived=%v unread=%v", haveOpen, haveArchived, haveUnread) - } -} - -func TestHandleChatThreadsDeterministic(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - url := srv.URL + "/api/chat/threads" - if a, b := getRaw(t, url), getRaw(t, url); !bytes.Equal(a, b) { - t.Fatalf("chat threads not byte-stable across calls\nfirst: %s\nsecond: %s", a, b) - } -} - -func TestHandleChatThread(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - // The release-room fixture exercises a promotion_request + job_result + refs. - var detail ChatThreadDetail - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/chat/thread?id=chat-release-room"), &detail); err != nil { - t.Fatalf("decode: %v", err) - } - if detail.ID != "chat-release-room" { - t.Fatalf("detail.ID = %q, want chat-release-room", detail.ID) - } - if len(detail.Messages) == 0 { - t.Fatalf("thread has no messages") - } - // Messages ascending by Seq; kinds/author-kinds within the real store's set. - var sawPromotion, sawJobResult bool - for i, msg := range detail.Messages { - if i > 0 && detail.Messages[i-1].Seq > msg.Seq { - t.Fatalf("messages not Seq-ascending: %+v", detail.Messages) - } - if !realChatMessageKinds[msg.Kind] { - t.Fatalf("message %q has unexpected kind %q", msg.ID, msg.Kind) - } - if !realChatAuthorKinds[msg.AuthorKind] { - t.Fatalf("message %q has unexpected authorKind %q", msg.ID, msg.AuthorKind) - } - if msg.Kind == "promotion_request" { - sawPromotion = true - if msg.PromotedJobID == "" { - t.Fatalf("promotion_request %q missing promotedJobId", msg.ID) - } - } - if msg.Kind == "job_result" { - sawJobResult = true - } - } - if !sawPromotion || !sawJobResult { - t.Fatalf("release-room must carry a promotion_request + job_result; got promotion=%v jobResult=%v", sawPromotion, sawJobResult) - } -} - -func TestHandleChatThreadSystemAskGate(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - // The adapter-review fixture exercises an ask-gate `system` message + a - // human reply_to answer. - var detail ChatThreadDetail - if err := json.Unmarshal(getRaw(t, srv.URL+"/api/chat/thread?id=chat-adapter-review"), &detail); err != nil { - t.Fatalf("decode: %v", err) - } - var sawSystem, sawReply bool - for _, msg := range detail.Messages { - if msg.Kind == "system" && msg.AuthorKind == "system" { - sawSystem = true - } - if msg.ReplyTo != "" { - sawReply = true - } - } - if !sawSystem || !sawReply { - t.Fatalf("adapter-review must carry a system ask-gate + a reply; got system=%v reply=%v", sawSystem, sawReply) - } -} - -func TestHandleChatThreadDeterministic(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - url := srv.URL + "/api/chat/thread?id=chat-release-room" - if a, b := getRaw(t, url), getRaw(t, url); !bytes.Equal(a, b) { - t.Fatalf("chat thread not byte-stable across calls\nfirst: %s\nsecond: %s", a, b) - } -} - -func TestHandleChatThreadNotFound(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - resp, err := http.Get(srv.URL + "/api/chat/thread?id=does-not-exist") - if err != nil { - t.Fatalf("GET /api/chat/thread?id=does-not-exist: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusNotFound { - t.Fatalf("status = %d, want 404", resp.StatusCode) - } -} - -func TestHandleChatThreadMissingID(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - resp, err := http.Get(srv.URL + "/api/chat/thread") - if err != nil { - t.Fatalf("GET /api/chat/thread: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusBadRequest { - t.Fatalf("status = %d, want 400", resp.StatusCode) - } -} diff --git a/cmd/gitmoot-dashboard-dev/main.go b/cmd/gitmoot-dashboard-dev/main.go index d5374c3..1b55353 100644 --- a/cmd/gitmoot-dashboard-dev/main.go +++ b/cmd/gitmoot-dashboard-dev/main.go @@ -12,14 +12,9 @@ import ( func main() { addr := flag.String("addr", ":8099", "HTTP listen address") - flatKnowledge := flag.Bool("knowledge-flat", false, "serve the no-parent Knowledge fixture") flag.Parse() - ds := dashboard.NewFakeDataSource() - if *flatKnowledge { - ds = dashboard.NewFakeDataSourceFlatKnowledge() - } - handler := dashboard.Serve(ds) - log.Printf("gitmoot-dashboard-dev listening on %s (knowledge-flat=%t)", *addr, *flatKnowledge) + handler := dashboard.Serve(dashboard.NewFakeDataSource()) + log.Printf("gitmoot-dashboard-dev listening on %s", *addr) if err := http.ListenAndServe(*addr, handler); err != nil { log.Fatal(err) } diff --git a/datasource.go b/datasource.go index d01568d..d2376a7 100644 --- a/datasource.go +++ b/datasource.go @@ -111,9 +111,6 @@ type AgentSummary struct { Capabilities []string `json:"capabilities,omitempty"` AutonomyPolicy string `json:"autonomyPolicy,omitempty"` Health string `json:"health,omitempty"` - // MemoryEnabled is true when the agent's [agents.] config section turns - // the memory feature on; the Agents page renders a small "memory" chip for it. - MemoryEnabled bool `json:"memoryEnabled,omitempty"` // Ephemeral is true only for the synthetic ephemeral-workers rollup row. Ephemeral bool `json:"ephemeral,omitempty"` JobCount int `json:"jobCount"` @@ -164,7 +161,6 @@ type AgentTemplateInfo struct { // workers gitmoot spins up for this agent, so they do not describe a one-off // foreground invocation. type AgentConfigInfo struct { - Memory bool `json:"memory"` MaxBackground int `json:"maxBackground,omitempty"` IdleTimeout string `json:"idleTimeout,omitempty"` JobTimeout string `json:"jobTimeout,omitempty"` @@ -183,11 +179,6 @@ type AgentDetail struct { // Config is the agent's [agents.] config section, or nil when the agent // has no such section. Config *AgentConfigInfo `json:"config,omitempty"` - // MemoryFacts is the count of confirmed_memories rows owned by this agent - // (across all owner versions). - MemoryFacts int `json:"memoryFacts"` - // MemoryObservations is the count of memory_observations rows owned by this agent. - MemoryObservations int `json:"memoryObservations"` } // GraphNode is a node in the whole-history "galaxy" graph. Type is "job" (a real @@ -742,14 +733,12 @@ type ConfigSection struct { // ConfigAgent is the sanitized per-agent behavior visible in config.toml. // Credentials, environment and template contents are intentionally absent. type ConfigAgent struct { - Name string `json:"name"` - Runtime string `json:"runtime"` - Model string `json:"model"` - Memory bool `json:"memory"` - ChatAutorespond bool `json:"chat_autorespond"` - Capabilities []string `json:"capabilities"` - AutonomyPolicy string `json:"autonomy_policy"` - MaxBackground int `json:"max_background"` + Name string `json:"name"` + Runtime string `json:"runtime"` + Model string `json:"model"` + Capabilities []string `json:"capabilities"` + AutonomyPolicy string `json:"autonomy_policy"` + MaxBackground int `json:"max_background"` } // KeychainView is the metadata-only registry projection shown on the Config @@ -925,93 +914,6 @@ type Skills struct { PendingTotal int `json:"pendingTotal"` } -// Knowledge — the memory brain graph. - -// KnowledgeAgent is one memory-enrolled agent hub in the brain graph, with the -// size of its confirmed-fact / observation pool. -type KnowledgeAgent struct { - Name string `json:"name"` - Enrolled bool `json:"enrolled"` - Facts int `json:"facts"` - Observations int `json:"observations"` -} - -// KnowledgeCluster is an emergent memory cluster (Knowledge graph v2, gitmoot -// #763): a community of similar facts derived deterministically over the -// fact-similarity graph (the same FTS/bm25 signal that seeds vault [[links]]). -// The same DB yields byte-identical clusters, matching the vault byte-identity -// house rule. Label is the display label (an owner override wins server-side, -// so the client renders Label verbatim); Count is the number of member facts; -// Repo is the cluster's dominant repo scope ("" = general/mixed) so the client -// can nest repo -> cluster -> fact; Medoid anchors the label to a representative -// fact for stability across recomputes. ParentID is additive hierarchy metadata: -// facts attach to leaf clusters, while every ancestor aggregates its descendants. -// -// Additive contract: Track A (the gitmoot bridge) fills this. A gitmoot build -// that predates clusters simply omits the enclosing Clusters slice and leaves -// each fact's Cluster empty, so the client falls back to its pre-cluster view. -type KnowledgeCluster struct { - ID string `json:"id"` // stable unique id (e.g. "cluster:") - Label string `json:"label"` // display label (owner override wins server-side) - Count int `json:"count"` // direct member count for leaves; aggregate for parents - Repo string `json:"repo,omitempty"` // dominant repo scope, "" = general/mixed - Medoid string `json:"medoid,omitempty"` // anchor fact id (label stability) - ParentID string `json:"parent_id,omitempty"` // parent cluster id; empty for top-level clusters -} - -// KnowledgeFact is a single confirmed memory. Repo scopes the fact ("" = general -// scope); Superseded marks a fact replaced by a newer one on the same key. -// -// The Cluster/SourceJob/SourceFile/Links fields back the Knowledge graph v2 -// detail panel (gitmoot #763) and are all additive + optional: a pre-cluster -// gitmoot build leaves them empty and the client degrades gracefully. -// Created/updated are already carried by FirstSeen/LastSeen. -type KnowledgeFact struct { - ID string `json:"id"` // stable unique id (e.g. "fact:") - Content string `json:"content"` - Repo string `json:"repo,omitempty"` // "" = general scope - Key string `json:"key,omitempty"` - Owner string `json:"owner"` // agent name - Witnesses int `json:"witnesses"` - FirstSeen int64 `json:"firstSeen,omitempty"` - LastSeen int64 `json:"lastSeen,omitempty"` - Superseded bool `json:"superseded,omitempty"` - // Cluster is the id of the fact's owning KnowledgeCluster ("" = unclustered). - Cluster string `json:"cluster,omitempty"` - // SourceJob is the job id the fact was learned from (provenance). - SourceJob string `json:"sourceJob,omitempty"` - // SourceFile is the file the fact was ingested from (provenance). - SourceFile string `json:"sourceFile,omitempty"` - // Links are the ids of facts this fact references (the vault [[wikilinks]]), - // rendered as clickable cross-references in the detail panel. - Links []string `json:"links,omitempty"` -} - -// KnowledgeEdge is one edge in the brain graph: a fact to its owner agent -// (owner), a fact to its category/scope hub (category), a fact to its emergent -// cluster hub (cluster, gitmoot #763), a newer fact to the older fact it -// supersedes (supersede), or an undirected fact-to-fact wiki link (link). Link -// edges are emitted once per pair and carry a score in (0,1]. -type KnowledgeEdge struct { - Source string `json:"source"` - Target string `json:"target"` - Kind string `json:"kind"` // owner | category | cluster | supersede | link - Score float64 `json:"score,omitempty"` -} - -// Knowledge is the data behind the Learning page's Knowledge view: the memory -// brain graph of enrolled agents, their facts, the emergent clusters those -// facts belong to (gitmoot #763) and the edges between them. -type Knowledge struct { - Agents []KnowledgeAgent `json:"agents"` - Facts []KnowledgeFact `json:"facts"` - // Clusters are the emergent memory clusters (gitmoot #763). Additive: a - // pre-cluster gitmoot build leaves this empty and the client falls back to - // its scope/category view. - Clusters []KnowledgeCluster `json:"clusters"` - Edges []KnowledgeEdge `json:"edges"` -} - // Pipelines — the declared shell-stage pipelines (gitmoot #681). // PipelineSummary is one row of the Pipelines list: a declared pipeline @@ -1154,66 +1056,6 @@ type PipelineKeyEntry struct { Mode string `json:"mode"` } -// Chat — the Gitmoot-native agent chat layer (gitmoot #534): durable, -// repo-scoped coordination threads where agents and humans exchange messages, -// tag each other, and promote messages into real jobs. - -// ChatRef is a structured reference carried by a chat message: a link to a -// Gitmoot entity (a job, PR, artifact, repo, …). Kind names the entity type; -// URL, when present and http(s), is a safe external link the client can render. -type ChatRef struct { - Kind string `json:"kind"` // job | pr | artifact | repo | thread | … - Repo string `json:"repo,omitempty"` // owning repo, when scoped - ID string `json:"id"` // the entity id (job id, PR number, …) - URL string `json:"url,omitempty"` // external link, when the entity has one -} - -// ChatMessage is one durable message in a thread. Body is untrusted, -// agent/human-authored markdown-ish plain text and MUST be escaped by any -// renderer. Kind drives how the client styles the message: chat (a normal -// message), system (an ask-gate question from a paused job), job_result (an -// agent's job result posted back), or promotion_request (a message that spawned -// a job — see PromotedJobID). -type ChatMessage struct { - ID string `json:"id"` - Seq int `json:"seq"` // 1-based per-thread ordering key - TsMs int64 `json:"tsMs"` // epoch milliseconds - AuthorKind string `json:"authorKind"` // human | agent | system - AuthorName string `json:"authorName"` // agent/human name (empty for system) - Kind string `json:"kind"` // chat | system | job_result | promotion_request - Body string `json:"body"` // UNTRUSTED markdown-ish text — escape everything - Refs []ChatRef `json:"refs,omitempty"` // structured entity references - ReplyTo string `json:"replyTo,omitempty"` // id of the message this replies to - PromotedJobID string `json:"promotedJobId,omitempty"` // set on promotion_request: the job it spawned -} - -// ChatThreadSummary is one row of the Chat threads list: a repo-scoped -// coordination ledger plus a rollup of its activity (message count, unread -// mentions, and a server-truncated preview of the last message) so the list can -// render without fetching each thread's full history. -type ChatThreadSummary struct { - ID string `json:"id"` - Slug string `json:"slug,omitempty"` - Name string `json:"name"` - Repo string `json:"repo,omitempty"` - State string `json:"state"` // open | archived - CreatedBy string `json:"createdBy,omitempty"` - UpdatedAt int64 `json:"updatedAt,omitempty"` // epoch ms of the last activity - MessageCount int `json:"messageCount"` - UnreadMentions int `json:"unreadMentions"` // pending @mentions across enrolled agents - LastAuthor string `json:"lastAuthor,omitempty"` // author of the most recent message - LastKind string `json:"lastKind,omitempty"` // kind of the most recent message - LastSnippet string `json:"lastSnippet,omitempty"` // server-truncated preview of the last message body - Participants []string `json:"participants,omitempty"` // enrolled agents/humans, sorted -} - -// ChatThreadDetail is the click-through detail for one thread: its summary plus -// the full message history (ascending by Seq). -type ChatThreadDetail struct { - ChatThreadSummary - Messages []ChatMessage `json:"messages"` // ascending by Seq; never nil -} - // Attention + binary checks — surfacing evaluator output and human gates where a // human (or the planned Slack/media bridge, gitmoot #519) manages work // (gitmoot #528). @@ -1351,20 +1193,17 @@ type DataSource interface { // by name only, and the keychain projection contains metadata only. Sections, // knobs, agents, unknown keys and keychain rows are deterministic. Config(ctx context.Context) (ConfigSnapshot, error) - // Skills returns the SkillOpt evolution overview behind the Learning page's + // Skills returns the template evolution overview behind the Learning page's // Skills view: per-template version history, active canaries and pending // candidates. Ordering must be deterministic (the UI polls with a // signature-skip): templates pending-first then most-recently-promoted, each // template's versions ascending by Number. + // + // Skills is REQUIRED (gitmoot #2206) while Knowledge and ChatThreads left this + // interface: gitmoot serves Skills from its surviving agent-template tables, so + // the page renders real data, whereas Knowledge and Chat were backed by tables + // gitmoot retired and could only ever answer empty. Skills(ctx context.Context) (Skills, error) - // Knowledge returns the memory brain graph behind the Learning page's - // Knowledge view: enrolled agents, their facts, the emergent clusters those - // facts belong to (gitmoot #763) and the owner/category/cluster/supersede - // edges between them. Clusters are additive — a pre-cluster gitmoot build - // returns an empty Clusters slice and empty per-fact Cluster fields, and the - // client falls back to its scope/category view. Ordering must be - // deterministic (the UI polls with a signature-skip). - Knowledge(ctx context.Context) (Knowledge, error) // Pipelines returns every declared pipeline with its schedule state and recent // run outcomes (newest-first, capped at 10), sorted by name. Ordering must be // deterministic (the UI polls with a signature-skip). @@ -1377,15 +1216,6 @@ type DataSource interface { // return ErrPipelineNotFound. Ordering must be deterministic (the UI polls with // a signature-skip). PipelineDetail(ctx context.Context, name string) (PipelineDetail, error) - // ChatThreads returns every chat thread (gitmoot #534) with its activity - // rollup, sorted most-recently-active first (UpdatedAt desc, id desc - // tie-break). Ordering must be deterministic (the UI polls with a - // signature-skip). - ChatThreads(ctx context.Context) ([]ChatThreadSummary, error) - // ChatThread returns one thread's detail by id: its summary plus the full - // message history (ascending by Seq). Unknown ids return - // (nil, ErrChatThreadNotFound). Output must be deterministic. - ChatThread(ctx context.Context, id string) (*ChatThreadDetail, error) // Attention returns the "Needs a human" view (gitmoot #528): blocked job // gates, pending synth approvals and template candidates awaiting promotion. // Ordering must be deterministic (the UI polls with a signature-skip). diff --git a/fakefeed.go b/fakefeed.go index a84fa4f..182bd92 100644 --- a/fakefeed.go +++ b/fakefeed.go @@ -26,8 +26,6 @@ var ( ErrPipelineNotFound = errors.New("pipeline not found") // ErrOrgRoleNotFound indicates the requested org role does not exist. ErrOrgRoleNotFound = errors.New("org role not found") - // ErrChatThreadNotFound indicates the requested chat thread does not exist. - ErrChatThreadNotFound = errors.New("chat thread not found") // ErrWorkflowNotFound indicates the requested workflow label does not exist. ErrWorkflowNotFound = errors.New("workflow not found") ) @@ -54,10 +52,9 @@ const ( // // FakeDataSource is safe for concurrent use. type FakeDataSource struct { - interval time.Duration - broker *broker - flatKnowledgeFixture bool - workflowsEnabled bool + interval time.Duration + broker *broker + workflowsEnabled bool mu sync.Mutex st State @@ -68,24 +65,12 @@ type FakeDataSource struct { // NewFakeDataSource returns a FakeDataSource seeded with the noted run and // starts the background goroutine that advances it. func NewFakeDataSource() *FakeDataSource { - return newFakeDataSource(false) -} - -// NewFakeDataSourceFlatKnowledge returns the base Knowledge fixture without the -// additional cluster:4 split. The base fixture still carries the issue #69 -// depth-three research chain so both dev-harness modes exercise deep ancestry. -func NewFakeDataSourceFlatKnowledge() *FakeDataSource { - return newFakeDataSource(true) -} - -func newFakeDataSource(flatKnowledgeFixture bool) *FakeDataSource { workflowsEnabled := os.Getenv("FAKEFEED_WORKFLOWS") != "0" f := &FakeDataSource{ - interval: fakeTickInterval, - broker: newBroker(), - flatKnowledgeFixture: flatKnowledgeFixture, - workflowsEnabled: workflowsEnabled, - st: initialFakeState(workflowsEnabled), + interval: fakeTickInterval, + broker: newBroker(), + workflowsEnabled: workflowsEnabled, + st: initialFakeState(workflowsEnabled), } f.start() return f @@ -1242,44 +1227,31 @@ type fakeAgent struct { capabilities []string autonomyPolicy string health string - // memory mirrors the agent's config memory switch: it drives the card's - // "memory" chip (AgentSummary.MemoryEnabled) and, when a config is present, - // the config section's memory on/off row. - memory bool // config is the agent's [agents.] section for the detail panel, or nil - // when the agent has no config entry. memFacts/memObs are the pretend memory - // pool sizes surfaced by the detail panel. Constant (no time.Now()) so a - // clicked-through AgentDetail stays byte-stable. - config *AgentConfigInfo - memFacts int - memObs int + // when the agent has no config entry. + config *AgentConfigInfo } // fakeAgents is a handful of registered agents with varied runtimes/health so // the Agents page has realistic rows standalone. project-lead/implementer/ // integrator match the names used by the seeded run (so their counts are live); // the rest are idle registrations. -// The fake agents span every config/memory UI branch so the Agents page renders -// them all standalone: a memory-on agent with a config and a live pool -// (researcher); a memory-on agent whose pool is still empty (project-lead); a -// config with memory OFF (implementer); a degraded kimi agent that is likewise -// memory-on with a config and pool (reviewer-kimi — enrolled agents always carry -// a config section, so memory-on implies a config just like real enrollment); and -// plain agents with neither (integrator/ci-runner). All config/pool values are -// constant (no time.Now()) so a clicked-through detail is byte-stable. +// The fake agents span every config UI branch so the Agents page renders them +// all standalone: agents that carry an [agents.] config section +// (project-lead/implementer/researcher/reviewer-kimi, the last one degraded on +// the kimi runtime) and plain agents with none (integrator/ci-runner). All +// config values are constant (no time.Now()) so a clicked-through detail is +// byte-stable. var fakeAgents = []fakeAgent{ {name: "project-lead", role: "coordinator", runtime: "codex", model: "gpt-5.5", capabilities: []string{"orchestrate", "review"}, autonomyPolicy: "workspace-write", health: "healthy", repoScope: []string{fakeRepo}, - memory: true, memFacts: 0, memObs: 0, - config: &AgentConfigInfo{Memory: true, MaxBackground: 4, IdleTimeout: "10m", JobTimeout: "1h", Model: "gpt-5.5", Template: "coordinator", Capabilities: []string{"orchestrate", "review"}}}, + config: &AgentConfigInfo{MaxBackground: 4, IdleTimeout: "10m", JobTimeout: "1h", Model: "gpt-5.5", Template: "coordinator", Capabilities: []string{"orchestrate", "review"}}}, {name: "implementer", role: "implementer", runtime: "codex", model: "gpt-5.5", capabilities: []string{"implement"}, autonomyPolicy: "workspace-write", health: "healthy", repoScope: []string{fakeRepo}, - config: &AgentConfigInfo{Memory: false, MaxBackground: 6, IdleTimeout: "5m", JobTimeout: "45m", Model: "gpt-5.5", Capabilities: []string{"implement"}}}, + config: &AgentConfigInfo{MaxBackground: 6, IdleTimeout: "5m", JobTimeout: "45m", Model: "gpt-5.5", Capabilities: []string{"implement"}}}, {name: "integrator", role: "integrator", runtime: "codex", capabilities: []string{"review", "integrate"}, autonomyPolicy: "workspace-write", health: "healthy", repoScope: []string{fakeRepo}}, {name: "researcher", role: "researcher", runtime: "claude", model: "claude-opus-4-8", capabilities: []string{"research"}, autonomyPolicy: "read-only", health: "healthy", - memory: true, memFacts: 42, memObs: 17, - config: &AgentConfigInfo{Memory: true, MaxBackground: 2, IdleTimeout: "15m", JobTimeout: "30m", Model: "claude-opus-4-8", Template: "researcher", Capabilities: []string{"research"}}}, + config: &AgentConfigInfo{MaxBackground: 2, IdleTimeout: "15m", JobTimeout: "30m", Model: "claude-opus-4-8", Template: "researcher", Capabilities: []string{"research"}}}, {name: "reviewer-kimi", role: "reviewer", runtime: "kimi", model: "kimi-code", capabilities: []string{"review"}, autonomyPolicy: "read-only", health: "degraded", - memory: true, memFacts: 8, memObs: 3, - config: &AgentConfigInfo{Memory: true, MaxBackground: 3, IdleTimeout: "10m", JobTimeout: "30m", Model: "kimi-code", Template: "reviewer", Capabilities: []string{"review"}}}, + config: &AgentConfigInfo{MaxBackground: 3, IdleTimeout: "10m", JobTimeout: "30m", Model: "kimi-code", Template: "reviewer", Capabilities: []string{"review"}}}, {name: "ci-runner", role: "ci", runtime: "shell", capabilities: []string{"ci", "lint"}, autonomyPolicy: "workspace-write", health: "healthy", repoScope: []string{fakeRepo}}, } @@ -1328,7 +1300,6 @@ func (f *FakeDataSource) Agents(ctx context.Context) ([]AgentSummary, error) { Capabilities: fa.capabilities, AutonomyPolicy: fa.autonomyPolicy, Health: fa.health, - MemoryEnabled: fa.memory, } if a := byAgent[fa.name]; a != nil { s.JobCount = a.jobs @@ -1528,9 +1499,9 @@ func (f *FakeDataSource) Agent(ctx context.Context, name string) (AgentDetail, e detail.Template = &tmpl detail.Versions = append([]TemplateVersionInfo(nil), fakeCoordinatorVersions...) } - // Config section + memory pool sizes come from the registered fakeAgent (nil - // config => "no config entry" in the panel). Constant, so the detail stays - // byte-stable across calls. + // Config section comes from the registered fakeAgent (nil config => "no + // config entry" in the panel). Constant, so the detail stays byte-stable + // across calls. for i := range fakeAgents { fa := &fakeAgents[i] if fa.name != name { @@ -1540,8 +1511,6 @@ func (f *FakeDataSource) Agent(ctx context.Context, name string) (AgentDetail, e cfg := *fa.config detail.Config = &cfg } - detail.MemoryFacts = fa.memFacts - detail.MemoryObservations = fa.memObs break } return detail, nil @@ -1926,23 +1895,9 @@ func (f *FakeDataSource) Config(ctx context.Context) (ConfigSnapshot, error) { ModifiedAt: fakeChartsNow.Add(-37 * time.Minute).UnixMilli(), Exists: true, Sections: []ConfigSection{ - {Name: "chat", Knobs: []ConfigKnob{ - {Key: "auto_respond", Value: false, Default: false, IsDefault: true, Kind: "flag", Doc: "Allow enrolled agents to respond automatically in chat threads."}, - }}, {Name: "github", Knobs: []ConfigKnob{ {Key: "rate_limit_per_hour", Value: 4200, Default: 4500, IsDefault: false, Kind: "int", Doc: "Reserve-aware GitHub request budget per hour."}, }}, - {Name: "memory", Knobs: []ConfigKnob{ - {Key: "cluster_depth_cap", Value: 3, Default: 3, IsDefault: true, Kind: "int", Doc: "Maximum recursive memory-cluster depth."}, - {Key: "cluster_fanout", Value: 6, Default: 6, IsDefault: true, Kind: "int", Doc: "Target child clusters created by a split."}, - {Key: "distill_enabled", Value: false, Default: false, IsDefault: true, Kind: "flag", Doc: "Distill confirmed memories into compact reusable facts."}, - {Key: "groom_split_llm", Value: true, Default: false, IsDefault: false, Kind: "flag", Doc: "Use an LLM to propose coherent child clusters during grooming."}, - {Key: "groom_split_max_per_run", Value: 8, Default: 4, IsDefault: false, Kind: "int", Doc: "Maximum LLM-assisted cluster splits per grooming run."}, - {Key: "groom_split_model", Value: "gpt-5.6-sol", Default: "", IsDefault: false, Kind: "string", Doc: "Optional model override for LLM-assisted splits."}, - {Key: "groom_split_runtime", Value: "codex", Default: "codex", IsDefault: true, Kind: "string", Doc: "Runtime used for LLM-assisted cluster splits."}, - {Key: "max_entries", Value: 1200, Default: 1000, IsDefault: false, Kind: "int", Doc: "Maximum confirmed memories considered for injection."}, - {Key: "token_budget", Value: 12000, Default: 12000, IsDefault: true, Kind: "int", Doc: "Token budget for injected memory context."}, - }}, {Name: "orchestrate", Knobs: []ConfigKnob{ {Key: "blocked_ttl", Value: "30m", Default: "30m", IsDefault: true, Kind: "duration", Doc: "Time a blocked orchestration remains resumable."}, }}, @@ -1952,10 +1907,10 @@ func (f *FakeDataSource) Config(ctx context.Context) (ConfigSnapshot, error) { }}, }, Agents: []ConfigAgent{ - {Name: "galaxy-impl", Runtime: "codex", Model: "gpt-5.6-codex", Memory: true, ChatAutorespond: false, Capabilities: []string{"ask", "implement"}, AutonomyPolicy: "workspace-write", MaxBackground: 2}, - {Name: "lead", Runtime: "claude", Model: "opus-4.6", Memory: true, ChatAutorespond: true, Capabilities: []string{"ask", "implement", "review"}, AutonomyPolicy: "workspace-write", MaxBackground: 3}, - {Name: "researcher", Runtime: "kimi", Model: "kimi-k2.5", Memory: true, ChatAutorespond: false, Capabilities: []string{"ask", "review"}, AutonomyPolicy: "read-only", MaxBackground: 1}, - {Name: "reviewer", Runtime: "codex", Model: "gpt-5.6-codex", Memory: false, ChatAutorespond: false, Capabilities: []string{"review"}, AutonomyPolicy: "read-only", MaxBackground: 1}, + {Name: "galaxy-impl", Runtime: "codex", Model: "gpt-5.6-codex", Capabilities: []string{"ask", "implement"}, AutonomyPolicy: "workspace-write", MaxBackground: 2}, + {Name: "lead", Runtime: "claude", Model: "opus-4.6", Capabilities: []string{"ask", "implement", "review"}, AutonomyPolicy: "workspace-write", MaxBackground: 3}, + {Name: "researcher", Runtime: "kimi", Model: "kimi-k2.5", Capabilities: []string{"ask", "review"}, AutonomyPolicy: "read-only", MaxBackground: 1}, + {Name: "reviewer", Runtime: "codex", Model: "gpt-5.6-codex", Capabilities: []string{"review"}, AutonomyPolicy: "read-only", MaxBackground: 1}, }, UnknownKeys: []string{"experimental.scheduler_bias", "plugins.private_token"}, Keychain: fakeKeychain(), @@ -2107,198 +2062,6 @@ func (f *FakeDataSource) Skills(ctx context.Context) (Skills, error) { return fakeSkills(), nil } -// fakeKnowledge builds the fixed memory brain-graph fixture behind the Learning -// page's Knowledge view. Timestamps are anchored on fakeChartsNow (never -// time.Now()) so the view is byte-stable across polls. It models three enrolled -// agents owning eleven facts spread across two repos and two general-scope entries, -// with witness counts varied across 1..7 and two superseded chains. One historical -// repo fact deliberately has no cluster so the client fixture exercises repo-scoped -// unclustered placement. Some fact bodies carry angle brackets, -// ampersands and quotes so the client's HTML-escaping is exercised. -func fakeKnowledge() Knowledge { - dA := func(n int) int64 { return fakeChartsNow.AddDate(0, 0, -n).UnixMilli() } - - // Fact bodies deliberately mix angle brackets, ampersands and quotes (to - // exercise the client's escape-FIRST HTML escaping) with a safe markdown - // subset — **bold**, `inline code`, - lists, fenced code, plain https links - // and [[fact:id]] wikilinks — so the detail panel's markdown renderer is - // exercised end-to-end. The wikilinks mirror the Links slice. - facts := []KnowledgeFact{ - {ID: "fact:1", Content: `Build with GOTOOLCHAIN=local & GOFLAGS=-mod=mod; the pinned go1.26.4 toolchain lives under /root/.local.`, Repo: fakeRepo, Key: "build-toolchain", Owner: "researcher", Witnesses: 5, FirstSeen: dA(18), LastSeen: dA(1), Cluster: "cluster:3:delivery:build", SourceJob: "job:build-31", Links: []string{"fact:8"}}, - {ID: "fact:2", Content: `TestExport is flaky under -race; retry once before failing the job.`, Repo: fakeRepo, Key: "test-flake", Owner: "reviewer-kimi", Witnesses: 3, FirstSeen: dA(16), LastSeen: dA(2), Cluster: "cluster:2", SourceJob: "job:test-88"}, - {ID: "fact:3", Content: `Auth uses tokens & refreshes 5m before expiry; header is "Authorization".`, Repo: fakeRepo, Key: "auth-flow", Owner: "researcher", Witnesses: 7, FirstSeen: dA(15), LastSeen: dA(2), Superseded: true, Cluster: "cluster:1", SourceJob: "job:auth-12"}, - {ID: "fact:4", Content: `Exports default to CSV; JSON is opt-in via --format json.`, Repo: "jerryfane/noted", Key: "export-format", Owner: "project-lead", Witnesses: 2, FirstSeen: dA(12), LastSeen: dA(3), Cluster: "cluster:4", SourceFile: "jerryfane/noted:docs/exports.md"}, - {ID: "fact:5", Content: `Search index rebuilds lazily on the first query after a write.`, Repo: "jerryfane/noted", Key: "search-index", Owner: "researcher", Witnesses: 4, FirstSeen: dA(10), LastSeen: dA(1), Cluster: "cluster:4", SourceJob: "job:idx-40", Links: []string{"fact:7"}}, - {ID: "fact:6", Content: `Bulk delete requires a confirm token & is soft-delete for 30 days.`, Repo: "jerryfane/noted", Key: "delete-safety", Owner: "reviewer-kimi", Witnesses: 1, FirstSeen: dA(9), LastSeen: dA(4), Cluster: "cluster:4", SourceFile: "jerryfane/noted:docs/deletion.md"}, - {ID: "fact:7", Content: `Rate limiting is per-token: 100 req/min, burst 20; 429 carries Retry-After.`, Repo: "jerryfane/noted", Key: "rate-limit", Owner: "researcher", Witnesses: 4, FirstSeen: dA(7), LastSeen: dA(2), Cluster: "cluster:4", SourceJob: "job:rl-19"}, - {ID: "fact:8", Content: "Cut GA releases only with explicit sign-off; \"deploy latest\" means build & install locally.\n\nChecklist:\n- run `make release`\n- verify the tag & sha256sums\n- see https://gitmoot.io/docs/releasing\n\n```sh\ngh release create vX.Y.Z --latest\n```\n\nRelated: [[fact:1]].", Key: "release-policy", Owner: "researcher", Witnesses: 6, FirstSeen: dA(5), LastSeen: dA(1), Cluster: "cluster:3:delivery:release", SourceFile: "docs/RELEASING.md", Links: []string{"fact:1"}}, - {ID: "fact:9", Content: "Auth migrated to tokens & rotating keys; refresh 10m before \"expiry\". Supersedes [[fact:3]]; **rotate keys** nightly via `authctl rotate`.", Repo: fakeRepo, Key: "auth-flow", Owner: "researcher", Witnesses: 2, FirstSeen: dA(2), LastSeen: dA(1), Cluster: "cluster:1", SourceJob: "job:auth-77", Links: []string{"fact:3"}}, - {ID: "fact:10", Content: `Prefer table-driven tests & gofmt; avoid naked returns in long functions.`, Key: "coding-style", Owner: "project-lead", Witnesses: 3, FirstSeen: dA(4), LastSeen: dA(1), Cluster: "cluster:2", SourceFile: "CONTRIBUTING.md"}, - {ID: "fact:11", Content: `Builds must use the system Go toolchain; do not use a pinned local toolchain.`, Repo: fakeRepo, Key: "build-toolchain", Owner: "researcher", Witnesses: 2, FirstSeen: dA(22), LastSeen: dA(19), Superseded: true, SourceJob: "job:build-09"}, - } - // Newest-first by FirstSeen (distinct across the fixture), ID tie-break. - sort.SliceStable(facts, func(i, j int) bool { - if facts[i].FirstSeen != facts[j].FirstSeen { - return facts[i].FirstSeen > facts[j].FirstSeen - } - return facts[i].ID < facts[j].ID - }) - - // Enrolled agents. Facts is the INJECTABLE count (the real datasource fills it - // from CountConfirmedMemoriesForOwner, which excludes superseded_by IS NOT NULL - // rows), so it deliberately differs from the on-graph owned-node count where an - // agent has superseded facts. researcher OWNS seven fact nodes but two (fact:3 - // and fact:11) are excluded, so its injectable count is 5; reviewer-kimi owns 2 - // and project-lead owns 2 (none superseded). - agents := []KnowledgeAgent{ - {Name: "project-lead", Enrolled: true, Facts: 2, Observations: 3}, - {Name: "researcher", Enrolled: true, Facts: 5, Observations: 12}, - {Name: "reviewer-kimi", Enrolled: true, Facts: 2, Observations: 4}, - } - sort.SliceStable(agents, func(i, j int) bool { return agents[i].Name < agents[j].Name }) - - // Emergent clusters (gitmoot #763): four communities over the ten facts, - // anchored to a medoid fact for label stability. Repo is the dominant repo - // scope ("" = general/mixed), so the client nests repo -> cluster -> fact. - // The client renders Label verbatim (an owner override wins server-side). - // - // The member distribution is deliberately UNEVEN (4 / 2 / 2 / 2 facts) so the - // clustered four-column layout shows visibly grouped fact bands with gaps - // between cluster groups. This non-empty slice drives the clustered left -> - // right column view; a build that returns an EMPTY clusters slice (and empty - // per-fact Cluster fields) instead exercises the legacy fallback layout - // (the scope/category columns), so both code paths stay reachable in fake mode. - clusters := []KnowledgeCluster{ - {ID: "cluster:1", Label: "auth & tokens", Repo: fakeRepo, Medoid: "fact:9"}, - {ID: "cluster:2", Label: "testing & style", Medoid: "fact:2"}, - {ID: "cluster:3", Label: "build & release"}, - {ID: "cluster:3:delivery", Label: "delivery workflow", Medoid: "fact:1", ParentID: "cluster:3"}, - {ID: "cluster:3:delivery:build", Label: "build toolchain", Medoid: "fact:1", ParentID: "cluster:3:delivery"}, - {ID: "cluster:3:delivery:release", Label: "release policy", Medoid: "fact:8", ParentID: "cluster:3:delivery"}, - {ID: "cluster:4", Label: "noted api & data", Repo: "jerryfane/noted", Medoid: "fact:7"}, - } - // Count is derived recursively from leaf assignments so intermediate/root - // totals cannot drift as the fixture grows deeper. - directCount := map[string]int{} - for _, fct := range facts { - if fct.Cluster != "" { - directCount[fct.Cluster]++ - } - } - children := map[string][]string{} - for _, c := range clusters { - if c.ParentID != "" { - children[c.ParentID] = append(children[c.ParentID], c.ID) - } - } - var clusterCount func(string) int - clusterCount = func(id string) int { - total := directCount[id] - for _, child := range children[id] { - total += clusterCount(child) - } - return total - } - for i := range clusters { - clusters[i].Count = clusterCount(clusters[i].ID) - } - sort.SliceStable(clusters, func(i, j int) bool { return clusters[i].ID < clusters[j].ID }) - - // Owner + category + cluster edges per fact, then two supersede chains. - // Category edges stay - // for the pre-cluster fallback view; cluster edges back the repo -> cluster - // -> fact hierarchy. Scored link edges are undirected and emitted once per - // pair. They deliberately cover tight in-cluster pairs, cross-cluster pairs, - // and cross-repo pairs so the dev harness exercises every galaxy treatment. - edges := make([]KnowledgeEdge, 0, len(facts)*3+10) - for _, fct := range facts { - edges = append(edges, KnowledgeEdge{Source: fct.ID, Target: fct.Owner, Kind: "owner"}) - cat := fct.Repo - if cat == "" { - cat = "general" - } - edges = append(edges, KnowledgeEdge{Source: fct.ID, Target: cat, Kind: "category"}) - if fct.Cluster != "" { - edges = append(edges, KnowledgeEdge{Source: fct.ID, Target: fct.Cluster, Kind: "cluster"}) - } - } - edges = append(edges, KnowledgeEdge{Source: "fact:9", Target: "fact:3", Kind: "supersede"}) - edges = append(edges, KnowledgeEdge{Source: "fact:1", Target: "fact:11", Kind: "supersede"}) - edges = append(edges, - KnowledgeEdge{Source: "fact:3", Target: "fact:9", Kind: "link", Score: 0.95}, - KnowledgeEdge{Source: "fact:1", Target: "fact:8", Kind: "link", Score: 0.92}, - KnowledgeEdge{Source: "fact:6", Target: "fact:7", Kind: "link", Score: 0.88}, - KnowledgeEdge{Source: "fact:2", Target: "fact:10", Kind: "link", Score: 0.84}, - KnowledgeEdge{Source: "fact:4", Target: "fact:5", Kind: "link", Score: 0.78}, - KnowledgeEdge{Source: "fact:5", Target: "fact:7", Kind: "link", Score: 0.62}, - KnowledgeEdge{Source: "fact:1", Target: "fact:2", Kind: "link", Score: 0.48}, - KnowledgeEdge{Source: "fact:1", Target: "fact:4", Kind: "link", Score: 0.33}, - KnowledgeEdge{Source: "fact:9", Target: "fact:5", Kind: "link", Score: 0.15}, - ) - sort.SliceStable(edges, func(i, j int) bool { - if edges[i].Kind != edges[j].Kind { - return edges[i].Kind < edges[j].Kind - } - if edges[i].Source != edges[j].Source { - return edges[i].Source < edges[j].Source - } - return edges[i].Target < edges[j].Target - }) - - return Knowledge{Agents: agents, Facts: facts, Clusters: clusters, Edges: edges} -} - -// fakeKnowledgeWithSubclusters derives the default hierarchy fixture from the -// depth-three base fixture. cluster:4 additionally becomes a parent with two -// leaf children; the children omit Repo so the dashboard inherits the root lane. -func fakeKnowledgeWithSubclusters() Knowledge { - k := fakeKnowledge() - leafByFact := map[string]string{ - "fact:4": "cluster:4:storage", - "fact:5": "cluster:4:storage", - "fact:6": "cluster:4:safety", - "fact:7": "cluster:4:safety", - } - for i := range k.Facts { - if leaf := leafByFact[k.Facts[i].ID]; leaf != "" { - k.Facts[i].Cluster = leaf - } - } - k.Clusters = append(k.Clusters, - KnowledgeCluster{ID: "cluster:4:safety", Label: "limits & deletion", Count: 2, Medoid: "fact:7", ParentID: "cluster:4"}, - KnowledgeCluster{ID: "cluster:4:storage", Label: "exports & search", Count: 2, Medoid: "fact:5", ParentID: "cluster:4"}, - ) - for i := range k.Edges { - if k.Edges[i].Kind != "cluster" { - continue - } - if leaf := leafByFact[k.Edges[i].Source]; leaf != "" { - k.Edges[i].Target = leaf - } - } - sort.SliceStable(k.Clusters, func(i, j int) bool { return k.Clusters[i].ID < k.Clusters[j].ID }) - sort.SliceStable(k.Edges, func(i, j int) bool { - if k.Edges[i].Kind != k.Edges[j].Kind { - return k.Edges[i].Kind < k.Edges[j].Kind - } - if k.Edges[i].Source != k.Edges[j].Source { - return k.Edges[i].Source < k.Edges[j].Source - } - return k.Edges[i].Target < k.Edges[j].Target - }) - return k -} - -// Knowledge implements DataSource. Both fixtures carry the issue #69 depth-three -// chain; the default adds the existing cluster:4 split. Both remain deterministic -// and byte-stable across calls. -func (f *FakeDataSource) Knowledge(ctx context.Context) (Knowledge, error) { - if f.flatKnowledgeFixture { - return fakeKnowledge(), nil - } - return fakeKnowledgeWithSubclusters(), nil -} - // fakePipelineRuns builds the fixed set of pipeline run details (gitmoot #681) // behind the Pipelines section, keyed by run id. Every timestamp is anchored on // fakeChartsNow (never time.Now()) so the section is byte-stable across polls. @@ -2782,184 +2545,6 @@ func (f *FakeDataSource) PipelineDetail(ctx context.Context, name string) (Pipel return detail, nil } -// fakeChatThreadDetails builds the fixed set of chat threads (gitmoot #534), -// keyed by thread id. Every timestamp is anchored on fakeChartsNow (never -// time.Now()) so the section is byte-stable across polls. The four threads -// together exercise every real-emittable shape: -// - chat-release-room: a busy multi-agent thread with a promotion_request that -// spawned a job (promotedJobId) and the agent's job_result posted back, plus -// refs to a job and a PR; -// - chat-adapter-review: an ask-gate flow — an agent message, a `system` -// ask-gate question from a paused job, the human's answer (reply_to), and the -// resumed agent's job_result; -// - chat-triage-inbox: a fresh thread with pending @mentions (unread) and no -// replies yet; -// - chat-sqlite-migration: an archived, wrapped-up thread. -// -// Some bodies carry angle brackets, ampersands and a fake ** and inline ``.\n\n> quoted not-bold & a bare link javascript:alert(document.cookie) stays plain text.\n\n```\n\n```"}, - }, - }, - { - ChatThreadSummary: ChatThreadSummary{ - ID: "chat-adapter-review", Slug: "adapter-review", Name: "Adapter review", - Repo: "jerryfane/gitmoot", State: "open", CreatedBy: "jerry", - UnreadMentions: 0, Participants: []string{"jerry", "reviewer"}, - }, - Messages: []ChatMessage{ - {ID: "msg-ar-1", Seq: 1, TsMs: at(2*h + 30*m), AuthorKind: "agent", AuthorName: "reviewer", Kind: "chat", - Body: "Starting an adversarial review of the adapter manifest PR (#742)."}, - {ID: "msg-ar-2", Seq: 2, TsMs: at(2*h + 8*m), AuthorKind: "system", AuthorName: "", Kind: "system", - Body: "Job job-adapter-review-07 is paused awaiting an answer:\n\nThe manifest omits a network_access flag. Should ephemeral codex workers be granted network access by default? (yes/no)", - Refs: []ChatRef{{Kind: "job", Repo: "jerryfane/gitmoot", ID: "job-adapter-review-07"}}}, - {ID: "msg-ar-3", Seq: 3, TsMs: at(2 * h), AuthorKind: "human", AuthorName: "jerry", Kind: "chat", ReplyTo: "msg-ar-2", - Body: "yes — codex ephemeral workers need [sandbox_workspace_write] network_access=true to push branches & open PRs (default sandbox blocks network -> gh \"auth invalid\")."}, - {ID: "msg-ar-4", Seq: 4, TsMs: at(2*h - 12*m), AuthorKind: "agent", AuthorName: "reviewer", Kind: "job_result", ReplyTo: "msg-ar-3", - Body: "**Decision:** approved\n**Summary:** resumed after the ask-gate answer. Approved with a note that `network_access=true` is required for the ephemeral worker path. No blocking findings.\n**Verify:** re-ran the manifest schema test -> ok", - Refs: []ChatRef{{Kind: "job", Repo: "jerryfane/gitmoot", ID: "job-adapter-review-07"}, {Kind: "pr", Repo: "jerryfane/gitmoot", ID: "742", URL: "https://github.com/jerryfane/gitmoot/pull/742"}}}, - }, - }, - { - ChatThreadSummary: ChatThreadSummary{ - ID: "chat-triage-inbox", Slug: "triage-inbox", Name: "Triage inbox", - Repo: "jerryfane/noted", State: "open", CreatedBy: "gaijinjoe", - UnreadMentions: 2, Participants: []string{"claude-a", "gaijinjoe", "researcher"}, - }, - Messages: []ChatMessage{ - {ID: "msg-ti-1", Seq: 1, TsMs: at(6 * m), AuthorKind: "human", AuthorName: "gaijinjoe", Kind: "chat", - Body: "@claude-a the nightly-deploy pipeline is parked (score stage blocked on the R2 token). Can you look? @researcher any known R2 token rotation issues this week? but no auto-run — I'll promote if needed."}, - }, - }, - { - ChatThreadSummary: ChatThreadSummary{ - ID: "chat-sqlite-migration", Slug: "sqlite-migration", Name: "SQLite migration", - Repo: "acme/webapp", State: "archived", CreatedBy: "jerry", - UnreadMentions: 0, Participants: []string{"codex-b", "jerry"}, - }, - Messages: []ChatMessage{ - {ID: "msg-sm-1", Seq: 1, TsMs: at(6 * d), AuthorKind: "human", AuthorName: "jerry", Kind: "chat", - Body: "Let's coordinate the modernc pure-Go SQLite migration here (no cgo, single static binary stays sacred)."}, - {ID: "msg-sm-2", Seq: 2, TsMs: at(6*d - 3*h), AuthorKind: "agent", AuthorName: "codex-b", Kind: "chat", - Body: "Done — swapped mattn/go-sqlite3 -> modernc.org/sqlite. All migrations pass, `CGO_ENABLED=0 go build` is clean, binary is fully static."}, - {ID: "msg-sm-3", Seq: 3, TsMs: at(6*d - 4*h), AuthorKind: "human", AuthorName: "jerry", Kind: "chat", - Body: "Perfect. Archiving this thread, thanks."}, - }, - }, - } - - out := make(map[string]*ChatThreadDetail, len(details)) - for _, det := range details { - // Derive the summary rollup from the message history so the list and the - // detail can never disagree. - det.MessageCount = len(det.Messages) - if n := len(det.Messages); n > 0 { - last := det.Messages[n-1] - det.UpdatedAt = last.TsMs - det.LastAuthor = last.AuthorName - if last.AuthorKind == "system" { - det.LastAuthor = "system" - } - det.LastKind = last.Kind - det.LastSnippet = chatSnippet(last.Body) - } - sort.Strings(det.Participants) - out[det.ID] = det - } - return out -} - -// chatSnippet collapses a message body to a single-line, server-truncated -// preview (matching what the live store would send so the client never has to -// re-truncate). Newlines become spaces and the result is capped at 90 runes. -func chatSnippet(body string) string { - s := strings.Join(strings.Fields(body), " ") - const cap = 90 - r := []rune(s) - if len(r) > cap { - return strings.TrimRight(string(r[:cap]), " ") + "…" - } - return s -} - -// fakeChatThreads projects the fixed thread details into the list summaries, -// sorted most-recently-active first (UpdatedAt desc, id desc tie-break) so the -// view is byte-stable across polls. -func fakeChatThreads() []ChatThreadSummary { - details := fakeChatThreadDetails() - out := make([]ChatThreadSummary, 0, len(details)) - for _, det := range details { - s := det.ChatThreadSummary - // copy the participants slice so callers can't mutate the fixture - s.Participants = append([]string(nil), det.Participants...) - out = append(out, s) - } - sort.SliceStable(out, func(i, j int) bool { - if out[i].UpdatedAt != out[j].UpdatedAt { - return out[i].UpdatedAt > out[j].UpdatedAt // most recent first - } - return out[i].ID > out[j].ID // id desc tie-break (unique) - }) - return out -} - -// ChatThreads implements DataSource. It returns the fixed fakeChatThreads -// fixture; output is deterministic and byte-stable across calls. -func (f *FakeDataSource) ChatThreads(ctx context.Context) ([]ChatThreadSummary, error) { - return fakeChatThreads(), nil -} - -// ChatThread implements DataSource. It returns the fixed detail for a thread by -// id from the fakeChatThreadDetails fixture; unknown ids return -// (nil, ErrChatThreadNotFound). Output is deterministic and byte-stable. -func (f *FakeDataSource) ChatThread(ctx context.Context, id string) (*ChatThreadDetail, error) { - det, ok := fakeChatThreadDetails()[id] - if !ok { - return nil, ErrChatThreadNotFound - } - // copy so callers can't mutate the fixture's shared slices - cp := *det - cp.Participants = append([]string(nil), det.Participants...) - cp.Messages = append([]ChatMessage(nil), det.Messages...) - return &cp, nil -} - // fakeVerdictRun is the SkillOpt eval run id the fake binary-verdicts fixture is // keyed on (matches the pending candidate skill-reviewer-v3's evaluation). const fakeVerdictRun = "eval-reviewer-0007" diff --git a/server.go b/server.go index c5c3be2..3910da4 100644 --- a/server.go +++ b/server.go @@ -11,10 +11,10 @@ import ( // Serve returns an http.Handler serving the read-only dashboard: the embedded // static UI (with SPA fallback to index.html) plus the JSON API (handleRuns/ // handleJobs/handleAgents/handleAgent/handleCharts/handleHealth/ -// handleLearningSkills/handleLearningKnowledge/handlePipelines/ +// handleLearningSkills/handlePipelines/ // handlePipelineDetail/handlePipelineRun/handleOverview/handleTasks/ // handleWakeSummary/handleWakes/handleWakeReceipts/ -// handleOrg/handleOrgRole/handleWorkflows/handleWorkflow/handleChatThreads/handleChatThread/ +// handleOrg/handleOrgRole/handleWorkflows/handleWorkflow/ // handleAttention/handleJobChecks/handleBinaryVerdicts/ // handleState/handleJob/handleGraph/handleChangeEvents in api.go) and the // run-state SSE stream (handleEvents in sse.go). @@ -30,7 +30,6 @@ func Serve(ds DataSource) http.Handler { mux.HandleFunc("GET /api/health", s.handleHealth) mux.HandleFunc("GET /api/config", s.handleConfig) mux.HandleFunc("GET /api/learning/skills", s.handleLearningSkills) - mux.HandleFunc("GET /api/learning/knowledge", s.handleLearningKnowledge) mux.HandleFunc("GET /api/pipelines", s.handlePipelines) mux.HandleFunc("GET /api/pipelines/{name}", s.handlePipelineDetail) mux.HandleFunc("GET /api/pipeline/run/{id}", s.handlePipelineRun) @@ -43,8 +42,6 @@ func Serve(ds DataSource) http.Handler { mux.HandleFunc("GET /api/org/role/{name}", s.handleOrgRole) mux.HandleFunc("GET /api/workflows", s.handleWorkflows) mux.HandleFunc("GET /api/workflow/{label}", s.handleWorkflow) - mux.HandleFunc("GET /api/chat/threads", s.handleChatThreads) - mux.HandleFunc("GET /api/chat/thread", s.handleChatThread) mux.HandleFunc("GET /api/attention", s.handleAttention) mux.HandleFunc("GET /api/job/{id}/checks", s.handleJobChecks) mux.HandleFunc("GET /api/run/{id}/verdicts", s.handleBinaryVerdicts) @@ -76,11 +73,11 @@ func newServer(ds DataSource) *server { } // The JSON API handlers (handleRuns/handleJobs/handleAgents/handleAgent/ -// handleCharts/handleHealth/handleLearningSkills/handleLearningKnowledge/ +// handleCharts/handleHealth/handleLearningSkills/ // handlePipelines/handlePipelineDetail/handlePipelineRun/handleOverview/handleTasks/ // handleWakeSummary/handleWakes/handleWakeReceipts/ -// handleOrg/handleOrgRole/handleWorkflows/handleWorkflow/handleChatThreads/ -// handleChatThread/handleAttention/handleJobChecks/handleBinaryVerdicts/ +// handleOrg/handleOrgRole/handleWorkflows/handleWorkflow/ +// handleAttention/handleJobChecks/handleBinaryVerdicts/ // handleState/handleJob/handleGraph/handleChangeEvents) live in api.go and the // run-state SSE handler (handleEvents) lives in sse.go. diff --git a/server_test.go b/server_test.go index 06cdbbd..aff3669 100644 --- a/server_test.go +++ b/server_test.go @@ -89,27 +89,6 @@ func TestPipelinesRouteRegistered(t *testing.T) { } } -// TestChatThreadsRouteRegistered asserts the /api/chat/threads route is wired -// into the mux and served by the JSON handler (not the static SPA fallback, -// which would return an HTML index). Mirrors TestStateRouteRegistered. -func TestChatThreadsRouteRegistered(t *testing.T) { - srv := httptest.NewServer(Serve(NewFakeDataSource())) - defer srv.Close() - - resp, err := http.Get(srv.URL + "/api/chat/threads") - if err != nil { - t.Fatalf("GET /api/chat/threads: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - t.Fatalf("GET /api/chat/threads status = %d, want 200", resp.StatusCode) - } - if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { - t.Fatalf("GET /api/chat/threads Content-Type = %q, want application/json", ct) - } -} - // TestOrgRoutesRegistered asserts both optional Org API routes are wired into // the mux and served as JSON rather than falling through to the SPA shell. func TestOrgRoutesRegistered(t *testing.T) { diff --git a/web/dist/index.html b/web/dist/index.html index 4d9f7c0..0aef891 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -34,7 +34,7 @@ .gm-aplink:hover{background:rgba(158,206,106,0.12);border-color:rgba(158,206,106,0.35);color:#eef0ff} .gm-aplink svg{flex:none} .gm-aplink .ext{opacity:.55} - .ov-scroll,.wfi-scroll,.wfd-scroll,.tk-col-body,.tk-detail-body,.pl-list-scroll,.pl-main-body,.pl-runs,.jb-tablewrap,.jd-body,.ag-list,.ag-pane,.gd-body,.ch-scroll,.at-scroll,.hl-body,.cfg-scroll,.xd-body,#lr-skills,#lr-know-mobile,.lr-dbody,.bc-feed,.ch-list,.cd-body,.ci-scroll,.gm-graph-detail-body,.gm-more-sheet,.gm-runs-list{overscroll-behavior-y:contain} + .ov-scroll,.wfi-scroll,.wfd-scroll,.tk-col-body,.tk-detail-body,.pl-list-scroll,.pl-main-body,.pl-runs,.jb-tablewrap,.jd-body,.ag-list,.ag-pane,.gd-body,.ch-scroll,.at-scroll,.hl-body,.cfg-scroll,.xd-body,#lr-skills,.gm-graph-detail-body,.gm-more-sheet,.gm-runs-list{overscroll-behavior-y:contain} .ov-fleet-list{overscroll-behavior-x:contain} .gm-ptr-indicator{position:fixed;left:0;top:0;z-index:120;height:0;display:flex;justify-content:center;overflow:visible;pointer-events:none;opacity:0;transform:translateY(-18px);transition:opacity .14s ease,transform .14s ease} .gm-ptr-indicator span{display:inline-flex;align-items:center;gap:7px;height:24px;padding:0 10px;border:1px solid rgba(160,168,220,.14);border-radius:12px;background:rgba(13,15,28,.94);box-shadow:0 5px 18px rgba(0,0,0,.28);color:#7b82aa;font:9px 'JetBrains Mono',monospace;letter-spacing:.05em;text-transform:uppercase;white-space:nowrap} @@ -129,18 +129,8 @@ Org -
- - Chat - -
INSIGHT
-
- - Brain - -
Galaxy @@ -306,9 +296,9 @@
WORK
Overview
Tasks
Workflows
Jobs
Pipelines
FLEET
-
Agents
Org
Chat
+
Agents
Org
INSIGHT
-
Brain
Galaxy
Charts
Learning
+
Galaxy
Charts
Learning
SYSTEM
Needs a human
Health
Config
@@ -329,10 +319,6 @@ Workflows -
- - Brain -
More @@ -360,10 +346,7 @@ this.state.view = r.view; if (r.view === 'jobs' && r.agent) this._jobsFacetAgent = r.agent; if (r.view === 'agents' && r.agent) this._pendingAgentDetail = r.agent; - if (r.view === 'learning') this._learningTab = 'skills'; - if (r.view === 'brain') { this._learningTab = 'knowledge'; this._brainRestoreRoute(r.brain); } if (r.view === 'pipelines') this._pendingPipelineDetail = r.name || null; - if (r.view === 'chat') this._pendingChatThread = r.name || null; if (r.view === 'workflows') this._pendingWorkflowLabel = r.name || null; // Normalize unknown paths to '/' (Overview). Also tidy a non-canonical known // path (e.g. a trailing slash). Never rewrite a graph URL, so a @@ -371,7 +354,7 @@ if (r.unknown) { try { history.replaceState(null, '', '/'); } catch (e) {} } else if (r.view !== 'graph') { - const canon = this._routeUrl(r.view, { agent: r.agent, tab: r.tab, name: r.name, brain: r.brain }); + const canon = this._routeUrl(r.view, { agent: r.agent, tab: r.tab, name: r.name }); if ((location.pathname + location.search) !== canon) { try { history.replaceState(null, '', canon); } catch (e) {} } @@ -383,7 +366,7 @@ // ---- client-side router ---------------------------------------------------- // Route table: / -> overview (or graph when ?run= is present) | /tasks | // /galaxy | /jobs[?agent=] | /agents | /org | - // /agents/ | /brain | /charts | /health | /config. Agent names are encode/decode- + // /agents/ | /charts | /health | /config. Agent names are encode/decode- // URIComponent'd and treated as one path segment after /agents/. _parseRoute(pathname, search) { let p = pathname || '/'; @@ -395,7 +378,6 @@ } if (p === '/tasks') return { view: 'tasks' }; if (p === '/galaxy') return { view: 'galaxy' }; - if (p === '/brain') return { view: 'brain', brain: this._brainParseRoute(search) }; if (p === '/charts') return { view: 'charts' }; if (p === '/health') return { view: 'health' }; if (p === '/config') return { view: 'config' }; @@ -404,7 +386,6 @@ // /learning normalizes to /learning/skills (constructor/_onPopState canonicalize). if (p === '/learning') return { view: 'learning', tab: 'skills' }; if (p === '/learning/skills') return { view: 'learning', tab: 'skills' }; - if (p === '/learning/knowledge') return { view: 'brain', brain: this._brainParseRoute(search) }; // constructor canonicalizes with replaceState if (p === '/jobs') { const a = this._routeQueryAgent(search); return a ? { view: 'jobs', agent: a } : { view: 'jobs' }; } if (p === '/pipelines') return { view: 'pipelines' }; if (p.indexOf('/pipelines/') === 0) { @@ -420,13 +401,6 @@ try { name = decodeURIComponent(raw); } catch (e) { name = raw; } return name ? { view: 'workflows', name: name } : { view: 'workflows' }; } - if (p === '/chat') return { view: 'chat' }; - if (p.indexOf('/chat/') === 0) { - const raw = p.slice(6); // '/chat/'.length - let name = raw; - try { name = decodeURIComponent(raw); } catch (e) { name = raw; } - return name ? { view: 'chat', name: name } : { view: 'chat' }; - } if (p === '/agents') return { view: 'agents' }; if (p.indexOf('/agents/') === 0) { const raw = p.slice(8); // '/agents/'.length @@ -452,70 +426,22 @@ } return ''; } - _brainParseRoute(search) { - const out = { view: 'graph', fact: '', kinds: [], repo: '', actor: '', q: '' }; - try { - const p = new URLSearchParams(search || ''); - if (p.get('view') === 'changelog') out.view = 'changelog'; - out.fact = p.get('fact') || ''; - out.repo = p.get('repo') || ''; - out.actor = p.get('actor') || ''; - out.q = p.get('q') || ''; - const seen = {}; - out.kinds = (p.get('kinds') || '').split(',').map(v => v.trim()).filter(v => v && !seen[v] && (seen[v] = true)); - if (out.fact || out.kinds.length || out.repo || out.actor || out.q) out.view = 'changelog'; - } catch (e) {} - return out; - } - _brainRestoreRoute(route) { - route = route || { view: 'graph', fact: '', kinds: [], repo: '', actor: '', q: '' }; - const previousFact = this._brainBiographyKey || ''; - this._brainView = route.view === 'changelog' ? 'changelog' : 'graph'; - this._brainBiographyKey = route.fact || ''; - if (previousFact !== this._brainBiographyKey) { this._brainBiographyMemoryId = null; this._brainBiographyFact = null; } - this._brainFilters = { - kinds: Array.isArray(route.kinds) ? route.kinds.slice() : [], - repo: route.repo || '', actor: route.actor || '', q: route.q || '' - }; - } - _brainRouteState() { - const f = this._brainFilters || {}; - return { - view: this._brainView === 'changelog' ? 'changelog' : 'graph', - fact: this._brainBiographyKey || '', kinds: Array.isArray(f.kinds) ? f.kinds.slice() : [], - repo: f.repo || '', actor: f.actor || '', q: f.q || '' - }; - } - _brainRouteUrl(route) { - route = route || this._brainRouteState(); - if (route.view !== 'changelog') return '/brain'; - const p = new URLSearchParams(); - p.set('view', 'changelog'); - if (route.fact) p.set('fact', route.fact); - if (route.kinds && route.kinds.length) p.set('kinds', route.kinds.join(',')); - if (route.repo) p.set('repo', route.repo); - if (route.actor) p.set('actor', route.actor); - if (route.q) p.set('q', route.q); - return '/brain?' + p.toString(); - } _routeUrl(view, opts) { opts = opts || {}; switch (view) { case 'overview': return '/'; case 'tasks': return '/tasks'; case 'galaxy': return '/galaxy'; - case 'brain': return this._brainRouteUrl(opts.brain || this._brainRouteState()); case 'jobs': return opts.agent ? '/jobs?agent=' + encodeURIComponent(opts.agent) : '/jobs'; case 'pipelines': return opts.name ? '/pipelines/' + encodeURIComponent(opts.name) : '/pipelines'; case 'workflows': return opts.name ? '/workflows/' + encodeURIComponent(opts.name) : '/workflows'; - case 'chat': return opts.name ? '/chat/' + encodeURIComponent(opts.name) : '/chat'; case 'agents': return opts.agent ? '/agents/' + encodeURIComponent(opts.agent) : '/agents'; case 'org': return '/org'; case 'charts': return '/charts'; case 'health': return '/health'; case 'config': return '/config'; case 'attention': return '/attention'; - case 'learning': return '/learning/' + (opts.tab === 'knowledge' ? 'knowledge' : 'skills'); + case 'learning': return '/learning/skills'; case 'graph': { // graph: keep a '?run=' deep-link if the URL already carries one, so // selecting a run (which replaceState's ?run) survives a Graph-tab click. @@ -535,18 +461,16 @@ case 'overview': return 'gitmoot · overview'; case 'tasks': return 'gitmoot · tasks'; case 'galaxy': return 'gitmoot · galaxy'; - case 'brain': return 'gitmoot · brain'; case 'jobs': return opts.agent ? 'gitmoot · jobs · ' + opts.agent : 'gitmoot · jobs'; case 'pipelines': return opts.name ? 'gitmoot · pipelines · ' + opts.name : 'gitmoot · pipelines'; case 'workflows': return opts.name ? 'gitmoot · workflow · ' + opts.name : 'gitmoot · workflows'; - case 'chat': return opts.name ? 'gitmoot · chat · ' + opts.name : 'gitmoot · chat'; case 'agents': return opts.agent ? 'gitmoot · agents · ' + opts.agent : 'gitmoot · agents'; case 'org': return 'gitmoot · org'; case 'charts': return 'gitmoot · charts'; case 'health': return 'gitmoot · health'; case 'config': return 'gitmoot · config'; case 'attention': return 'gitmoot · needs a human'; - case 'learning': return 'gitmoot · learning · ' + (opts.tab === 'knowledge' ? 'knowledge' : 'skills'); + case 'learning': return 'gitmoot · learning · skills'; case 'graph': return 'gitmoot · graph'; default: return 'gitmoot'; } @@ -572,9 +496,6 @@ _onPopState = () => { let r; try { r = this._parseRoute(location.pathname, location.search); } catch (e) { r = { view: 'overview' }; } - if (r.view === 'brain' && location.pathname.replace(/\/+$/, '') === '/learning/knowledge') { - try { history.replaceState(null, '', this._brainRouteUrl(r.brain)); } catch (e) {} - } this._routing = true; try { try { document.title = this._routeTitle(r.view, { agent: r.agent, tab: r.tab, name: r.name }); } catch (e) {} @@ -598,28 +519,6 @@ } else { this._pendingWorkflowLabel = r.name || null; } - } else if (r.view === 'chat') { - if (this._chatRoot) { - // chat already mounted (possibly hidden): open/close thread in place. - if (r.name) { if (this._chatSelected !== r.name) this.openChatThread(r.name); } - else if (this._chatSelected) this.closeChatThread(); - } else { - // not mounted yet: applyView opens the thread after it mounts. - this._pendingChatThread = r.name || null; - } - } else if (r.view === 'brain') { - this._learningTab = 'knowledge'; - this._brainRestoreRoute(r.brain); - if (this.state.view === 'brain' && this._learningRoot) this._applyBrainView(true); - } else if (r.view === 'learning') { - const tab = 'skills'; - if (this._learningRoot) { - // learning already mounted: switch sub-tab in place (view unchanged => - // no setState re-render, so drive the tab side-effects directly). - if (this._learningTab !== tab) { this._learningTab = tab; this._applyLearningTab(); } - } else { - this._learningTab = tab; // applyView opens the right tab after it mounts. - } } else if (r.view === 'agents') { if (this._agentsRoot) { // agents view already mounted (possibly hidden): open/close in place. @@ -650,17 +549,13 @@ runsOpen: true, runsQuery: '', facets: { status: [], kind: [], agent: [], repo: [] }, openFacet: null, oneShotsExpanded: false, oneShotLimit: 6, selectedRunId: null, hoverRun: null, listLoading: true, listError: false, - // Chat: true when any open thread has unread @mentions (drives the nav - // attention dot). Seeded by a light fetch in componentDidMount and kept live - // by the Chat view's poll. - chatAttn: false, // Persistent top bar: daemon liveness for the "daemon · up … · ● LIVE" chip. // daemonUp starts true because this page is served over HTTP by a live process; // the seed fetch (_navSeed) corrects it within the first cycle and keeps it live. daemonUp: true, daemonStartedAt: 0, daemonVersion: '', buildSkew: '', buildSkewDismissed: '', // Nav "needs you" amber dots (repurposed from the old you-are-here dot). Each is // seeded once on load (_navSeed), piggybacks the matching view's poll while open, - // and re-seeds every 60s. chatAttn (above) is the Chat item's flag. + // and re-seeds every 60s. healthAttn: false, learningAttn: false, pipelinesAttn: false, workflowsAttn: false, tasksAttn: false, attnAttn: false, // Mobile: the "More" bottom sheet (Galaxy/Charts/Learning). Transient, not persisted. moreOpen: false, @@ -726,7 +621,6 @@ if (this.state.view === 'agents') { this._agApplyMobileClass(); this.renderAgentsPane(true); } if (this.state.view === 'org' && this._orgData) { this._orgForceFitToken = (this._orgForceFitToken || 0) + 1; this.renderOrg(this._orgData); } if (this.state.view === 'pipelines' && this._plDetailName) { this._plLayout(); this._plUpdateScrollCue(); } - if (this.state.view === 'chat') this._chatRerender(); if (this.state.view === 'charts' && this._chartsLoaded) this.renderCharts(false); if (this.state.view === 'overview' && this._overviewData) this.renderOverview(this._overviewData); if (this.state.view === 'tasks' && this._tasksData) this.renderTasks(this._tasksData); @@ -738,19 +632,6 @@ const gr = this._galaxyGraphEl.getBoundingClientRect(); this._galaxyGraph.width(gr.width).height(gr.height); } - // Learning/Knowledge: the second force-graph re-fits to the post-dock width. - if (this.state.view === 'brain' && this._knowGraph && this._knowGraphEl) { - if (this._brainView === 'changelog') { this._brainRender(); return; } - // Apply the mobile List/Graph choice first. Re-fit whenever the graph is - // actually visible (desktop, fallback mobile, or explicit mobile Graph). - this._knowApplyMobile(); - if (this._knowGraphEl.style.display !== 'none') { - const kr = this._knowGraphEl.getBoundingClientRect(); - this._knowGraph.width(kr.width).height(kr.height); - // Re-dock changed the container width, so recompute the bands and re-settle. - this._knowRelayout(); - } - } }; if (this.state.isMobile !== m) this.setState({ isMobile: m }, after); else after(); @@ -772,9 +653,6 @@ // poll the run list so newly-created / state-changed runs surface live // (the selected run's graph already streams via SSE); background refresh. this._runsPoll = setInterval(() => this.loadRuns(), 15000); - // Seed the Chat nav attention dot from a one-off /api/chat/threads fetch so it - // reflects unread mentions before the user first opens the Chat view. - this.loadChatAttn(); // Seed the persistent top bar (daemon liveness) + the needs-you nav dots // (health/pipelines/learning/attention) from a light batch fetch, then re-seed // every 60s so the background stays live without adding per-view polls. @@ -786,8 +664,6 @@ clearInterval(this._runsPoll); clearInterval(this._navSeedTimer); clearTimeout(this._loadTO); - clearTimeout(this._brainLiveTimer); - clearTimeout(this._brainSearchTimer); this.stopGalaxyPoll(); this.stopJobsPoll(); this.stopAgentsPoll(); @@ -797,13 +673,9 @@ this.stopConfigPoll(); this.stopAttentionPoll(); this.stopSkillsPoll(); - this.stopKnowledgePoll(); - this._brainStopPoll(); this.stopPipelinesPoll(); this.stopPipelineRunPoll(); this.stopPipelineDetailPoll(); - this.stopChatPoll(); - this.stopChatThreadPoll(); this.stopWorkflowPoll(); this.stopOverviewPoll(); this.stopTasksPoll(); @@ -822,13 +694,9 @@ try { document.removeEventListener('keydown', this._orgKeydown); } catch (e) {} try { document.removeEventListener('keydown', this._healthKeydown); } catch (e) {} try { document.removeEventListener('keydown', this._attentionKeydown); } catch (e) {} - try { document.removeEventListener('keydown', this._learningKeydown); } catch (e) {} - try { document.removeEventListener('click', this._brainDocClick); } catch (e) {} try { document.removeEventListener('keydown', this._pipelinesKeydown); } catch (e) {} - try { document.removeEventListener('keydown', this._chatKeydown); } catch (e) {} try { document.removeEventListener('keydown', this._workflowKeydown); } catch (e) {} try { document.removeEventListener('keydown', this._tasksKeydown); } catch (e) {} - try { window.removeEventListener('resize', this._knowResize); } catch (e) {} try { if (this._orgReactRoot) this._orgReactRoot.unmount(); } catch (e) {} try { if (this._galaxyRoot) this._galaxyRoot.remove(); } catch (e) {} try { if (this._jobsRoot) this._jobsRoot.remove(); } catch (e) {} @@ -840,7 +708,6 @@ try { if (this._attentionRoot) this._attentionRoot.remove(); } catch (e) {} try { if (this._learningRoot) this._learningRoot.remove(); } catch (e) {} try { if (this._pipelinesRoot) this._pipelinesRoot.remove(); } catch (e) {} - try { if (this._chatRoot) this._chatRoot.remove(); } catch (e) {} try { if (this._workflowRoot) this._workflowRoot.remove(); } catch (e) {} try { if (this._workflowStrip) this._workflowStrip.remove(); } catch (e) {} try { if (this._overviewRoot) this._overviewRoot.remove(); } catch (e) {} @@ -975,17 +842,10 @@ else if (view === 'config') this.fetchConfig(true); else if (view === 'attention') this.fetchAttention(true); else if (view === 'learning') this.fetchSkills(true); - else if (view === 'brain') { - if (this._brainView === 'changelog') this._brainFetchNewest(true); - else this.fetchKnowledge(true); - } else if (view === 'pipelines') { this.fetchPipelines(true); if (this._plDetailName) this.fetchPipelineDetailData(this._plDetailName, true); if (this._plDetailName && this._plSelectedRun) this.fetchPipelineRun(this._plSelectedRun, true); - } else if (view === 'chat') { - this.fetchChatThreads(true); - if (this._chatSelected) this.fetchChatThread(this._chatSelected, true); } else if (view === 'graph') { this.loadState(); this.loadRuns(); @@ -1025,9 +885,7 @@ health: ['#health-root .hl-body'], config: ['#config-root .cfg-scroll'], learning: ['#learning-root #lr-skills'], - brain: ['#learning-root #lr-know-mobile', '#learning-root .bc-feed'], pipelines: ['#pipelines-root .pl-list-scroll', '#pipelines-root .pl-main-body'], - chat: ['#chat-root .ch-list', '#chat-root .cd-body'], graph: ['.gm-runs-list'] }; return selectors[this.state.view] || []; @@ -1228,7 +1086,7 @@ root.style.display = 'flex'; this.startJobsPoll(); this.fetchJobs(); - // Deep-link intent (a job chip clicked from the Chat view): open that job's + // Deep-link intent (a job chip clicked from Agents): open that job's // detail once the view is mounted. openJobsDetail fetches /api/job/ // independently, so it works even before /api/jobs resolves. if (this._pendingJobDetail) { @@ -1312,19 +1170,15 @@ this.stopAttentionPoll(); if (this._attentionRoot) this._attentionRoot.style.display = 'none'; } - // Learning and Brain share one overlay. Brain selects the existing Knowledge - // graph branch; Learning is the single Skills surface. - if (v === 'learning' || v === 'brain') { - this._learningTab = v === 'brain' ? 'knowledge' : 'skills'; + // Learning overlay: the Skills surface (agent-template evolution). Same + // body-appended overlay pattern as galaxy/jobs/agents/charts/health. + if (v === 'learning') { const root = this.ensureLearningDom(); root.style.display = 'flex'; - this._applyLearningTab(); + this.startSkillsPoll(); + this.fetchSkills(false); } else { this.stopSkillsPoll(); - this.stopKnowledgePoll(); - this._brainStopPoll(); - clearTimeout(this._brainSearchTimer); this._brainSearchTimer = null; - try { if (this._knowGraph && this._knowGraph.pauseAnimation) this._knowGraph.pauseAnimation(); } catch (e) {} if (this._learningRoot) this._learningRoot.style.display = 'none'; } // Pipelines overlay (declared pipelines list + run detail + hand-rolled stage DAG). @@ -1351,27 +1205,6 @@ this.stopPipelineDetailPoll(); if (this._pipelinesRoot) this._pipelinesRoot.style.display = 'none'; } - // Chat overlay (repo-scoped agent threads list + a slide-in message history). - if (v === 'chat') { - const root = this.ensureChatDom(); - root.style.display = 'grid'; - this._chatLayout(); - this.startChatPoll(); - this.fetchChatThreads(false); - // Deep-link intent (/chat/): open the thread once the list loads - // (fetchChatThreads completes any pending open). If already cached, open now - // and restart the thread poll for an already-open detail. - if (this._pendingChatThread && this._chatByID && this._chatByID[this._pendingChatThread]) { - const id = this._pendingChatThread; this._pendingChatThread = null; this.openChatThread(id); - } else if (this._chatSelected) { - this.fetchChatThread(this._chatSelected, false); - this.startChatThreadPoll(); - } - } else { - this.stopChatPoll(); - this.stopChatThreadPoll(); - if (this._chatRoot) this._chatRoot.style.display = 'none'; - } this._queuePullToRefreshSync(); } @@ -2967,13 +2800,11 @@ showAgents = () => { this.setState({ view: 'agents' }); this._navRoute('agents', { agent: this._agentsSelected || undefined }); }; showOrg = () => { this.setState({ view: 'org' }); this._navRoute('org'); }; showCharts = () => { this.setState({ view: 'charts' }); this._navRoute('charts'); }; - showBrain = () => { this._learningTab = 'knowledge'; this.setState({ view: 'brain' }); this._navRoute('brain'); }; showHealth = () => { this.setState({ view: 'health' }); this._navRoute('health'); }; showConfig = () => { this.setState({ view: 'config' }); this._navRoute('config'); }; showAttention = () => { this.setState({ view: 'attention' }); this._navRoute('attention'); }; - showLearning = () => { this._learningTab = 'skills'; this.setState({ view: 'learning' }); this._navRoute('learning', { tab: 'skills' }); }; + showLearning = () => { this.setState({ view: 'learning' }); this._navRoute('learning'); }; showPipelines = () => { this.setState({ view: 'pipelines' }); this._navRoute('pipelines', { name: this._plDetailName || undefined }); }; - showChat = () => { this.setState({ view: 'chat' }); this._navRoute('chat', { name: this._chatSelected || undefined }); }; startJobsPoll() { if (this._jobsPoll) return; @@ -5973,10 +5804,6 @@ "#config-root .cfg-runtime.codex{color:#9ad9ff;border-color:rgba(110,198,255,.27);background:rgba(110,198,255,.08)}", "#config-root .cfg-runtime.kimi{color:#e8c58a;border-color:rgba(224,175,104,.3);background:rgba(224,175,104,.08)}", "#config-root .cfg-runtime.shell{color:#9299b8;border-color:rgba(146,153,184,.24);background:rgba(146,153,184,.06)}", - "#config-root .cfg-bool{display:inline-flex;align-items:center;gap:6px;color:#68709a;font:9px 'JetBrains Mono',monospace}", - "#config-root .cfg-bool i{width:6px;height:6px;border-radius:50%;background:#4f567c;box-shadow:none}", - "#config-root .cfg-bool.on{color:#9baa82}", - "#config-root .cfg-bool.on i{background:#9ece6a;box-shadow:0 0 6px rgba(158,206,106,.45)}", "#config-root .cfg-agent-cards{display:none}", "#config-root .cfg-trust{display:flex;flex-direction:column;gap:9px;padding-top:15px;border-top:1px solid rgba(160,168,220,.08);color:#50577e;font:9.5px 'JetBrains Mono',monospace}", "#config-root .cfg-trust-line{display:flex;align-items:center;gap:8px;flex-wrap:wrap}", @@ -6206,13 +6033,12 @@ return [a.name, a.runtime, a.model, a.autonomy_policy].concat(Array.isArray(a.capabilities) ? a.capabilities : []).join(' ').toLowerCase().indexOf(aq) >= 0; }); if (agents.length) { - const id = this._configSlug('agents'), memoryN = agents.filter(a => a.memory).length, autoN = agents.filter(a => a.chat_autorespond).length; + const id = this._configSlug('agents'); anchors.push({ id: id, label: 'Per-agent', count: agents.length }); const rt = a => { const runtime = String(a.runtime || 'shell').toLowerCase(), cls = /claude/.test(runtime) ? 'claude' : /codex/.test(runtime) ? 'codex' : /kimi/.test(runtime) ? 'kimi' : 'shell'; return '' + esc(a.runtime || 'shell') + ''; }; - const bool = (v, label) => '' + label + ''; - const trs = agents.map(a => '' + esc(a.name) + '' + rt(a) + '' + bool(!!a.memory, '') + '' + bool(!!a.chat_autorespond, '') + '' + esc((Array.isArray(a.capabilities) ? a.capabilities : []).join(', ') || '-') + '' + esc(a.autonomy_policy || '-') + '' + esc(a.max_background == null ? '-' : a.max_background) + '' + esc(a.model || '-') + '').join(''); - const cards = agents.map(a => '
' + esc(a.name) + '' + rt(a) + '
' + bool(!!a.memory, 'mem') + bool(!!a.chat_autorespond, 'ar') + '' + esc(a.model || 'default') + '
').join(''); - out.push('
Per-agent overrides
' + trs + '
AgentRuntimeMemoryAuto-respCapabilitiesPolicyMax bgModel
' + cards + '
'); + const trs = agents.map(a => '' + esc(a.name) + '' + rt(a) + '' + esc((Array.isArray(a.capabilities) ? a.capabilities : []).join(', ') || '-') + '' + esc(a.autonomy_policy || '-') + '' + esc(a.max_background == null ? '-' : a.max_background) + '' + esc(a.model || '-') + '').join(''); + const cards = agents.map(a => '
' + esc(a.name) + '' + rt(a) + '
' + esc(a.model || 'default') + '
').join(''); + out.push('
Per-agent overrides
' + trs + '
AgentRuntimeCapabilitiesPolicyMax bgModel
' + cards + '
'); } const unknown = (Array.isArray(data.unknown_keys) ? data.unknown_keys : []).filter(k => !q || String(k).toLowerCase().indexOf(q) >= 0); if (unknown.length) anchors.push({ id: this._configSlug('unknown'), label: 'Unknown', count: unknown.length }); @@ -6227,693 +6053,20 @@ } // ============================================================ - // Learning page. Body-appended, position:fixed overlay (same pattern as - // galaxy/jobs/agents/charts/health). Two sub-tabs, each polled every 12s with - // a change-signature skip: - // Skills -> /api/learning/skills : the SkillOpt evolution table. - // Knowledge -> /api/learning/knowledge : a SECOND force-graph instance (the - // galaxy overlay is untouched) of the memory brain — enrolled - // agents, their facts and owner/category/supersede edges, with - // the proven custom screen-space hit-testing + pinned float. + // Learning page: the Skills surface over /api/learning/skills — the agent + // template evolution table (version history, current version, pending + // candidates). Body-appended, position:fixed overlay (same pattern as + // galaxy/jobs/agents/charts/health), polled every 12s with a + // change-signature skip. // ============================================================ startSkillsPoll() { if (this._skillsPoll) return; this._skillsPoll = setInterval(() => { - if (this.state.view !== 'learning' || this._learningTab !== 'skills') return; + if (this.state.view !== 'learning') return; this.fetchSkills(true); }, 12000); } stopSkillsPoll() { try { clearInterval(this._skillsPoll); } catch (e) {} this._skillsPoll = null; } - startKnowledgePoll() { - if (this._knowPoll) return; - this._knowPoll = setInterval(() => { - if (this.state.view !== 'brain' || this._brainView === 'changelog' || !this._knowGraph) return; - this.fetchKnowledge(true); - }, 12000); - } - stopKnowledgePoll() { try { clearInterval(this._knowPoll); } catch (e) {} this._knowPoll = null; } - _brainStartPoll() { - if (this._brainPoll) return; - this._brainPoll = setInterval(() => { - if (this.state.view === 'brain' && this._brainView === 'changelog') this._brainFetchNewest(false); - }, 12000); - } - _brainStopPoll() { try { clearInterval(this._brainPoll); } catch (e) {} this._brainPoll = null; } - - // Switch the active sub-tab. A tab switch is a pushState (URL changes - // /learning/skills <-> /learning/knowledge) so back/forward crosses it. - switchLearningTab(tab) { - if (tab === 'knowledge') { this.showBrain(); return; } - if (tab !== 'skills') return; - if (this._learningTab === tab) return; - this._learningTab = tab; - this._navRoute('learning', { tab: tab }); // pushState - this._applyLearningTab(); - } - // Apply the current sub-tab: toggle the chips + container visibility, and start - // exactly the visible tab's poll (stopping the other). Called by applyView on - // entry, switchLearningTab on a tab click, and _onPopState on back/forward. - _applyLearningTab() { - if (!this._learningRoot) return; - const tab = this._learningTab || 'skills'; - const root = this._learningRoot; - root.querySelectorAll('.lr-chip').forEach(b => b.classList.toggle('on', b.getAttribute('data-tab') === tab)); - const skEl = root.querySelector('#lr-skills'); - const knEl = root.querySelector('#lr-knowledge'); - if (skEl) skEl.style.display = tab === 'skills' ? 'block' : 'none'; - if (knEl) knEl.style.display = tab === 'knowledge' ? 'block' : 'none'; - root.classList.toggle('brain', tab === 'knowledge'); - try { document.title = this._routeTitle(tab === 'knowledge' ? 'brain' : 'learning', { tab: tab }); } catch (e) {} - this.setState({}); // refresh the top-bar breadcrumb - if (tab === 'skills') { - this.stopKnowledgePoll(); - this._brainStopPoll(); - try { if (this._knowGraph && this._knowGraph.pauseAnimation) this._knowGraph.pauseAnimation(); } catch (e) {} - this.startSkillsPoll(); - this.fetchSkills(false); - } else { - this.stopSkillsPoll(); - this.initKnowledgeGraph(); - this._applyBrainView(false); - } - } - - _applyBrainView(fromRoute) { - if (!this._learningRoot || this.state.view !== 'brain') return; - const changelog = this._brainView === 'changelog'; - const graph = this._learningRoot.querySelector('#lr-know-graph'); - const loading = this._learningRoot.querySelector('#lr-know-loading'); - const legend = this._learningRoot.querySelector('#lr-know-legend'); - const empty = this._learningRoot.querySelector('#lr-empty'); - const mobile = this._learningRoot.querySelector('#lr-know-mobile'); - const detail = this._learningRoot.querySelector('.lr-detail'); - const log = this._learningRoot.querySelector('#lr-changelog'); - const chrome = this._learningRoot.querySelector('#lr-know-chrome'); - this._learningRoot.classList.toggle('brain-changelog', changelog); - if (chrome) chrome.classList.toggle('changelog', changelog); - if (log) log.style.display = changelog ? 'flex' : 'none'; - if (changelog) { - if (graph) graph.setAttribute('data-mobile-hidden', 'true'); - [graph, loading, legend, empty, mobile, detail].forEach(el => { if (el) el.style.display = 'none'; }); - } - else { - if (graph) graph.style.display = ''; - if (loading) loading.style.display = this._knowRaw ? 'none' : 'flex'; - if (legend) legend.style.display = ''; - if (empty) empty.style.display = this._knowEmpty ? 'block' : 'none'; - if (detail) detail.style.display = 'flex'; - } - this._brainSetGraphControlsVisible(!changelog); - const buttons = chrome ? chrome.querySelectorAll('[data-brain-view]') : []; - buttons.forEach(b => { const on = b.getAttribute('data-brain-view') === (changelog ? 'changelog' : 'graph'); b.classList.toggle('on', on); b.setAttribute('aria-pressed', on ? 'true' : 'false'); }); - if (changelog) { - this.stopKnowledgePoll(); - try { if (this._knowGraph && this._knowGraph.pauseAnimation) this._knowGraph.pauseAnimation(); } catch (e) {} - this._brainStartPoll(); - if (!this._brainLoaded) this._brainFetchPage('', false); - else { - if (this._brainBiographyKey && !this._brainBiographyFact) this._brainResolveBiography(); - this._brainRender(); - } - this._brainSyncStats(); - } else { - this._brainStopPoll(); - this._brainSheetOpen = false; - this._brainCloseMenus(); - try { if (this._knowGraph && this._knowGraph.resumeAnimation) this._knowGraph.resumeAnimation(); } catch (e) {} - this.startKnowledgePoll(); - this._knowChromeMode = ''; - this._knowSyncChrome(this._knowBuilt || { agentCount: 0, factCount: 0, factLinkCount: 0 }); - try { this._knowApplyMobile(); } catch (e) {} - } - } - - _brainSetGraphControlsVisible(show) { - const chrome = this._learningRoot && this._learningRoot.querySelector('#lr-know-chrome'); - if (!chrome) return; - const count = chrome.querySelector('#lr-know-count'); - ['#lr-know-linkcount', '#lr-know-controls'].forEach(sel => { - let el = chrome.querySelector(sel) || this[sel === '#lr-know-linkcount' ? '_brainLinkChip' : '_brainGraphControls']; - if (!el) return; - if (show) { - if (!el.parentNode) chrome.appendChild(el); - } else if (el.parentNode) { - if (sel === '#lr-know-linkcount') this._brainLinkChip = el; else this._brainGraphControls = el; - el.remove(); - } - }); - } - - _brainSetView(view, push) { - view = view === 'changelog' ? 'changelog' : 'graph'; - if (this._brainView === view) return; - this._brainView = view; - if (view === 'graph') { - this._brainBiographyKey = ''; - clearTimeout(this._brainSearchTimer); this._brainSearchTimer = null; - } - this._applyBrainView(false); - this._navRoute('brain', { brain: this._brainRouteState() }, push === false); - } - - _brainKindMap() { - return { - created: { label: 'created', color: '#7dcfff' }, updated: { label: 'updated', color: '#7aa2f7' }, - retired: { label: 'retired', color: '#e0697f' }, unretired: { label: 'unretired', color: '#73daca' }, - superseded: { label: 'superseded', color: '#8b8fc0' }, confirmed: { label: 'confirmed', color: '#9ece6a' }, - promoted: { label: 'promoted', color: '#9ece6a' }, ingested: { label: 'ingested', color: '#8a93b3' }, - cluster_recompute: { label: 'cluster_recompute', color: '#bb9af7' }, cluster_rename: { label: 'cluster_rename', color: '#bb9af7' } - }; - } - - _brainNormalizeEvent(raw) { - const e = raw && typeof raw === 'object' ? Object.assign({}, raw) : {}; - let detail = e.detail; - if (typeof detail === 'string') { try { detail = JSON.parse(detail); } catch (err) { detail = {}; } } - e.detail = detail && typeof detail === 'object' ? detail : {}; - e.id = e.id == null ? '' : e.id; - e.memoryId = e.memoryId != null ? e.memoryId : (e.memory_id != null ? e.memory_id : null); - e.ownerKind = e.ownerKind || e.owner_kind || ''; - e.ownerRef = e.ownerRef || e.owner_ref || ''; - e.backfilled = !!(e.backfilled || e.detail.backfilled); - return e; - } - - _brainStoreOlderCursor(next) { - this._brainOlderCursor = next || 0; - this._brainExhausted = !next; - this._brainCursorQuarantined = false; - } - - _brainFetchNewest(live) { return this._brainFetchPage('', !!live); } - _brainFetchPage(cursor, live) { - const older = cursor !== '' && cursor != null; - if (this._brainLoading) return this._brainLoading; - this._brainLoadingCursor = older ? String(cursor) : ''; - const url = '/api/brain/events?limit=60' + (older ? '&cursor=' + encodeURIComponent(cursor) : ''); - const request = fetch(url, { cache: 'no-store' }).then(async r => { - if (r.status === 400 && older) { - this._brainEvents = []; this._brainEventIds = {}; this._brainOlderCursor = 0; - this._brainNewestEventId = 0; this._brainExhausted = false; this._brainLoaded = false; - return { stale: true }; - } - if (!r.ok) throw new Error('HTTP ' + r.status); - return r.json(); - }).then(data => { - if (data && data.stale) { this._brainLoading = null; return this._brainFetchPage('', false); } - const incoming = (data && Array.isArray(data.events) ? data.events : []).map(e => this._brainNormalizeEvent(e)); - const known = this._brainEventIds || {}; - const fresh = incoming.filter(e => !known[String(e.id)]); - if (!this._brainLoaded) { - this._brainEvents = incoming; - this._brainEventIds = {}; - incoming.forEach(e => { this._brainEventIds[String(e.id)] = true; }); - this._brainNewestEventId = incoming.length ? incoming[0].id : 0; - this._brainStoreOlderCursor(data && data.nextCursor); - if (!this._brainOpenInitialized && !this._brainBiographyKey && incoming.length) { - this._brainOpenId = String(incoming[0].id); this._brainOpenInitialized = true; - if (incoming[0].kind === 'updated' && incoming[0].memoryId != null) setTimeout(() => this._brainEnsureFact(incoming[0].memoryId), 0); - } - } else if (older) { - fresh.forEach(e => { known[String(e.id)] = true; }); - this._brainEvents = (this._brainEvents || []).concat(fresh); - this._brainStoreOlderCursor(data && data.nextCursor); - } else { - fresh.forEach(e => { known[String(e.id)] = true; }); - this._brainEvents = fresh.concat(this._brainEvents || []); - if (incoming.length) this._brainNewestEventId = incoming[0].id; - if (live && fresh.length) { - if (!this._brainLiveIds) this._brainLiveIds = {}; - fresh.forEach(e => { this._brainLiveIds[String(e.id)] = true; }); - clearTimeout(this._brainLiveTimer); - this._brainLiveTimer = setTimeout(() => { this._brainLiveIds = {}; this._brainRender(); }, 3600); - } - } - this._brainEvents = (this._brainEvents || []).slice().sort((a, b) => { - const dt = new Date(b.at || 0).getTime() - new Date(a.at || 0).getTime(); - if (dt) return dt; - return Number(b.id || 0) - Number(a.id || 0); - }); - this._brainTotal = Number(data && data.total != null ? data.total : this._brainEvents.length) || 0; - this._brainLoaded = true; this._brainError = ''; - this._brainRender(); - if (this._brainBiographyKey) setTimeout(() => this._brainResolveBiography(), 0); - return data; - }).catch(err => { - if (!this._brainLoaded) { this._brainLoaded = true; this._brainError = err && err.message ? err.message : 'request failed'; this._brainRender(); } - return null; - }).finally(() => { - if (this._brainLoading === request) { this._brainLoading = null; this._brainLoadingCursor = ''; } - }); - this._brainLoading = request; - return request; - } - - _brainLoadOlder() { - if (this._brainLoading) { - const pending = this._brainLoading, loadingOlder = !!this._brainLoadingCursor; - return pending.then(() => loadingOlder ? null : this._brainLoadOlder()); - } - if (this._brainExhausted || !this._brainOlderCursor) return Promise.resolve(null); - return this._brainFetchPage(this._brainOlderCursor, false); - } - - _brainLoadBiographyHistory(batch) { - batch = batch || 0; - if (!this._brainBiographyKey || this._brainExhausted || !this._brainOlderCursor || batch >= 100) return Promise.resolve(); - const cursor = String(this._brainOlderCursor); - return this._brainLoadOlder().then(() => { - if (!this._brainBiographyKey || (String(this._brainOlderCursor) === cursor && !this._brainExhausted)) return null; - return this._brainLoadBiographyHistory(batch + 1); - }); - } - - _brainEnsureFact(id) { - if (id == null || id === '') return Promise.resolve(null); - const key = String(id); - if (!this._brainFacts) this._brainFacts = {}; - if (Object.prototype.hasOwnProperty.call(this._brainFacts, key)) return Promise.resolve(this._brainFacts[key]); - if (!this._brainFactRequests) this._brainFactRequests = {}; - if (this._brainFactRequests[key]) return this._brainFactRequests[key]; - const req = fetch('/api/brain/fact?id=' + encodeURIComponent(id), { cache: 'no-store' }) - .then(r => { if (r.status === 404) return null; if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }) - .then(fact => { this._brainFacts[key] = fact && typeof fact === 'object' ? fact : null; this._brainRender(); return this._brainFacts[key]; }) - .catch(() => { this._brainFacts[key] = null; this._brainRender(); return null; }) - .finally(() => { delete this._brainFactRequests[key]; }); - this._brainFactRequests[key] = req; - return req; - } - - _brainResolveBiography() { - const key = this._brainBiographyKey; - if (!key) return; - const events = this._brainEvents || []; - const match = events.find(e => e.key === key && e.memoryId != null); - if (match) { - this._brainBiographyMemoryId = match.memoryId; - this._brainEnsureFact(match.memoryId).then(fact => { - if (this._brainBiographyKey === key) { this._brainBiographyFact = fact; this._brainRender(); } - }); - } - if (!this._brainExhausted && !this._brainBiographyLoading) { - this._brainBiographyLoading = this._brainLoadBiographyHistory(0).finally(() => { - this._brainBiographyLoading = null; - if (this._brainBiographyKey === key) this._brainResolveBiography(); - }); - } - } - - _brainOpenBiography(key, memoryId, replace) { - if (!key) return; - this._brainBiographyKey = key; - this._brainBiographyMemoryId = memoryId != null && memoryId !== '' ? memoryId : null; - this._brainBiographyFact = this._brainBiographyMemoryId != null && this._brainFacts ? this._brainFacts[String(this._brainBiographyMemoryId)] : null; - this._brainOpenId = ''; this._brainSheetOpen = false; this._brainCloseMenus(); - this._navRoute('brain', { brain: this._brainRouteState() }, !!replace); - this._brainRender(); - if (this._brainBiographyMemoryId != null) this._brainEnsureFact(this._brainBiographyMemoryId).then(f => { if (this._brainBiographyKey === key) { this._brainBiographyFact = f; this._brainRender(); } }); - this._brainResolveBiography(); - } - - _brainExitBiography() { - this._brainBiographyKey = ''; this._brainBiographyMemoryId = null; this._brainBiographyFact = null; this._brainOpenId = ''; - this._navRoute('brain', { brain: this._brainRouteState() }); - this._brainRender(); - } - - _brainSyncRoute() { this._navRoute('brain', { brain: this._brainRouteState() }, true); } - _brainCloseMenus() { this._brainMenu = ''; } - - _brainClearFilters() { - this._brainFilters = { kinds: [], repo: '', actor: '', q: '' }; - this._brainCloseMenus(); this._brainSyncRoute(); this._brainRender(); - } - - _brainSyncStats() { - if (!this._learningRoot || this._brainView !== 'changelog') return; - const el = this._learningRoot.querySelector('#lr-know-count'); if (!el) return; - const total = this._brainTotal != null ? this._brainTotal : (this._brainEvents || []).length; - const active = this._knowBuilt && this._knowBuilt.factCount != null ? this._knowBuilt.factCount : 0; - el.innerHTML = '' + total + ' event' + (total === 1 ? '' : 's') + ' · ' + active + ' active fact' + (active === 1 ? '' : 's'); - } - - _brainAbsTime(at) { - const d = new Date(at || 0), p = n => String(n).padStart(2, '0'); - if (Number.isNaN(d.getTime())) return 'unknown time'; - return d.getUTCFullYear() + '-' + p(d.getUTCMonth() + 1) + '-' + p(d.getUTCDate()) + ' ' + p(d.getUTCHours()) + ':' + p(d.getUTCMinutes()) + ':' + p(d.getUTCSeconds()) + ' UTC'; - } - _brainRelTime(at) { - const ms = Math.max(0, Date.now() - new Date(at || 0).getTime()), s = Math.floor(ms / 1000); - if (s < 60) return 'now'; if (s < 3600) return Math.floor(s / 60) + 'm'; - if (s < 86400) return Math.floor(s / 3600) + 'h'; return Math.floor(s / 86400) + 'd'; - } - _brainDayKey(at) { - const d = new Date(at || 0), p = n => String(n).padStart(2, '0'); - return d.getUTCFullYear() + '-' + p(d.getUTCMonth() + 1) + '-' + p(d.getUTCDate()); - } - _brainDayLabel(key) { - const now = new Date(), p = n => String(n).padStart(2, '0'); - const today = now.getUTCFullYear() + '-' + p(now.getUTCMonth() + 1) + '-' + p(now.getUTCDate()); - const y = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 1)); - const yesterday = y.getUTCFullYear() + '-' + p(y.getUTCMonth() + 1) + '-' + p(y.getUTCDate()); - return key === today ? 'Today' : (key === yesterday ? 'Yesterday' : key); - } - _brainShort(value, max) { - const s = String(value || ''), n = max || 34; return s.length > n ? s.slice(0, n - 1) + '…' : s; - } - - _brainSentence(e) { - const d = e.detail || {}, actor = this._brainShort(e.actor, 34); - if (e.isBurst) return String(e.kind || 'changed').replace(/_/g, ' ') + ' ' + e.count + ' facts in one journal burst'; - switch (e.kind) { - case 'created': return e.backfilled ? 'created · backfilled from history' : 'created by ' + (actor || 'unknown actor'); - case 'updated': return 'content updated by ' + (actor || 'unknown actor'); - case 'retired': return 'retired' + (d.reason ? ' · ' + this._brainShort(d.reason, 90) : ' by ' + actor); - case 'unretired': return 'unretired by ' + (actor || 'unknown actor'); - case 'superseded': { - const sid = d.superseded_by, successorKey = sid == null ? '' : String(sid); - const resolved = !!(successorKey && this._brainFacts && Object.prototype.hasOwnProperty.call(this._brainFacts, successorKey)); - const successor = resolved ? this._brainFacts[successorKey] : null; - return 'superseded by ' + (successor && successor.key ? successor.key : (sid != null ? 'memory ' + sid + (resolved ? ' (no longer available)' : '') : 'a successor fact')); - } - case 'confirmed': return 'confirmed by ' + (actor || 'unknown actor'); - case 'promoted': return 'promoted from ' + ((d.from_owner_kind || 'owner') + (d.from_owner_ref ? ':' + d.from_owner_ref : '')); - case 'ingested': return d.source ? 'ingested from ' + d.source : 'ingested by ' + (actor || 'unknown actor'); - case 'cluster_rename': return 'cluster renamed' + (d.previous_label ? ' from ' + d.previous_label : '') + (d.label ? ' → ' + d.label : ''); - case 'cluster_recompute': return 'cluster recomputed · ' + (Array.isArray(d.clusters) ? d.clusters.length : 0) + ' clusters changed'; - default: return String(e.kind || 'event').replace(/_/g, ' '); - } - } - - _brainLineDiff(before, after) { - const a = String(before == null ? '' : before).split('\n'), b = String(after == null ? '' : after).split('\n'); - let prefix = 0; - while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++; - let ai = a.length - 1, bi = b.length - 1; - while (ai >= prefix && bi >= prefix && a[ai] === b[bi]) { ai--; bi--; } - const line = (text, kind) => ({ text: text, kind: kind, gut: kind === 'del' ? '-' : (kind === 'add' ? '+' : ' ') }); - const left = a.map((v, i) => line(v, i >= prefix && i <= ai ? 'del' : 'same')); - const right = b.map((v, i) => line(v, i >= prefix && i <= bi ? 'add' : 'same')); - const unified = []; - for (let i = 0; i < prefix; i++) unified.push(line(a[i], 'same')); - for (let i = prefix; i <= ai; i++) unified.push(line(a[i], 'del')); - for (let i = prefix; i <= bi; i++) unified.push(line(b[i], 'add')); - for (let i = ai + 1; i < a.length; i++) unified.push(line(a[i], 'same')); - return { left: left, right: right, unified: unified }; - } - - _brainBurst(items) { - const out = []; - for (let i = 0; i < items.length;) { - const first = items[i], run = [first]; let j = i + 1; - const firstAt = new Date(first.at || 0).getTime(); - while (j < items.length) { - const next = items[j], nextAt = new Date(next.at || 0).getTime(); - if (next.kind !== first.kind || next.actor !== first.actor || Math.abs(firstAt - nextAt) > 60000) break; - run.push(next); j++; - } - if (run.length > 10) { - out.push({ - id: 'burst:' + String(run[0].id) + ':' + String(run[run.length - 1].id), at: run[0].at, - kind: first.kind, actor: first.actor, repo: first.repo || '', scope: first.scope || '', - detail: {}, isBurst: true, count: run.length, items: run, - backfilled: run.every(e => e.backfilled) - }); - } else out.push.apply(out, run); - i = j; - } - return out; - } - - _brainFilteredItems() { - const f = this._brainFilters || { kinds: [], repo: '', actor: '', q: '' }; - let raw = (this._brainEvents || []).slice(); - if (this._brainBiographyKey) return raw.filter(e => e.key === this._brainBiographyKey).sort((a, b) => new Date(a.at || 0) - new Date(b.at || 0)); - const q = String(f.q || '').trim().toLowerCase(); - const filtered = !!((f.kinds && f.kinds.length) || f.repo || f.actor || q); - if (f.kinds && f.kinds.length) raw = raw.filter(e => f.kinds.indexOf(e.kind) >= 0); - if (f.repo) raw = f.repo === '__general' ? raw.filter(e => !e.repo) : raw.filter(e => e.repo === f.repo); - if (f.actor) raw = raw.filter(e => e.actor === f.actor); - if (q) raw = raw.filter(e => String(e.key || '').toLowerCase().indexOf(q) >= 0); - return filtered ? raw : this._brainBurst(raw); - } - - _brainGroupDays(items) { - const groups = [], byDay = {}; - items.forEach(e => { - const key = this._brainDayKey(e.at); - if (!byDay[key]) { byDay[key] = { key: key, label: this._brainDayLabel(key), rows: [] }; groups.push(byDay[key]); } - byDay[key].rows.push(e); - byDay[key].count = (byDay[key].count || 0) + (e.isBurst ? e.count : 1); - }); - return groups; - } - - _brainLinesHtml(lines) { - const esc = v => this._galaxyEsc(v); - return (lines || []).map(line => '
' + esc(line.gut || ' ') + '' + esc(line.text) + '
').join(''); - } - - _brainMetaHtml(e) { - const esc = v => this._galaxyEsc(v), cells = [ - ['memory_id', e.memoryId != null ? e.memoryId : '-'], ['scope', e.scope || '-'], - ['actor', e.actor || '-'], ['at', this._brainAbsTime(e.at)] - ]; - return '
' + cells.map(c => '
' + esc(c[0]) + '' + esc(c[1]) + '
').join('') + '
'; - } - - _brainExpansionHtml(e) { - const esc = v => this._galaxyEsc(v), d = e.detail || {}; - if (e.isBurst) { - return '
' + esc(e.actor || 'actor') + ' ' + esc(e.kind) + ' ' + e.count + ' facts within one minute.
' + (e.items || []).map(x => '' + esc(x.key || ('memory ' + (x.memoryId != null ? x.memoryId : x.id))) + '').join('') + '
'; - } - let body = ''; - if (e.kind === 'updated') { - let before = d.before; - if (before == null) before = d.before_preview != null ? d.before_preview + (d.truncated ? '\n… preview truncated' : '') : (d.before_hash ? 'previous content hash: ' + d.before_hash : 'previous content was not captured'); - const key = e.memoryId == null ? '' : String(e.memoryId), has = !!(key && this._brainFacts && Object.prototype.hasOwnProperty.call(this._brainFacts, key)); - const current = has ? this._brainFacts[key] : null; - const after = current && current.content != null ? current.content : (has ? 'current fact is unavailable' : 'loading current fact…'); - const diff = this._brainLineDiff(before, after); - body += '
' + - '
before' + esc(this._brainAbsTime(e.at)) + '
' + this._brainLinesHtml(diff.left) + '
' + - '
after · currentlive
' + this._brainLinesHtml(diff.right) + '
' + - '
before → aftercurrent
' + this._brainLinesHtml(diff.unified) + '
'; - } else if (e.kind === 'retired') { - body += '
retirement reason
' + esc(d.reason || 'No reason recorded.') + '
' + (e.memoryId != null ? '
' : '') + '
'; - } else if (e.kind === 'superseded') { - const sid = d.superseded_by, successorKey = sid == null ? '' : String(sid); - const resolved = !!(successorKey && this._brainFacts && Object.prototype.hasOwnProperty.call(this._brainFacts, successorKey)); - const successor = resolved ? this._brainFacts[successorKey] : null; - body += '
This fact was superseded - its content was replaced by a newer fact.
successor' + - (successor && successor.key ? '' : '' + (sid != null ? 'memory ' + esc(sid) + (resolved ? ' (no longer available)' : ' · resolving…') : 'not recorded') + '') + '
'; - } else if (e.kind === 'cluster_rename') { - body += '
cluster rename
' + esc(d.previous_label || 'unlabeled') + ' → ' + esc(d.label || 'unlabeled') + '
' + esc(d.cluster_id || '') + '
'; - } else if (e.kind === 'cluster_recompute') { - const rows = Array.isArray(d.clusters) ? d.clusters : []; - body += '
recomputed clusters
' + rows.map(c => { const delta = Number(c.MemberCountDelta || 0); return '' + esc(c.Label || c.ClusterID || 'cluster') + ' ' + (delta > 0 ? '+' : '') + delta + ''; }).join('') + (rows.length ? '' : 'no member deltas recorded') + '
'; - } else if (e.kind === 'promoted') { - body += '
previous owner
' + esc((d.from_owner_kind || '-') + (d.from_owner_ref ? ':' + d.from_owner_ref : '')) + '
'; - } else if (e.kind === 'ingested') { - body += '
source
' + esc(d.source || ('ingested by ' + (e.actor || 'unknown actor'))) + '
'; - } - return '' + body + this._brainMetaHtml(e) + (e.memoryId != null ? '
' : ''); - } - - _brainEventHtml(e) { - const esc = v => this._galaxyEsc(v), km = this._brainKindMap(), info = km[e.kind] || { label: String(e.kind || 'event'), color: '#8b93ac' }; - const cluster = String(e.kind || '').indexOf('cluster_') === 0; - const color = e.kind === 'created' ? (e.repo ? '#7dcfff' : '#e0af68') : info.color; - let label = e.isBurst ? (e.actor || 'journal burst') : (e.key || ''); - if (cluster) label = (e.detail && (e.detail.label || e.detail.cluster_id)) || e.key || info.label; - const open = String(this._brainOpenId || '') === String(e.id), canBio = !e.isBurst && !cluster && !!e.key; - const live = this._brainLiveIds && this._brainLiveIds[String(e.id)]; - const keyHtml = canBio - ? '' - : '' + esc(label || info.label) + ''; - return '
' + - '
' + - '' + keyHtml + - '' + esc(this._brainSentence(e)) + '' + - (e.isBurst ? '' + e.count + ' facts' : '') + - (e.backfilled ? 'backfilled' : '') + - '' + - '' + esc(this._brainRelTime(e.at)) + '›
' + - (open ? '
' + this._brainExpansionHtml(e) + '
' : '') + '
'; - } - - _brainKindChipsHtml() { - const f = this._brainFilters || {}, active = Array.isArray(f.kinds) ? f.kinds : [], map = this._brainKindMap(), esc = v => this._galaxyEsc(v); - return '
kinds' + Object.keys(map).map(kind => { - const on = active.indexOf(kind) >= 0, info = map[kind]; - return ''; - }).join('') + (active.length ? '' : '') + '
'; - } - - _brainSelectHtml(type, options) { - const f = this._brainFilters || {}, value = f[type] || '', esc = v => this._galaxyEsc(v), open = this._brainMenu === type; - const label = !value ? (type === 'repo' ? 'all repos' : 'all actors') : (value === '__general' ? 'general facts' : value); - return '
' + - (open ? '
' + options.map(v => '').join('') + '
' : '') + '
'; - } - - _brainFilterControlsHtml(sheet) { - const f = this._brainFilters || {}, esc = v => this._galaxyEsc(v), events = this._brainEvents || []; - const repos = Array.from(new Set(events.map(e => e.repo || '__general'))).sort((a, b) => a === '__general' ? 1 : (b === '__general' ? -1 : a.localeCompare(b))); - const actors = Array.from(new Set(events.map(e => e.actor).filter(Boolean))).sort(); - const searchTarget = sheet ? 'sheet' : 'desktop'; - const search = ''; - const second = '
' + search + this._brainSelectHtml('repo', repos) + this._brainSelectHtml('actor', actors) + '
'; - if (sheet) return '
Filters
' + this._brainKindChipsHtml() + search + this._brainSelectHtml('repo', repos) + this._brainSelectHtml('actor', actors) + ''; - return '
' + this._brainKindChipsHtml() + second + '
'; - } - - _brainBiographyHtml(items) { - const esc = v => this._galaxyEsc(v), fact = this._brainBiographyFact, key = this._brainBiographyKey || ''; - let status = fact && fact.status ? fact.status : 'active'; - if (!fact && items.length) { - const last = items[items.length - 1]; - if (last.kind === 'retired') status = 'retired'; else if (last.kind === 'superseded') status = 'superseded'; - } - const color = status === 'retired' ? '#e0697f' : (status === 'superseded' ? '#8b8fc0' : '#9ece6a'); - let content = fact && fact.content != null ? fact.content : ''; - if (!content) content = this._brainBiographyLoading || (this._brainBiographyMemoryId != null && this._brainFactRequests && this._brainFactRequests[String(this._brainBiographyMemoryId)]) ? 'loading current fact…' : 'Current fact content is unavailable.'; - const repo = fact && fact.repo ? 'repo fact · ' + fact.repo : 'general fact'; - const scope = fact && fact.scope ? ' · ' + fact.scope : ''; - return '
' + esc(key) + '' + esc(status) + '' + esc(repo + scope) + '
' + esc(content) + '
' + esc(repo + scope) + ' · ' + items.length + ' event' + (items.length === 1 ? '' : 's') + ' · oldest first
'; - } - - _brainRender() { - if (!this._learningRoot || this._brainView !== 'changelog') return; - const host = this._learningRoot.querySelector('#lr-changelog'); if (!host) return; - const oldFeed = host.querySelector('.bc-feed'); - let anchor = null, anchorOffset = 0, wasTop = true; - if (oldFeed) { - wasTop = oldFeed.scrollTop < 24; - const fr = oldFeed.getBoundingClientRect(); - const candidates = oldFeed.querySelectorAll('[data-bc-anchor]'); - for (let i = 0; i < candidates.length; i++) { - const r = candidates[i].getBoundingClientRect(); - if (r.bottom > fr.top + 2) { anchor = candidates[i].getAttribute('data-bc-anchor'); anchorOffset = r.top - fr.top; break; } - } - } - const items = this._brainFilteredItems(), groups = this._brainGroupDays(items), bio = !!this._brainBiographyKey; - this._brainDisplayById = {}; - items.forEach(e => { this._brainDisplayById[String(e.id)] = e; }); - const expanded = this._brainDisplayById[String(this._brainOpenId || '')]; - if (expanded && expanded.kind === 'updated' && expanded.memoryId != null && !(this._brainFacts && Object.prototype.hasOwnProperty.call(this._brainFacts, String(expanded.memoryId)))) { - setTimeout(() => this._brainEnsureFact(expanded.memoryId), 0); - } - if (expanded && expanded.kind === 'superseded' && expanded.detail && expanded.detail.superseded_by != null && !(this._brainFacts && Object.prototype.hasOwnProperty.call(this._brainFacts, String(expanded.detail.superseded_by)))) { - setTimeout(() => this._brainEnsureFact(expanded.detail.superseded_by), 0); - } - const f = this._brainFilters || {}, filterCount = (f.kinds ? f.kinds.length : 0) + (f.repo ? 1 : 0) + (f.actor ? 1 : 0) + (f.q ? 1 : 0); - let feedHtml = ''; - if (!this._brainLoaded) { - feedHtml = '
≡Opening the journal

Brain changes will appear here.

'; - } else if (this._brainError) { - feedHtml = '
!Could not load the journal

' + this._galaxyEsc(this._brainError) + '

'; - } else if ((this._brainTotal || 0) === 0) { - feedHtml = '
□No events yet

The journal starts recording with the next brain change.

'; - } else if (!items.length) { - feedHtml = '
⌕' + (bio ? 'No events recorded for this fact' : 'No events match these filters') + '

' + (bio ? 'The selected fact is not present in the loaded journal.' : 'Try clearing a filter or widening your search.') + '

' + (!bio ? '' : '') + '
'; - } else { - feedHtml = groups.map(g => '
' + this._galaxyEsc(g.label) + '' + g.count + ' event' + (g.count === 1 ? '' : 's') + '
' + g.rows.map(e => this._brainEventHtml(e)).join('') + '
').join(''); - if (this._brainExhausted && !this._brainCursorQuarantined) feedHtml += '
beginning of the journal
'; - } - const mobile = !bio ? '
' : ''; - host.innerHTML = (!bio ? this._brainFilterControlsHtml(false) : '') + mobile + '
' + (bio ? this._brainBiographyHtml(items) : '') + '
' + feedHtml + '
' + (this._brainSheetOpen && !bio ? '
' + this._brainFilterControlsHtml(true) + '
' : ''); - const feed = host.querySelector('.bc-feed'); - if (feed) { - feed.addEventListener('scroll', () => { - if (!this._brainBiographyKey && feed.scrollTop + feed.clientHeight >= feed.scrollHeight - 180) this._brainLoadOlder(); - }, { passive: true }); - if (this._brainResetScroll || wasTop) feed.scrollTop = 0; - else if (anchor) { - const next = Array.from(feed.querySelectorAll('[data-bc-anchor]')).find(el => el.getAttribute('data-bc-anchor') === anchor); - if (next) { const fr = feed.getBoundingClientRect(); feed.scrollTop += next.getBoundingClientRect().top - fr.top - anchorOffset; } - } - if (!this._brainBiographyKey && !this._brainExhausted && feed.scrollHeight <= feed.clientHeight + 180) setTimeout(() => this._brainLoadOlder(), 0); - } - this._brainResetScroll = false; - this._brainSyncStats(); - } - - _brainToggleEvent(id) { - const item = this._brainDisplayById && this._brainDisplayById[String(id)]; - this._brainOpenId = String(this._brainOpenId || '') === String(id) ? '' : String(id); - if (item && this._brainOpenId) { - if (item.kind === 'updated' && item.memoryId != null) this._brainEnsureFact(item.memoryId); - if (item.kind === 'superseded' && item.detail && item.detail.superseded_by != null) this._brainEnsureFact(item.detail.superseded_by); - } - this._brainRender(); - } - - _brainViewInGraph(id) { - this._brainSetView('graph', true); - setTimeout(() => { try { this.selectKnowledgeFactById(id); } catch (e) {} }, 80); - } - - _brainHandleClick(e) { - const target = e.target; - const closedOutside = !!(this._brainMenu && !(target.closest && target.closest('.bc-select'))); - if (closedOutside) this._brainCloseMenus(); - const closeSheet = target.closest && target.closest('[data-bc-sheet-close]'); - if (closeSheet) { this._brainSheetOpen = false; this._brainCloseMenus(); this._brainRender(); return; } - const openSheet = target.closest && target.closest('[data-bc-sheet-open]'); - if (openSheet) { this._brainSheetOpen = true; this._brainCloseMenus(); this._brainRender(); return; } - const exit = target.closest && target.closest('[data-bc-bio-exit]'); - if (exit) { this._brainExitBiography(); return; } - const graph = target.closest && target.closest('[data-bc-graph]'); - if (graph) { this._brainViewInGraph(graph.getAttribute('data-bc-graph')); return; } - const successor = target.closest && target.closest('[data-bc-successor]'); - if (successor) { this._brainResetScroll = true; this._brainOpenBiography(decodeURIComponent(successor.getAttribute('data-bc-successor') || ''), successor.getAttribute('data-bc-memory')); return; } - const key = target.closest && target.closest('[data-bc-key]'); - if (key) { this._brainResetScroll = true; this._brainOpenBiography(decodeURIComponent(key.getAttribute('data-bc-key') || ''), key.getAttribute('data-bc-memory')); return; } - const option = target.closest && target.closest('[data-bc-option]'); - if (option) { - const type = option.getAttribute('data-bc-option'), encoded = option.getAttribute('data-bc-value') || ''; - if (!this._brainFilters) this._brainFilters = { kinds: [], repo: '', actor: '', q: '' }; - this._brainFilters[type] = encoded ? decodeURIComponent(encoded) : ''; - this._brainCloseMenus(); this._brainResetScroll = true; this._brainSyncRoute(); this._brainRender(); return; - } - const menu = target.closest && target.closest('[data-bc-menu]'); - if (menu) { const type = menu.getAttribute('data-bc-menu'); this._brainMenu = this._brainMenu === type ? '' : type; this._brainRender(); return; } - const kind = target.closest && target.closest('[data-bc-kind]'); - if (kind) { - const value = kind.getAttribute('data-bc-kind'), kinds = (this._brainFilters.kinds || []).slice(), at = kinds.indexOf(value); - if (at >= 0) kinds.splice(at, 1); else kinds.push(value); - this._brainFilters.kinds = kinds; this._brainResetScroll = true; this._brainSyncRoute(); this._brainRender(); return; - } - const clearKinds = target.closest && target.closest('[data-bc-clear-kinds]'); - if (clearKinds) { this._brainFilters.kinds = []; this._brainResetScroll = true; this._brainSyncRoute(); this._brainRender(); return; } - const clear = target.closest && target.closest('[data-bc-clear]'); - if (clear) { this._brainResetScroll = true; this._brainClearFilters(); return; } - const row = target.closest && target.closest('[data-bc-event]'); - if (row) { this._brainToggleEvent(row.getAttribute('data-bc-event')); return; } - if (this._brainMenu) { this._brainCloseMenus(); this._brainRender(); return; } - if (closedOutside) this._brainRender(); - } - - _brainHandleInput(e) { - if (!e.target || !e.target.hasAttribute('data-bc-search')) return; - if (!this._brainFilters) this._brainFilters = { kinds: [], repo: '', actor: '', q: '' }; - const searchTarget = e.target.getAttribute('data-bc-search') || 'desktop'; - const selectionStart = e.target.selectionStart, selectionEnd = e.target.selectionEnd; - this._brainFilters.q = e.target.value || ''; - clearTimeout(this._brainSearchTimer); - this._brainSearchTimer = setTimeout(() => { - this._brainResetScroll = true; this._brainSyncRoute(); this._brainRender(); - const input = this._learningRoot && this._learningRoot.querySelector('[data-bc-search="' + searchTarget + '"]'); - if (input) { - input.focus(); - try { - const end = input.value.length; - input.setSelectionRange(Math.min(selectionStart == null ? end : selectionStart, end), Math.min(selectionEnd == null ? end : selectionEnd, end)); - } catch (err) {} - } - }, 120); - } ensureLearningDom() { if (this._learningRoot) return this._learningRoot; @@ -6921,17 +6074,11 @@ st.textContent = [ "#learning-root{font-family:Inter,system-ui,sans-serif;color:#c8cce6;flex-direction:column}", "#learning-root .lr-head{display:flex;align-items:center;gap:16px;padding:18px 24px 14px;flex:none;flex-wrap:wrap}", - "#learning-root.brain .lr-head{display:none}", "#learning-root .lr-page-title{font:600 13px 'JetBrains Mono',monospace;color:#c7c9e5}", "#learning-root .lr-title{font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:20px;color:#eef0ff;letter-spacing:-0.02em}", "#learning-root .lr-title .lr-tdot{color:#bb9af7;margin-left:1px}", - "#learning-root .lr-switch{display:flex;gap:4px;background:#0f1120;border:1px solid rgba(160,168,220,0.12);border-radius:9px;padding:3px}", - "#learning-root .lr-chip{background:none;border:none;color:#868db5;font-family:'JetBrains Mono',monospace;font-size:11.5px;padding:5px 14px;border-radius:7px;cursor:pointer}", - "#learning-root .lr-chip:hover{color:#c8cce6}", - "#learning-root .lr-chip.on{background:rgba(158,206,106,0.14);color:#c5f882}", "#learning-root .lr-body{flex:1;position:relative;min-height:0}", "#learning-root #lr-skills{position:absolute;inset:0;overflow-y:auto}", - "#learning-root #lr-knowledge{position:absolute;inset:0;background:#080a14}", "#learning-root .lr-skbody{padding:22px 24px 40px}", "#learning-root .lr-skcol{display:flex;flex-direction:column;gap:20px}", "#learning-root .lr-needs{background:linear-gradient(180deg,rgba(224,175,104,0.07),#111325);border:1px solid rgba(224,175,104,0.26);border-left:3px solid #e0af68;border-radius:12px;overflow:hidden}", @@ -6976,192 +6123,7 @@ "#learning-root .lr-barfill{display:block;height:100%;border-radius:3px}", "#learning-root .lr-scv{font-family:'JetBrains Mono',monospace;font-size:11.5px}", "#learning-root .lr-empty-tbl{padding:60px 20px;text-align:center;color:#5a6088;font-size:13px}", - "#learning-root #lr-know-graph{position:absolute;inset:0}", - "#learning-root .lr-kchip{position:absolute;z-index:10;background:rgba(14,16,30,.72);border:1px solid rgba(187,154,247,.2);border-radius:12px;backdrop-filter:blur(9px);-webkit-backdrop-filter:blur(9px);box-shadow:0 6px 30px rgba(0,0,0,.55)}", - "#learning-root #lr-know-chrome{position:absolute;z-index:12;top:16px;left:16px;right:16px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;pointer-events:none}", - "#learning-root #lr-know-chrome .lr-kchip{position:relative;z-index:auto;pointer-events:auto}", - "#learning-root #lr-know-count,#learning-root #lr-know-linkcount{padding:9px 13px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#c8cce6}", - "#learning-root #lr-know-count b{color:#bb9af7;font-weight:500}", - "#learning-root #lr-know-linkcount b{color:#6ec6ff;font-weight:500}", - "#learning-root .bc-switch{display:flex;padding:3px!important;gap:2px;border-radius:9px!important;background:#0e1320!important;border-color:#1b2233!important;box-shadow:none!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}", - "#learning-root .bc-switch button{display:flex;align-items:center;gap:7px;border:0;background:transparent;color:#5a627e;padding:6px 13px;border-radius:6px;font:600 13px Inter,system-ui,sans-serif;cursor:pointer}", - "#learning-root .bc-switch button:hover{color:#c6cee6}", - "#learning-root .bc-switch button.on{color:#7dcfff;background:#152234}", - "#learning-root .bc-switch .ico{font-family:'JetBrains Mono',monospace;font-size:14px}", - "#learning-root #lr-know-controls{display:flex;align-items:center;padding:4px;gap:4px}", - "#learning-root .lr-ktoggle{border:0;background:transparent;color:#6b7196;padding:5px 9px;border-radius:7px;font-family:'JetBrains Mono',monospace;font-size:10.5px;cursor:pointer;white-space:nowrap}", - "#learning-root .lr-ktoggle:hover{color:#c8cce6;background:rgba(160,168,220,.07)}", - "#learning-root .lr-ktoggle.on{color:#a9e4ff;background:rgba(110,198,255,.12)}", - "#learning-root .lr-ktoggle .dot{display:inline-block;width:6px;height:6px;border-radius:50%;margin-right:6px;background:#454b6c;box-shadow:none}", - "#learning-root .lr-ktoggle.on .dot{background:#6ec6ff;box-shadow:0 0 7px rgba(110,198,255,.75)}", - "#learning-root #lr-know-legend{bottom:16px;left:16px;padding:12px 14px;max-width:230px}", - "#learning-root #lr-know-legend .h{font-family:'JetBrains Mono',monospace;font-size:9.5px;text-transform:uppercase;letter-spacing:1.2px;color:#7f86ad;margin-bottom:7px}", - "#learning-root #lr-know-legend .row{display:flex;align-items:center;gap:8px;font-size:12px;line-height:1.85;color:#c8cce6}", - "#learning-root #lr-know-legend .sw{width:11px;height:11px;border-radius:50%;flex:0 0 auto;box-shadow:0 0 8px 1px currentColor}", - "#learning-root #lr-know-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;z-index:20;font-family:'JetBrains Mono',monospace;font-size:13px;color:#7f86ad;pointer-events:none;transition:opacity .5s}", - "#learning-root #lr-know-loading.hidden{opacity:0}", - "#learning-root #lr-empty{position:absolute;left:0;right:0;top:50%;transform:translateY(-50%);z-index:15;text-align:center;padding:0 40px;font-family:'JetBrains Mono',monospace;font-size:13px;line-height:1.7;color:#7f86ad;pointer-events:none}", - "#learning-root #lr-empty b{color:#bb9af7;font-weight:500}", - "#learning-root .lr-detail{position:absolute;right:0;top:0;bottom:0;width:360px;z-index:30;background:rgba(15,17,32,0.92);border-left:1px solid rgba(160,168,220,0.14);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);box-shadow:-30px 0 60px rgba(0,0,0,0.5);display:flex;flex-direction:column;animation:panelin .28s cubic-bezier(.2,.8,.2,1)}", - "#learning-root .lr-dhead{padding:18px 20px 14px;border-bottom:1px solid rgba(160,168,220,0.08)}", - "#learning-root .lr-drow{display:flex;align-items:flex-start;gap:10px}", - "#learning-root .lr-ddot{width:11px;height:11px;border-radius:50%;flex:none;margin-top:4px}", - "#learning-root .lr-dtitle{font-size:15px;font-weight:600;color:#eef0ff;font-family:Inter;line-height:1.3;word-break:break-word}", - "#learning-root .lr-dsub{font-family:'JetBrains Mono',monospace;font-size:11px;color:#868db5;margin-top:3px;word-break:break-word}", - "#learning-root .lr-dclose{width:26px;height:26px;flex:none;background:rgba(160,168,220,0.08);border:1px solid rgba(160,168,220,0.12);border-radius:7px;color:#868db5;font-size:14px;cursor:pointer;line-height:1}", - "#learning-root .lr-dbadges{display:flex;gap:8px;margin-top:13px;flex-wrap:wrap}", - "#learning-root .lr-dbadge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:7px;font-family:'JetBrains Mono',monospace;font-size:11px;font-weight:600}", - "#learning-root .lr-dbadge.mut{color:#868db5;background:rgba(160,168,220,0.06);border:1px solid rgba(160,168,220,0.1);font-weight:400}", - "#learning-root .lr-dbody{flex:1;overflow-y:auto;padding:16px 20px 24px}", - "#learning-root .lr-dblock{background:#0a0b16;border:1px solid rgba(160,168,220,0.1);border-radius:9px;padding:12px 13px;font-family:'JetBrains Mono',monospace;font-size:12px;line-height:1.6;color:#c7c9e5;white-space:pre-wrap;word-break:break-word;margin-bottom:18px}", - "#learning-root .lr-dgrid{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:18px}", - "#learning-root .lr-dcell{background:rgba(10,11,22,0.6);border:1px solid rgba(160,168,220,0.08);border-radius:9px;padding:10px 11px}", - "#learning-root .lr-dk{font-size:10px;color:#5a6088;letter-spacing:0.04em;text-transform:uppercase}", - "#learning-root .lr-dv{font-family:'JetBrains Mono',monospace;font-size:13px;color:#a8aecf;margin-top:4px;word-break:break-word}", - "#learning-root .lr-dv.hi{color:#eef0ff}", - "#learning-root .lr-dsec{font-size:10.5px;color:#5a6088;letter-spacing:0.1em;text-transform:uppercase;margin-bottom:10px}", - "#learning-root .lr-dlink{display:flex;align-items:center;gap:10px;padding:11px 14px;background:rgba(187,154,247,0.1);border:1px solid rgba(187,154,247,0.26);border-radius:10px;color:#d7c4ff;text-decoration:none;font-size:13px;font-weight:500;cursor:pointer;margin-top:14px}", - "#learning-root .lr-dmd{background:#0a0b16;border:1px solid rgba(160,168,220,0.1);border-radius:9px;padding:12px 13px;font-size:13px;line-height:1.62;color:#c7c9e5;margin-bottom:14px;word-break:break-word;overflow-wrap:anywhere}", - "#learning-root .lr-dmd .lr-mdp{margin:0 0 8px}", - "#learning-root .lr-dmd .lr-mdp:last-child{margin-bottom:0}", - "#learning-root .lr-dmd strong{color:#eef0ff;font-weight:600}", - "#learning-root .lr-dmd .lr-mdcode{font-family:'JetBrains Mono',monospace;font-size:11.5px;background:rgba(160,168,220,0.12);color:#c5f882;border-radius:4px;padding:1px 5px}", - "#learning-root .lr-dmd .lr-mdpre{margin:8px 0;background:#06070e;border:1px solid rgba(160,168,220,0.12);border-radius:8px;padding:10px 11px;overflow-x:auto}", - "#learning-root .lr-dmd .lr-mdpre code{font-family:'JetBrains Mono',monospace;font-size:11.5px;line-height:1.55;color:#c7c9e5;white-space:pre;background:none}", - "#learning-root .lr-dmd .lr-mdul{margin:6px 0;padding-left:20px}", - "#learning-root .lr-dmd .lr-mdul li{margin:2px 0}", - "#learning-root .lr-dmd .lr-mdlink{color:#7dcfff;text-decoration:underline;text-underline-offset:2px;word-break:break-all}", - "#learning-root .lr-dmd .lr-mdtrunc{color:#5a6088;font-style:italic}", - "#learning-root .lr-dmd .lr-wikilink{display:inline;color:#d7c4ff;background:rgba(187,154,247,0.14);border:1px solid rgba(187,154,247,0.3);border-radius:5px;padding:0 5px;cursor:pointer;font-size:12px}", - "#learning-root .lr-dmd .lr-wikilink:hover{background:rgba(187,154,247,0.24)}", - "#learning-root .lr-dmd .lr-wikilink.dead{color:#868db5;background:rgba(160,168,220,0.08);border-color:rgba(160,168,220,0.18);cursor:default}", - "#learning-root .lr-dprov{font-family:'JetBrains Mono',monospace;font-size:11px;color:#868db5;line-height:1.5;padding:9px 11px;background:rgba(10,11,22,0.5);border:1px solid rgba(160,168,220,0.08);border-left:2px solid rgba(187,154,247,0.4);border-radius:7px;margin-bottom:16px;word-break:break-word}", - "#learning-root .lr-dprov b{color:#c7c9e5;font-weight:600}", - "#learning-root .lr-dparent{cursor:pointer;border-left-color:rgba(187,154,247,0.8)}", - "#learning-root .lr-dparent:hover{background:rgba(187,154,247,0.1)}", - "#learning-root .lr-dcrumb{display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#5a6088;margin-bottom:14px}", - "#learning-root .lr-dcrumb button{border:0;background:none;padding:0;color:#a99ac8;font:inherit;cursor:pointer}", - "#learning-root .lr-dcrumb button:hover{color:#d7c4ff}", - "#learning-root .lr-dcrumb .cur{color:#d7c4ff}", - "#learning-root .lr-dcmd{display:flex;align-items:center;padding:7px 10px;background:#0a0b16;border:1px solid rgba(160,168,220,0.14);border-radius:8px;margin-bottom:14px;overflow-x:auto}", - "#learning-root .lr-dcmd code{font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#c5f882;white-space:nowrap}", - "#learning-root .lr-dmemlist{display:flex;flex-direction:column;gap:5px}", - "#learning-root .lr-dmember{display:flex;align-items:flex-start;gap:9px;padding:9px 11px;background:rgba(10,11,22,0.6);border:1px solid rgba(160,168,220,0.08);border-radius:8px;cursor:pointer;transition:background .12s ease,border-color .12s ease}", - "#learning-root .lr-dmember:hover{background:rgba(160,168,220,0.07);border-color:rgba(160,168,220,0.2)}", - "#learning-root .lr-dmember.sup{opacity:0.55}", - "#learning-root .lr-dmemdot{width:7px;height:7px;border-radius:50%;flex:none;margin-top:5px}", - "#learning-root .lr-dmemtext{flex:1;min-width:0;font-size:12.5px;line-height:1.42;color:#c7c9e5;word-break:break-word}", - "#learning-root .lr-dlinklist{display:flex;flex-direction:column;gap:5px}", - "#learning-root .lr-dlinkfact{display:flex;align-items:flex-start;gap:8px;padding:8px 11px;background:rgba(187,154,247,0.07);border:1px solid rgba(187,154,247,0.2);border-radius:8px;cursor:pointer}", - "#learning-root .lr-dlinkfact:hover{background:rgba(187,154,247,0.15)}", - "#learning-root .lr-dlinkarrow{color:#bb9af7;flex:none;margin-top:1px;font-size:12px}", - "#learning-root .lr-dlinktext{flex:1;min-width:0;font-size:12.5px;line-height:1.42;color:#d7c4ff;word-break:break-word}", - "#learning-root .lr-dmute{font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#5a6088;padding:6px 2px}", - "#learning-root #lr-know-mobile{position:absolute;inset:0;overflow-y:auto;padding:108px 14px 24px;display:none}", - "#learning-root #lr-know-mobile-view{display:none;padding:3px;gap:2px;border-radius:9px;flex:none}", - "#learning-root #lr-know-mobile-view button{border:0;background:transparent;color:#6b7196;padding:5px 9px;border-radius:6px;font-family:'JetBrains Mono',monospace;font-size:10.5px;cursor:pointer}", - "#learning-root #lr-know-mobile-view button.on{color:#eef0ff;background:rgba(187,154,247,.16)}", - "#learning-root .km-sec{border:1px solid rgba(160,168,220,0.12);border-radius:11px;margin-bottom:10px;overflow:hidden;background:rgba(255,255,255,0.02)}", - "#learning-root .km-head{display:flex;align-items:center;gap:11px;padding:13px 13px;cursor:pointer;-webkit-tap-highlight-color:transparent}", - "#learning-root .km-bar{width:3px;height:16px;border-radius:2px;flex:none}", - "#learning-root .km-name{flex:1;min-width:0;font-size:13px;color:#e7ecf3;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", - "#learning-root .km-count{font-family:'JetBrains Mono',monospace;font-size:11px;color:#868db5;flex:none}", - "#learning-root .km-chev{font-size:11px;color:#5a6088;width:13px;text-align:center;flex:none}", - "#learning-root .km-body{padding:2px 12px 12px;display:flex;flex-direction:column;gap:6px}", - "#learning-root .km-cln{margin-left:auto;font-family:'JetBrains Mono',monospace;font-size:11px;color:#5a6088;flex:none;padding-left:8px}", - "#learning-root .km-cluster-group{display:flex;flex-direction:column;gap:5px}", - "#learning-root .km-subrow{margin-left:17px;padding-left:13px;background:rgba(187,154,247,0.035);border-left:2px solid rgba(187,154,247,0.24)}", - "#learning-root .km-subrow .lr-dmemdot{width:6px;height:6px;background:#a99ac8!important}", - "#learning-root .km-expand{flex:none;border:1px solid rgba(169,154,200,.45);background:rgba(169,154,200,.1);color:#d2c5ec;border-radius:5px;padding:2px 6px;font-family:'JetBrains Mono',monospace;font-size:9.5px;cursor:pointer}", - "#learning-root #lr-changelog{position:absolute;inset:0;display:none;flex-direction:column;gap:12px;padding:58px 16px 16px;overflow:hidden;background:#080a14}", - "#learning-root #lr-know-chrome.changelog .lr-kchip{background:#0e1320;border-color:#1b2233;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none}", - "#learning-root #lr-know-chrome.changelog #lr-know-count{border-radius:8px;padding:7px 13px;color:#8b93ac;font-size:12.5px}", - "#learning-root .bc-filterbar{flex:none;display:flex;flex-direction:column;gap:10px}", - "#learning-root .bc-kindrow{display:flex;align-items:center;gap:7px;flex-wrap:wrap}", - "#learning-root .bc-flabel{font-size:10px;text-transform:uppercase;letter-spacing:.12em;color:#464f6b;margin-right:2px;font-weight:600}", - "#learning-root .bc-kind{display:flex;align-items:center;gap:6px;padding:4px 10px;border-radius:7px;font-family:'JetBrains Mono',monospace;font-size:12px;cursor:pointer;color:#5a627e;background:transparent;border:1px solid #1b2233}", - "#learning-root .bc-kind:hover{color:#a2abc4;border-color:#28324c}", - "#learning-root .bc-kind.on{color:var(--bc);background:color-mix(in srgb,var(--bc) 10%,transparent);border-color:color-mix(in srgb,var(--bc) 34%,transparent)}", - "#learning-root .bc-dot{width:7px;height:7px;border-radius:50%;background:var(--bc);flex:none}", - "#learning-root .bc-clear{border:0;background:none;color:#5a627e;padding:4px 9px;font-size:11.5px;cursor:pointer}", - "#learning-root .bc-clear:hover{color:#c6cee6}", - "#learning-root .bc-filterrow{display:flex;align-items:center;gap:10px}", - "#learning-root .bc-search{flex:1;max-width:420px;display:flex;align-items:center;gap:8px;padding:8px 12px;background:#0e1320;border:1px solid #1b2233;border-radius:8px}", - "#learning-root .bc-search span{font-size:14px;color:#5a627e}", - "#learning-root .bc-search input{flex:1;min-width:0;background:transparent;border:0;outline:0;color:#c6cee6;font-family:'JetBrains Mono',monospace;font-size:13px}", - "#learning-root .bc-select{position:relative;min-width:158px}", - "#learning-root .bc-select.actor{min-width:220px}", - "#learning-root .bc-selectbtn{display:flex;align-items:center;gap:10px;width:100%;padding:8px 12px;background:#0e1320;border:1px solid #1b2233;border-radius:8px;color:#5a627e;font-size:13px;cursor:pointer;text-align:left}", - "#learning-root .bc-selectbtn span:first-child{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", - "#learning-root .bc-menu{position:absolute;top:calc(100% + 5px);left:0;right:0;z-index:40;background:#0e1320;border:1px solid #28324c;border-radius:8px;padding:5px;box-shadow:0 14px 34px rgba(0,0,0,.55);max-height:300px;overflow-y:auto}", - "#learning-root .bc-select.actor .bc-menu{min-width:260px}", - "#learning-root .bc-option{display:block;width:100%;border:0;background:none;padding:7px 10px;border-radius:6px;color:#8b93ac;text-align:left;font-family:'JetBrains Mono',monospace;font-size:12.5px;cursor:pointer}", - "#learning-root .bc-option:hover,#learning-root .bc-option.on{background:#141a2b;color:#c6cee6}", - "#learning-root .bc-mobile-actions{display:none}", - "#learning-root .bc-panel{flex:1;min-height:0;display:flex;flex-direction:column;background:#0b0f1a;border:1px solid #1b2233;border-radius:11px;overflow:hidden}", - "#learning-root .bc-bio{flex:none;padding:14px 18px;border-bottom:1px solid #141a28}", - "#learning-root .bc-biohead{display:flex;align-items:center;gap:12px;min-width:0}", - "#learning-root .bc-back{display:flex;align-items:center;gap:6px;padding:5px 10px;border:1px solid #1b2233;border-radius:7px;background:none;color:#8b93ac;font-size:12.5px;cursor:pointer}", - "#learning-root .bc-back:hover{border-color:#28324c;color:#c6cee6}", - "#learning-root .bc-biokey{font-family:'JetBrains Mono',monospace;font-size:15px;font-weight:600;color:#7dcfff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", - "#learning-root .bc-status{display:flex;align-items:center;gap:6px;padding:3px 9px;border-radius:20px;background:color-mix(in srgb,var(--bc) 12%,transparent);font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--bc);white-space:nowrap}", - "#learning-root .bc-status i{width:6px;height:6px;border-radius:50%;background:var(--bc)}", - "#learning-root .bc-biometa{margin-left:auto;font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#5a627e;white-space:nowrap}", - "#learning-root .bc-biocontent{margin-top:10px;background:#080b13;border:1px solid #161d2c;border-radius:8px;padding:10px 14px;font-family:'JetBrains Mono',monospace;font-size:12.5px;line-height:1.55;color:#a2abc4;white-space:pre-wrap;max-height:150px;overflow:auto}", - "#learning-root .bc-biofoot{margin-top:8px;font-size:11.5px;color:#464f6b}", - "#learning-root .bc-feed{flex:1;min-height:0;overflow-y:auto;overscroll-behavior-y:contain;scrollbar-gutter:stable}", - "#learning-root .bc-day{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:10px;padding:9px 18px;background:#0b0f1a;border-bottom:1px solid #141a28}", - "#learning-root .bc-day b{font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:#8b93ac}", - "#learning-root .bc-day i{height:1px;flex:1;background:#141a28}", - "#learning-root .bc-day span{font-family:'JetBrains Mono',monospace;font-size:11px;color:#464f6b}", - "#learning-root .bc-event{border-bottom:1px solid #101623}", - "#learning-root .bc-event.backfilled{opacity:.6}", - "#learning-root .bc-event.live-new{animation:bc-new 3.4s ease-out both}", - "@keyframes bc-new{0%{background:rgba(125,207,255,.2)}100%{background:transparent}}", - "#learning-root .bc-row{display:flex;align-items:center;gap:12px;padding:0 18px;height:40px;cursor:pointer;background:transparent}", - "#learning-root .bc-row:hover{background:#0f1524}", - "#learning-root .bc-event.open .bc-row{background:#0d1322}", - "#learning-root .bc-key{font-family:'JetBrains Mono',monospace;font-size:13px;font-weight:500;color:var(--bc);border:0;background:none;padding:0;cursor:pointer;max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:none;text-align:left}", - "#learning-root .bc-key:hover{text-decoration:underline}", - "#learning-root .bc-sentence{flex:1;min-width:0;font-size:12.5px;color:#8b93ac;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}", - "#learning-root .bc-tag{flex:none;padding:2px 7px;border-radius:5px;background:#11141f;border:1px solid #1b2233;font-family:'JetBrains Mono',monospace;font-size:10px;color:#5a627e;letter-spacing:.04em}", - "#learning-root .bc-count{flex:none;padding:2px 8px;border-radius:20px;background:rgba(224,105,129,.12);border:1px solid rgba(224,105,129,.3);font-family:'JetBrains Mono',monospace;font-size:11px;color:#e0697f}", - "#learning-root .bc-time{font-family:'JetBrains Mono',monospace;font-size:12px;color:#5a627e;width:48px;text-align:right;flex:none}", - "#learning-root .bc-caret{color:#3a4258;font-size:12px;transition:transform .15s;flex:none}", - "#learning-root .bc-event.open .bc-caret{transform:rotate(90deg)}", - "#learning-root .bc-expand{padding:2px 18px 16px 40px;animation:bc-expand .18s ease-out}", - "@keyframes bc-expand{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}", - "#learning-root .bc-box{background:#080b13;border:1px solid #161d2c;border-radius:8px;padding:12px 14px;color:#a2abc4;font-size:13px;line-height:1.55}", - "#learning-root .bc-boxlabel{color:#5a627e;font-family:'JetBrains Mono',monospace;font-size:10px;text-transform:uppercase;letter-spacing:.1em}", - "#learning-root .bc-action{border:0;background:none;padding:0;color:#7aa2f7;font-size:12.5px;cursor:pointer}", - "#learning-root .bc-action:hover{color:#9db8ff}", - "#learning-root .bc-diff{display:grid;grid-template-columns:1fr 1fr;gap:12px}", - "#learning-root .bc-dpane{background:#080b13;border:1px solid #161d2c;border-radius:8px;overflow:hidden;min-width:0}", - "#learning-root .bc-unified{display:none}", - "#learning-root .bc-dhead{padding:6px 12px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#5a627e;border-bottom:1px solid #141a28;display:flex;justify-content:space-between}", - "#learning-root .bc-dbody{padding:8px 0}", - "#learning-root .bc-line{display:flex;gap:8px;padding:1px 12px;font-family:'JetBrains Mono',monospace;font-size:12.5px;line-height:1.55;color:#a2abc4;white-space:pre-wrap;word-break:break-word}", - "#learning-root .bc-line.del{background:rgba(224,105,129,.08);color:#c08a95}", - "#learning-root .bc-line.add{background:rgba(158,206,106,.07);color:#a8c98b}", - "#learning-root .bc-gut{width:9px;flex:none;color:#464f6b}", - "#learning-root .bc-meta{margin-top:12px;display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:#141a28;border:1px solid #161d2c;border-radius:8px;overflow:hidden}", - "#learning-root .bc-mcell{background:#080b13;padding:9px 12px;min-width:0}", - "#learning-root .bc-mcell b{display:block;font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:#464f6b}", - "#learning-root .bc-mcell span{display:block;margin-top:3px;font-family:'JetBrains Mono',monospace;font-size:12.5px;color:#a2abc4;word-break:break-all}", - "#learning-root .bc-burstkeys{margin-top:10px;max-height:150px;overflow-y:auto;display:flex;flex-wrap:wrap;gap:6px}", - "#learning-root .bc-burstkeys span{padding:3px 8px;border-radius:6px;background:#0e1320;border:1px solid #1b2233;font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#c08a95}", - "#learning-root .bc-begin{display:flex;align-items:center;gap:12px;padding:16px 18px}", - "#learning-root .bc-begin i{height:1px;flex:1;background:#141a28}", - "#learning-root .bc-begin span{font-family:'JetBrains Mono',monospace;font-size:11px;color:#3a4258;letter-spacing:.05em}", - "#learning-root .bc-empty{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px;text-align:center}", - "#learning-root .bc-empty .icon{font-size:32px;color:#2c3350}", - "#learning-root .bc-empty b{font-size:15px;color:#c6cee6;font-weight:500}", - "#learning-root .bc-empty p{font-size:13px;color:#5a627e;max-width:400px;line-height:1.5;margin:0}", - "#learning-root .bc-sheetback,#learning-root .bc-sheet{display:none}", - "@media (prefers-reduced-motion:reduce){#learning-root .bc-event.live-new,#learning-root .bc-expand{animation:none!important}#learning-root .bc-caret{transition:none!important}}", - "@media (max-width:768px){#learning-root .lr-head{padding-left:16px;padding-right:16px}#learning-root .lr-skbody{padding-left:14px;padding-right:14px}#learning-root .lr-thead{display:none}#learning-root .lr-trow{flex-wrap:wrap;gap:6px 10px}#learning-root .lr-c-name{flex:1 1 100%;white-space:normal}#learning-root .lr-c-ver,#learning-root .lr-c-changed{width:auto;flex:none}#learning-root .lr-c-score{width:auto;flex:1}#learning-root .lr-nrow{gap:8px}#learning-root .lr-cmd{width:100%;max-width:none}#learning-root .lr-cmd code{white-space:normal;word-break:break-all}#learning-root .lr-detail{width:100%;left:0;border-left:none}#learning-root #lr-know-linkcount,#learning-root #lr-know-controls{display:none!important}#learning-root #lr-know-count{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#learning-root #lr-know-mobile-view{margin-left:auto}#learning-root #lr-know-chrome.changelog #lr-know-mobile-view{display:none!important}}", - "@media (max-width:768px){#learning-root #lr-know-chrome{top:12px;left:16px;right:16px;gap:10px}#learning-root #lr-know-chrome .bc-switch{order:0;flex:1 0 100%}#learning-root .bc-switch button{flex:1;justify-content:center;padding:7px 10px;font-size:12.5px}#learning-root #lr-know-chrome.changelog #lr-know-count{order:1;padding:0;border:0;background:none!important;font-size:11.5px}#learning-root #lr-changelog{padding:100px 16px 16px;gap:10px}#learning-root .bc-filterbar{display:none}#learning-root .bc-mobile-actions{display:flex;position:absolute;right:16px;top:58px;z-index:14}#learning-root .bc-filterbtn{display:flex;align-items:center;gap:6px;padding:5px 9px;border:1px solid #1b2233;border-radius:7px;background:#0e1320;color:#8b93ac;font-size:11.5px}#learning-root .bc-filterbtn b{min-width:17px;height:17px;padding:0 4px;border-radius:9px;background:#7dcfff;color:#06121e;font-size:10.5px;display:flex;align-items:center;justify-content:center}#learning-root .bc-row{height:48px;padding:0 14px;gap:10px}#learning-root .bc-key{font-size:12.5px;flex:1;max-width:none;min-width:0}#learning-root .bc-sentence{display:none}#learning-root .bc-time{font-size:11px;width:34px}#learning-root .bc-caret{display:none}#learning-root .bc-kindtag{display:block!important;flex:none;font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--bc)}#learning-root .bc-day{padding:8px 14px}#learning-root .bc-expand{padding:2px 14px 14px 32px}#learning-root .bc-mobile-sentence{display:block!important;font-size:12px;color:#8b93ac;line-height:1.5;margin-bottom:10px}#learning-root .bc-diff{display:block}#learning-root .bc-dpane.before,#learning-root .bc-dpane.after{display:none}#learning-root .bc-unified{display:block}#learning-root .bc-line{font-size:11.5px;line-height:1.5;padding-left:11px;padding-right:11px}#learning-root .bc-meta{grid-template-columns:1fr 1fr}#learning-root .bc-bio{padding:12px 14px}#learning-root .bc-biohead{gap:10px}#learning-root .bc-back{padding:5px 9px;font-size:12px}#learning-root .bc-biokey{font-size:13px;flex:1}#learning-root .bc-biometa{display:none}#learning-root .bc-status{font-size:10.5px;padding:3px 8px}#learning-root .bc-biocontent{font-size:11.5px;padding:9px 12px;margin-top:9px}#learning-root .bc-biofoot{font-size:11px}#learning-root .bc-sheetback{display:block;position:absolute;inset:0;z-index:49;background:rgba(2,3,8,.58)}#learning-root .bc-sheet{display:flex;position:absolute;left:0;right:0;bottom:0;z-index:50;max-height:78%;background:#0e1320;border:1px solid #28324c;border-radius:14px 14px 0 0;padding:12px 16px 20px;flex-direction:column;gap:13px;box-shadow:0 -18px 50px rgba(0,0,0,.55);overflow-y:auto}#learning-root .bc-sheethead{display:flex;align-items:center;justify-content:space-between;color:#c6cee6;font-weight:600}#learning-root .bc-sheetclose{border:0;background:none;color:#8b93ac;font-size:20px}#learning-root .bc-sheet .bc-kindrow{gap:6px}#learning-root .bc-sheet .bc-kind{padding:5px 9px}#learning-root .bc-sheet .bc-search{max-width:none}#learning-root .bc-sheet .bc-select{width:100%;min-width:0}#learning-root .bc-sheet .bc-menu{position:static;margin-top:5px;max-height:170px}}", - "@media (pointer:coarse){#learning-root .lr-dclose{width:44px;height:44px;font-size:17px}}" + "@media (max-width:768px){#learning-root .lr-head{padding-left:16px;padding-right:16px}#learning-root .lr-skbody{padding-left:14px;padding-right:14px}#learning-root .lr-thead{display:none}#learning-root .lr-trow{flex-wrap:wrap;gap:6px 10px}#learning-root .lr-c-name{flex:1 1 100%;white-space:normal}#learning-root .lr-c-ver,#learning-root .lr-c-changed{width:auto;flex:none}#learning-root .lr-c-score{width:auto;flex:1}#learning-root .lr-nrow{gap:8px}#learning-root .lr-cmd{width:100%;max-width:none}#learning-root .lr-cmd code{white-space:normal;word-break:break-all}}" ].join('\n'); document.head.appendChild(st); @@ -7176,80 +6138,11 @@ '
', '
', '
', - ' ', '
' ].join('\n'); document.body.appendChild(root); this._dockOverlay(root); // mobile: left:0 + bottom clears the tab bar this._learningRoot = root; - this._knowGraphEl = root.querySelector('#lr-know-graph'); - - this._knowFactLinksOn = this._knowFactLinksOn !== false; - this._knowCrossRepoOn = !!this._knowCrossRepoOn; - this._knowHistoryOn = !!this._knowHistoryOn; - root.querySelector('#lr-know-chrome').addEventListener('click', (e) => { - const view = e.target.closest && e.target.closest('[data-brain-view]'); - if (view) { this._brainSetView(view.getAttribute('data-brain-view'), true); return; } - const mobileView = e.target.closest && e.target.closest('[data-know-mobile-view]'); - if (mobileView) { this._knowSetMobileView(mobileView.getAttribute('data-know-mobile-view')); return; } - const b = e.target.closest && e.target.closest('[data-know-toggle]'); - if (!b) return; - const which = b.getAttribute('data-know-toggle'); - if (which === 'links') this._knowFactLinksOn = !this._knowFactLinksOn; - if (which === 'cross') this._knowCrossRepoOn = !this._knowCrossRepoOn; - if (which === 'history') { - this._knowHistoryOn = !this._knowHistoryOn; - this._knowSetHoveredFact(null); - if (!this._knowHistoryOn && this._knowSelected) { - const selectedFact = this._knowFactById && this._knowFactById[this._knowSelected.id]; - if (selectedFact && selectedFact.superseded) this.closeKnowledgeDetail(); - } - this.renderKnowledge(true); - return; - } - this._knowSyncChrome(this._knowBuilt || { agentCount: 0, factCount: 0, factLinkCount: 0 }); - try { if (this._knowGraph && this._knowGraph.refresh) this._knowGraph.refresh(); } catch (e2) {} - }); - const changelog = root.querySelector('#lr-changelog'); - changelog.addEventListener('click', (e) => this._brainHandleClick(e)); - changelog.addEventListener('input', (e) => this._brainHandleInput(e)); - this._brainDocClick = (e) => { - if (this.state.view !== 'brain' || this._brainView !== 'changelog' || !this._brainMenu) return; - if (e.target && e.target.closest && e.target.closest('.bc-select')) return; - this._brainCloseMenus(); this._brainRender(); - }; - document.addEventListener('click', this._brainDocClick); // Skills delegation: copy chip > section disclosure toggle > row-nav-to-agent. const sbody = root.querySelector('#lr-skills-body'); sbody.addEventListener('click', (e) => { @@ -7260,32 +6153,6 @@ const row = (e.target.closest && e.target.closest('.lr-tdata')) || null; if (row && row.getAttribute('data-agent')) this._learningGotoAgent(row.getAttribute('data-agent')); }); - // Knowledge: Escape clears detail focus and restores the collapsed hierarchy - // frontier; resize re-fits the graph. - this._learningKeydown = (e) => { - if (e.key !== 'Escape' || this.state.view !== 'brain') return; - if (this._brainView === 'changelog') { - if (this._brainSheetOpen || this._brainMenu) { this._brainSheetOpen = false; this._brainCloseMenus(); this._brainRender(); return; } - if (this._brainBiographyKey) { this._brainExitBiography(); return; } - if (this._brainOpenId) { this._brainOpenId = ''; this._brainRender(); } - return; - } - if (this._knowSelected) this.closeKnowledgeDetail(); - this._knowCollapseHierarchy(); - }; - document.addEventListener('keydown', this._learningKeydown); - this._knowResize = () => { - if (this.state.view !== 'brain' || this._brainView === 'changelog' || !this._knowGraph) return; - if (this._knowGraphEl.style.display === 'none') return; - const r = this._knowGraphEl.getBoundingClientRect(); - this._knowGraph.width(r.width).height(r.height); - // The three bands are graph-space positions derived from the container width, so - // a resize/breakpoint must recompute them and re-settle. Debounced so a drag-resize - // doesn't thrash the layout. - clearTimeout(this._knowRelayoutT); - this._knowRelayoutT = setTimeout(() => { this._knowRelayout(); }, 220); - }; - window.addEventListener('resize', this._knowResize); return root; } @@ -7440,2199 +6307,43 @@ this._navRoute('agents', { agent: name }); } - // ---- Knowledge tab: a SECOND force-graph instance -------------------------- - _knowColor(n) { - if (n.type === 'cluster') return n.__knowRole === 'frontier' || (!n.__knowRole && n.parentId) ? '#a99ac8' : '#cabff2'; - if (n.type === 'agent') return this._knowClustered ? '#cdbdf6' : '#bb9af7'; - if (n.type === 'category') return '#bb9af7'; // violet category hubs - if (n.superseded) return '#5a6088'; // superseded fact ghosts (dim) - return n.repo ? (this._knowClustered ? '#6ec6ff' : '#7dcfff') : '#e0af68'; - } - _knowAlpha(n) { - if (n.type === 'cluster') return 0.92; - if (n.type === 'agent') return (n.facts > 0) ? 0.95 : 0.4; // dim agent well when 0 facts - if (n.type === 'category') return 0.9; - return n.superseded ? 0.4 : 0.92; // superseded at 40% alpha - } - _knowRadius(n) { - if (n.type === 'cluster') return 2.4; // same size as facts (owner: hubs earn no extra pixels) - if (n.type === 'agent') return 7; - if (n.type === 'category') return 3; - if (n.type === 'evidence') return 1.4; // dim observation dots (input layer) - return 2.4; // facts: tiny + uniform (scope-colored) - } - // Strip the server's `cat:` namespace prefix off a category-hub id for display. - _knowCatLabel(id) { const s = String(id || ''); return s.indexOf('cat:') === 0 ? s.slice(4) : s; } - // Repo swimlane (option A) helpers. Short lane label = the repo name with its - // owner/ prefix stripped ("" = general). Lane color is a deterministic pick off - // the shared 9-color palette (general is a muted neutral so it recedes). - _knowRepoShort(scope) { const s = String(scope || ''); if (!s) return 'general'; const i = s.lastIndexOf('/'); return i >= 0 ? s.slice(i + 1) : s; } - _knowRepoColor(scope) { - if (!scope) return '#727b88'; // general lane: muted neutral - const pal = ['#7aa2f7', '#bb9af7', '#7dcfff', '#9ece6a', '#e0af68', '#f7768e', '#2ac3de', '#b4f9f8', '#c0caf5']; - return pal[this._knowHash(scope) % pal.length]; - } - // Deterministic string hash (FNV-1a) → uint32. Used for STABLE seeded jitter so - // the 12s poll re-render never reshuffles evidence dots or fact seeds (no - // Math.random at layout time for the banded layout). - _knowHash(str) { - let h = 2166136261; - const s = String(str); - for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } - return h >>> 0; - } - _knowRand(str) { return (this._knowHash(str) % 100000) / 100000; } // deterministic [0,1) - _knowRng(seed) { - let s = this._knowHash(seed); - return () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; }; - } - _knowClamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); } - _knowFactLinkAlpha(score) { - const s = this._knowClamp(Number(score) || 0, 0, 1); - const t = this._knowClamp((s - 0.2) / 0.75, 0, 1); - return 0.05 + 0.42 * Math.pow(t, 1.4); - } - _knowFactLinkWidth(score) { return 0.5 + 1.15 * this._knowClamp(Number(score) || 0, 0, 1); } - - // The FOUR vertical columns of the layered layout, in GRAPH coordinates (zoomToFit - // maps them to screen). Recomputed from the live container size so the spread tracks - // the width on resize/breakpoint. cols = [0]evidence [1]facts [2]category [3]agents, - // evenly spaced; GH is the graph-space height each column spans. - _knowComputeBands() { - let W = 1000, H = 700; - try { const r = this._knowGraphEl.getBoundingClientRect(); if (r && r.width) { W = r.width; H = r.height; } } catch (e) {} - const GH = 460; // column vertical extent (graph units) - const aspect = Math.max(0.5, Math.min(2.4, W / Math.max(1, H))); // clamp so extreme shapes stay readable - // spread the 4 columns to ~44% of the aspect-scaled height, but COMPRESS on narrow - // (portrait/mobile) widths so the rightmost agent labels never clip off the edge. - const spanFactor = 0.44 * Math.max(0.6, Math.min(1, (W - 40) / 700)); - const spanHalf = spanFactor * (GH * aspect); // half the 4-column horizontal spread - const cols = [-spanHalf, -spanHalf / 3, spanHalf / 3, spanHalf]; // evidence | facts | category | agents - this._knowBandX = { cols: cols, left: cols[0], fact: cols[1], cat: cols[2], right: cols[3], GH: GH, W: W, H: H }; - return this._knowBandX; - } - - // Compute the STATIC 4-column layout: every node gets a PINNED (fx/fy) position from - // a DETERMINISTIC sort — no physics runs, positions are computed, committed, done. - // facts grouped by category then id; category hubs at the mean-y of their facts; - // agents by name; evidence clustered beside its fact with small seeded offsets. - _knowLayout(nodes, links) { - if (this._knowClustered) return this._knowLayoutClustered(nodes, links); - const b = this._knowComputeBands(); - const cols = b.cols, GH = b.GH, top = -GH / 2; - const spanY = (n, i) => (n <= 1 ? 0 : top + i * (GH / (n - 1))); - // fact -> category id, read off the server's authored category edges - const factCat = {}; - for (let i = 0; i < links.length; i++) { const l = links[i]; if (l.kind === 'category') { const s = (l.source && l.source.id != null) ? l.source.id : l.source, t = (l.target && l.target.id != null) ? l.target.id : l.target; factCat[s] = t; } } - const catOf = (id) => factCat[id] || '~none'; - // order categories by id; sort facts by (categoryOrder, id) so each category's - // facts are contiguous and its fan converges cleanly onto one hub. - const facts = nodes.filter(n => n.type === 'fact'); - const catIds = Array.from(new Set(facts.map(f => catOf(f.id)))).sort(); - const catOrder = {}; catIds.forEach((c, i) => { catOrder[c] = i; }); - facts.sort((a, bb) => { const ca = catOrder[catOf(a.id)], cb = catOrder[catOf(bb.id)]; if (ca !== cb) return ca - cb; return a.id < bb.id ? -1 : a.id > bb.id ? 1 : 0; }); - // evenly space facts down the column, inserting a small gap between category groups - const GAP = 1.4; // extra slots between adjacent category groups - let units = Math.max(0, facts.length - 1), prev = null; - facts.forEach(f => { const c = catOf(f.id); if (prev !== null && c !== prev) units += GAP; prev = c; }); - const denom = Math.max(1, units); - let slot = 0; prev = null; - const cySum = {}, cyCnt = {}; - facts.forEach(f => { - const c = catOf(f.id); - if (prev !== null && c !== prev) slot += GAP; - prev = c; - const y = top + (slot / denom) * GH; - f.fx = cols[1]; f.fy = y; f.x = f.fx; f.y = f.fy; f.vx = 0; f.vy = 0; - cySum[c] = (cySum[c] || 0) + y; cyCnt[c] = (cyCnt[c] || 0) + 1; - slot += 1; - }); - // category hubs at the mean-y of their member facts (converging fan waists) - nodes.forEach(n => { if (n.type !== 'category') return; const cnt = cyCnt[n.id] || 0; n.fx = cols[2]; n.fy = cnt ? (cySum[n.id] / cnt) : 0; n.x = n.fx; n.y = n.fy; n.vx = 0; n.vy = 0; }); - // agents: right column, evenly spaced, sorted by name - const agents = nodes.filter(n => n.type === 'agent').sort((a, bb) => (a.id < bb.id ? -1 : a.id > bb.id ? 1 : 0)); - const na = agents.length; - agents.forEach((a, i) => { a.fx = cols[3]; a.fy = spanY(na, i); a.x = a.fx; a.y = a.fy; a.vx = 0; a.vy = 0; }); - // evidence: left column, clustered beside its fact's y with deterministic offsets - const fById = {}; facts.forEach(f => { fById[f.id] = f; }); - nodes.forEach(n => { if (n.type !== 'evidence') return; const f = fById[n.factId]; const fy = f ? f.fy : 0; n.fx = cols[0] + (n.__eox || 0); n.fy = fy + (n.__eoy || 0); n.x = n.fx; n.y = n.fy; n.vx = 0; n.vy = 0; }); - } - - // Recompute the STATIC layout for the current container width (called on resize + - // breakpoint re-dock). Positions are deterministic, so this just re-measures, re-lays, - // and re-fits — no reheat. - _knowRelayout() { - if (!this._knowGraph || this._knowEmpty) return; - let data = null; try { data = this._knowGraph.graphData(); } catch (e) { return; } - if (!data || !data.nodes) return; - this._knowLayout(data.nodes, data.links || []); - // clustered layout draws repo labels OUTBOARD (left of the leftmost column); give the - // fit extra padding so they survive. Fallback mode keeps its original padding. - this._knowFit(400, this._knowClustered ? 100 : 42); - this._knowScheduleGutterNudge(500); - } - - // Clustered fit is WIDTH-anchored: zoom so the columns + gutter fill the width - // (the same scaleW the layout converted its screen-px spacing floors through), - // then center a short stack or TOP-anchor a tall one — the user pans down for the - // rest. zoomToFit would instead shrink a tall stack until the constant screen-size - // labels overlap again, which is exactly the crowding this replaces. Non-clustered, - // empty, and mobile views keep the original fit-everything behavior. - _knowFit(ms, pad) { - const G = this._knowGraph; if (!G) return; - const geom = this._knowGeom; - if (!this._knowClustered || this._knowEmpty || !geom || this.state.isMobile) { - try { G.zoomToFit(ms, pad); } catch (e) {} - return; - } - let W = 0, H = 0; - try { const r = this._knowGraphEl.getBoundingClientRect(); W = r.width; H = r.height; } catch (e) {} - if (!W || !H) { try { G.zoomToFit(ms, pad); } catch (e) {} return; } - const k = Math.max(0.02, (W - geom.padL - geom.padR) / Math.max(1, geom.xA - geom.xF)); - const cx = geom.xF + (W / 2 - geom.padL) / k; // left edge lands at padL, agent labels keep padR - const fitsH = geom.totalH * k <= H - 60; - const cy = fitsH ? geom.top + geom.totalH / 2 : geom.top + (H / 2 - 56) / k; - try { G.zoom(k, ms); G.centerAt(cx, cy, ms); } catch (e) {} - } - - initKnowledgeGraph() { - if (this._knowGraph) { // reuse: refit + refetch (poll may have paused during the away) - const r = this._knowGraphEl.getBoundingClientRect(); - this._knowGraph.width(r.width).height(r.height); - try { if (this._knowGraph.resumeAnimation) this._knowGraph.resumeAnimation(); } catch (e) {} - this._knowFit(400, this._knowClustered ? 100 : 55); - this._knowScheduleGutterNudge(500); - this.fetchKnowledge(false); - return; - } - if (this._knowBuilding) return; // build-and-wait at most once while the lib downloads - this._knowBuilding = true; - let tries = 0; - const poll = () => { - if (this._knowGraph) return; - if (typeof window.ForceGraph === 'function') { this.buildKnowledgeGraph(); return; } - if (tries++ > 200) { this._knowBuilding = false; const l = this._learningRoot.querySelector('#lr-know-loading'); if (l) l.textContent = 'failed to load graph library'; return; } - setTimeout(poll, 50); - }; - poll(); + // ---- live feed: /api/state (graph) + /events (SSE) + /api/runs (list) ---- + connectLive() { + this.currentRunId = new URLSearchParams(location.search).get('run') || ''; + this.loadState(); + this.subscribeEvents(); } - - buildKnowledgeGraph() { - if (this._knowGraph) return; // only ever mount one instance - const esc = (s) => this._galaxyEsc(s); - const hexToRgb = (h) => { const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(h); return m ? [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)] : [160, 168, 220]; }; - const rgba = (h, a) => { const c = hexToRgb(h); return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; }; - const tooltip = (n) => { - if (n.type === 'evidence') return ''; // observation dots are non-interactive decoration - if (n.type === 'agent') return '
' + esc(n.label) + '
agent · ' + (n.facts || 0) + ' facts
'; - if (n.type === 'category') return '
' + esc(this._knowCatLabel(n.id)) + '
category hub
'; - if (n.type === 'cluster') return '
' + esc(n.label || n.id) + '
' + (n.__knowRole === 'root' || (!n.__knowRole && n.isParent) ? 'parent cluster' : (n.__knowRole === 'frontier' || (!n.__knowRole && n.parentId) ? 'subcluster' : 'cluster')) + ' · ' + (n.count || 0) + ' facts
'; - return '
fact
' + esc(String(n.content || '').slice(0, 120)) + '
'; - }; - // EDGE BUNDLES — the soul of the look. Every edge is a thin, low-alpha, additively - // blended QUADRATIC bezier whose control point is pulled toward the layout centerline - // (y=0) so each column-gap bundle bulges into a lens/waist. Colors are multi-hue by - // meaning; the translucent overlaps + 'lighter' blend glow at the dense waists. - const CURVE = 0.46; // 0..1: pull of the control point toward the centerline - const SUPBOW = 52; // sideways bow for same-column supersede edges - const ctrl = (s, t, kind) => { - const mx = (s.x + t.x) / 2, my = (s.y + t.y) / 2; - if (kind === 'supersede') return { x: mx - SUPBOW, y: my }; - return { x: mx, y: my * (1 - CURVE) }; - }; - const bez = (s, c, d, ph) => { const u = 1 - ph; return { x: u * u * s.x + 2 * u * ph * c.x + ph * ph * d.x, y: u * u * s.y + 2 * u * ph * c.y + ph * ph * d.y }; }; - const edgeStyle = (l) => { - switch (l.kind) { - case 'evidence': { const t = l.target; return { color: (t && t.repo) ? '#7dcfff' : '#e0af68', alpha: 0.15, width: 0.55 }; } // evidence->fact in the fact's scope hue - case 'category': return { color: '#bb9af7', alpha: 0.22, width: 0.6 }; // fact->category violet - case 'cluster': return { color: '#a99ac8', alpha: this._knowClustered ? 0.1 : 0.24, width: 0.52 }; // low-density membership fan - case 'subcluster':return { color: '#cabff2', alpha: 0.16, width: 0.52 }; // child->parent hierarchy edge - case 'catagent': { const c = Math.min(l.count || 1, 10); return { color: this._knowClustered ? '#c9e98a' : '#9ece6a', alpha: 0.16 + c * 0.04, width: 0.6 + c * 0.06 }; } - case 'link': { - const rel = l.factRelation || 'in', mult = rel === 'in' ? 1 : 0.4; - return { color: rel === 'in' ? '#6ec6ff' : (rel === 'cross' ? '#788fe1' : '#9678eb'), alpha: this._knowFactLinkAlpha(l.score) * mult, width: this._knowFactLinkWidth(l.score) }; - } - case 'supersede': return { color: '#f7768e', alpha: 0.42, width: 0.8 }; // supersede dim red - default: return { color: '#a0a8dc', alpha: 0.14, width: 0.5 }; - } - }; - const bandStub = (from, toward, band) => { - if (!band) return null; - const dx = toward.x - from.x, dy = toward.y - from.y, ts = []; - if (dx > 0) ts.push((band.galaxyX1 - from.x) / dx); else if (dx < 0) ts.push((band.galaxyX0 - from.x) / dx); - if (dy > 0) ts.push((band.y + band.h - from.y) / dy); else if (dy < 0) ts.push((band.y - from.y) / dy); - const valid = ts.filter(t => t > 0.001 && t <= 1).sort((a, b) => a - b); - const t = valid.length ? valid[0] : 0.15; - return { x: from.x + dx * t, y: from.y + dy * t }; - }; - const G = window.ForceGraph()(this._knowGraphEl) - .backgroundColor('#080a14') - .nodeRelSize(1) - .nodeLabel(tooltip) - .cooldownTicks(0) // STATIC: no physics — every node is pinned + committed - .warmupTicks(0) - .autoPauseRedraw(false) // keep the rAF loop alive for the packet animation - .nodeCanvasObjectMode(() => 'replace') - .nodeCanvasObject((n, ctx, scale) => { - if (n.type === 'cluster' && n.__knowVisible === false) return; - const sel = this._knowHoverFocus || this._knowSelected; - let dim = 1, hi = false; - if (sel) { if (n.id === sel.id || (sel.neighbors && sel.neighbors.has(n.id))) hi = true; else dim = 0.16; } - // EVIDENCE input layer: tiny dim observation dots, no glow / core / label. - if (n.type === 'evidence') { - let er = 1.4; const efl = 0.9 / scale; if (er < efl) er = efl; - ctx.beginPath(); ctx.arc(n.x, n.y, er, 0, 2 * Math.PI); - ctx.fillStyle = '#5a6088'; ctx.globalAlpha = (hi ? 0.85 : 0.42) * (sel && !hi ? 0.4 : 1); ctx.fill(); - ctx.globalAlpha = 1; return; - } - const col = this._knowColor(n); - let r = this._knowRadius(n); - // pixel-floor radii (graph-units are sub-pixel at fit zoom) so tiny nodes stay visible - const floor = (n.type === 'agent' ? 4 : (n.type === 'category' || n.type === 'cluster') ? 2.6 : 1.6) / scale; - if (r < floor) r = floor; - const blur = n.type === 'agent' ? 12 : (n.type === 'category' || n.type === 'cluster') ? 7 : (4 + Math.min(3, n.__knowDegree || 0) * 1.5); - if (this._knowClustered && n.type === 'fact' && n.superseded) { - ctx.shadowBlur = 0; ctx.beginPath(); ctx.arc(n.x, n.y, r + 0.4 / scale, 0, 2 * Math.PI); - ctx.strokeStyle = '#5a6088'; ctx.lineWidth = 1 / scale; ctx.globalAlpha = 0.58 * dim; ctx.stroke(); - } else { - ctx.shadowColor = col; ctx.shadowBlur = blur; - ctx.beginPath(); ctx.arc(n.x, n.y, r, 0, 2 * Math.PI); - ctx.fillStyle = col; ctx.globalAlpha = this._knowAlpha(n) * dim; ctx.fill(); - ctx.shadowBlur = 0; - ctx.beginPath(); ctx.arc(n.x, n.y, r * 0.5, 0, 2 * Math.PI); - ctx.fillStyle = '#ffffff'; ctx.globalAlpha = 0.4 * this._knowAlpha(n) * dim; ctx.fill(); - } - if (hi) { ctx.beginPath(); ctx.arc(n.x, n.y, r + 1.8, 0, 2 * Math.PI); ctx.strokeStyle = col; ctx.lineWidth = 1 / scale; ctx.globalAlpha = 0.9; ctx.stroke(); } - // Labels anchor sideways (never above/below) so stacked column nodes never - // collide with each other's labels. Clustered (option A) columns left -> - // right are FACT | CLUSTER | AGENT (repo scope is the band, not a node); - // CLUSTER labels sit RIGHT toward the open gap before the agents; AGENT - // labels sit right; CATEGORY (fallback view only) labels beside, mobile flip - // preserved below. - if (n.type === 'fact' && this._knowClustered) { - const hovered = this._knowHoveredFact === n.id; - if (hovered || n.__knowPersistentLabel) { - const fs = Math.max(3.2, 8.5 / scale); - ctx.font = '500 ' + fs + "px 'JetBrains Mono',monospace"; - ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; - ctx.fillStyle = hovered ? '#e9f7ff' : '#b4cce8'; - ctx.globalAlpha = hovered ? 1 : ((hi || !sel) ? 0.72 : 0.18); - ctx.fillText(n.key || n.id, n.x + r + 4 / scale, n.y - 6 / scale); - } - } else if (n.type === 'cluster') { - // Cluster labels sit RIGHT of the node. On mobile the canvas is replaced by - // the repo accordion, so this label never renders there anyway; desktop keeps - // the right-side label toward the empty gap before the agent column. - if (!this.state.isMobile) { - const isSub = n.__knowRole === 'frontier' || (!n.__knowRole && n.parentId); - const fs = Math.max(3.4, (isSub ? 8 : 9) / scale); - ctx.globalAlpha = (hi || !sel ? 0.92 : 0.45) * (dim < 1 ? dim : 1); - ctx.font = (n.isParent ? '600 ' : '500 ') + fs + "px 'JetBrains Mono',monospace"; - ctx.fillStyle = isSub ? '#a99ac8' : '#cabff2'; ctx.textBaseline = 'middle'; - if (isSub) { ctx.textAlign = 'right'; ctx.fillText(n.label || '', n.x - r - (4 / scale), n.y); } - else { ctx.textAlign = 'left'; ctx.fillText(n.label || '', n.x + r + (4 / scale), n.y); } - if (n.__knowExpandCount > 0) { - const bw = 27 / scale, bh = 14 / scale; - const bx = n.x + (isSub ? 17 : -17) / scale, by = n.y - 11 / scale; - ctx.beginPath(); ctx.roundRect(bx - bw / 2, by - bh / 2, bw, bh, 4 / scale); - ctx.fillStyle = 'rgba(18,20,38,0.96)'; ctx.globalAlpha = hi || !sel ? 1 : 0.45; ctx.fill(); - ctx.strokeStyle = isSub ? '#a99ac8' : '#cabff2'; ctx.lineWidth = 1 / scale; ctx.globalAlpha *= 0.7; ctx.stroke(); - ctx.font = '600 ' + (8 / scale) + "px 'JetBrains Mono',monospace"; - ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = isSub ? '#d2c5ec' : '#e0d9f5'; ctx.globalAlpha = hi || !sel ? 0.95 : 0.45; - ctx.fillText('+' + n.__knowExpandCount, bx, by + 0.25 / scale); - } - } - } else if (n.type === 'agent') { - const fs = Math.max(4.2, 11 / scale); - ctx.globalAlpha = (hi || !sel ? 1 : 0.5) * (dim < 1 ? dim : 1); - ctx.font = '600 ' + fs + "px 'Space Grotesk',sans-serif"; - ctx.fillStyle = col; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; - ctx.fillText(n.label || '', n.x + r + (4 / scale), n.y); - } else if (n.type === 'category') { - const fs = Math.max(3.4, 8 / scale); - ctx.globalAlpha = (hi || !sel ? 0.85 : 0.4) * (dim < 1 ? dim : 1); - ctx.font = '500 ' + fs + "px 'JetBrains Mono',monospace"; - ctx.fillStyle = '#cabff2'; ctx.textBaseline = 'middle'; - // On narrow (mobile) widths the category column sits only pixels from the agent - // column, so grow the label LEFT into the empty fact-gap instead of rightward - // across the gap into the agent glyphs/labels. Desktop keeps the right-side label. - if (this.state.isMobile) { ctx.textAlign = 'right'; ctx.fillText(n.label || '', n.x - r - (3 / scale), n.y); } - else { ctx.textAlign = 'left'; ctx.fillText(n.label || '', n.x + r + (3 / scale), n.y); } - } - ctx.globalAlpha = 1; - }) - .nodePointerAreaPaint((n, color, ctx) => { if (n.type === 'evidence' || (n.type === 'cluster' && n.__knowVisible === false)) return; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(n.x, n.y, this._knowRadius(n) + 4, 0, 2 * Math.PI); ctx.fill(); }) - // Links are drawn by hand in onRenderFramePre (curved + additive), not by force-graph. - .linkVisibility(false) - // ADDITIVE CURVED EDGE PASS — all bundles in ONE 'lighter' block, under the nodes, so - // overlapping translucent colors glow at the dense waists. - .onRenderFramePre((ctx, scale) => { - // REPO SWIMLANE BANDS (option A) — painted FIRST, source-over, under the - // additive edges + nodes. Each band = a faint repo-tinted rect + a left - // accent bar + a hairline separator + a short lane label and "N facts" - // sub-line anchored in the left gutter. General recedes (lower alpha, dashed). - if (this._knowClustered && !this._knowEmpty && this._knowBands && this._knowBands.length) { - ctx.save(); - const bsel = this._knowSelected; - for (let bi = 0; bi < this._knowBands.length; bi++) { - const bd = this._knowBands[bi]; - const rgb = hexToRgb(bd.color), rr = rgb[0], gg = rgb[1], bb = rgb[2]; - const isGen = bd.general; - const bw = bd.tintX1 - bd.tintX0; - ctx.fillStyle = 'rgba(' + rr + ',' + gg + ',' + bb + ',' + (isGen ? 0.035 : 0.06) + ')'; - ctx.fillRect(bd.tintX0, bd.y, bw, bd.h); - ctx.fillStyle = 'rgba(' + rr + ',' + gg + ',' + bb + ',' + (isGen ? 0.4 : 0.85) + ')'; - ctx.fillRect(bd.tintX0, bd.y + 2 / scale, 2.5 / scale, bd.h - 4 / scale); - ctx.strokeStyle = 'rgba(255,255,255,0.04)'; - ctx.lineWidth = 1 / scale; - ctx.setLineDash(isGen ? [3 / scale, 3 / scale] : []); - ctx.strokeRect(bd.tintX0 + 0.5 / scale, bd.y + 0.5 / scale, bw - 1 / scale, bd.h - 1 / scale); - ctx.setLineDash([]); - const active = bsel && bsel.id === bd.detail.id; - const labelCol = active ? bd.color : (isGen ? '#e0af68' : '#7dcfff'); // selected -> lane color, else the standard repo-label hue - ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; - ctx.font = '600 ' + (11 / scale) + "px 'Space Grotesk',sans-serif"; - ctx.fillStyle = labelCol; - ctx.fillText(bd.label, bd.labelX, bd.cy - 6 / scale); - ctx.font = '500 ' + (9 / scale) + "px 'Space Grotesk',sans-serif"; - ctx.fillStyle = '#5a6088'; - ctx.fillText(bd.factCount + ' fact' + (bd.factCount === 1 ? '' : 's'), bd.labelX, bd.cy + 7 / scale); - ctx.globalCompositeOperation = 'lighter'; - const clumps = bd.clumps || []; - for (let ci = 0; ci < clumps.length; ci++) { - const cl = clumps[ci], grad = ctx.createRadialGradient(cl.x, cl.y, 0, cl.x, cl.y, cl.r); - grad.addColorStop(0, 'rgba(80,125,185,0.055)'); grad.addColorStop(1, 'rgba(80,125,185,0)'); - ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(cl.x, cl.y, cl.r, 0, 2 * Math.PI); ctx.fill(); - } - ctx.globalCompositeOperation = 'source-over'; - } - ctx.restore(); - } - ctx.save(); ctx.globalCompositeOperation = 'lighter'; - let links = null; try { links = G.graphData().links; } catch (e) {} - if (links) { - const sel = this._knowHoverFocus || this._knowSelected; - for (let i = 0; i < links.length; i++) { - const l = links[i], s = l.source, t = l.target; - if (!s || !t || s.x == null || t.x == null) continue; - const sid = (s.id != null ? s.id : s), tid = (t.id != null ? t.id : t), key = sid + ' ' + tid; - if (l.kind === 'link') { - if (!this._knowFactLinksOn) continue; - const focused = !!(sel && sel.links && sel.links.has(key)); - if (l.factRelation === 'repo') { - const endpointHover = this._knowHoveredFact === sid || this._knowHoveredFact === tid; - const endpointSelected = !!(this._knowSelected && (this._knowSelected.id === sid || this._knowSelected.id === tid)); - const endpointFocus = endpointHover || endpointSelected; - if (!this._knowCrossRepoOn && !endpointFocus) continue; - const st = edgeStyle(l), alpha = endpointFocus ? Math.max(0.72, st.alpha + 0.48) : (focused ? 0.72 : (sel ? 0.02 : st.alpha)); - ctx.strokeStyle = rgba(st.color, alpha); ctx.lineWidth = Math.max(0.45 / scale, (st.width + (endpointFocus ? 0.55 : 0)) * 0.75 / scale); - ctx.setLineDash([3 / scale, 3 / scale]); - if (endpointFocus) { - const mx = (s.x + t.x) / 2, my = (s.y + t.y) / 2; - const dx = t.x - s.x, dy = t.y - s.y, mag = Math.hypot(dx, dy) || 1, bow = Math.min(24 / scale, mag * 0.06); - ctx.beginPath(); ctx.moveTo(s.x, s.y); ctx.quadraticCurveTo(mx - dy / mag * bow, my + dx / mag * bow, t.x, t.y); ctx.stroke(); - ctx.setLineDash([]); - continue; - } - const aStub = bandStub(s, t, s.__knowBand), bStub = bandStub(t, s, t.__knowBand); - if (aStub) { ctx.beginPath(); ctx.moveTo(s.x, s.y); ctx.lineTo(aStub.x, aStub.y); ctx.stroke(); ctx.fillStyle = rgba(st.color, Math.min(0.9, alpha + 0.2)); ctx.beginPath(); ctx.arc(aStub.x, aStub.y, 2 / scale, 0, 2 * Math.PI); ctx.fill(); } - if (bStub) { ctx.beginPath(); ctx.moveTo(t.x, t.y); ctx.lineTo(bStub.x, bStub.y); ctx.stroke(); ctx.fillStyle = rgba(st.color, Math.min(0.9, alpha + 0.2)); ctx.beginPath(); ctx.arc(bStub.x, bStub.y, 2 / scale, 0, 2 * Math.PI); ctx.fill(); } - ctx.setLineDash([]); - continue; - } - const st = edgeStyle(l); - let alpha = focused ? Math.min(0.9, st.alpha + 0.48) : (sel ? 0.02 : st.alpha); - let width = st.width + (focused ? 0.55 : 0); - const mx = (s.x + t.x) / 2, my = (s.y + t.y) / 2; - ctx.beginPath(); ctx.moveTo(s.x, s.y); - if (l.factRelation === 'cross') { - const dx = t.x - s.x, dy = t.y - s.y, mag = Math.hypot(dx, dy) || 1, bow = Math.min(18 / scale, mag * 0.08); - ctx.quadraticCurveTo(mx - dy / mag * bow, my + dx / mag * bow, t.x, t.y); - } else ctx.lineTo(t.x, t.y); - ctx.strokeStyle = rgba(st.color, alpha); ctx.lineWidth = Math.max(width / scale, 0.35 / scale); ctx.stroke(); - continue; - } - if (l.kind === 'cluster' && this._knowClustered) { - const fact = s.type === 'fact' ? s : (t.type === 'fact' ? t : null); - if (fact && fact.__knowBand && fact.__knowBand.factCount > 40 && this._knowHoveredFact !== fact.id) continue; - } - const st = edgeStyle(l); - let alpha = st.alpha, width = st.width; - if (sel) { - if (sel.links && sel.links.has(key)) { alpha = Math.min(1, alpha + 0.4); width += 0.5; } - else alpha = 0.035; - } - const c = ctrl(s, t, l.kind); - ctx.beginPath(); ctx.moveTo(s.x, s.y); ctx.quadraticCurveTo(c.x, c.y, t.x, t.y); - ctx.strokeStyle = rgba(st.color, alpha); - ctx.lineWidth = Math.max(width / scale, 0.35 / scale); - ctx.stroke(); - } - } - ctx.restore(); - }) - .onEngineStop(() => { - if (this._knowNeedFit && !this._knowFitDone) { this._knowFitDone = true; this._knowNeedFit = false; this._knowFit(600, this._knowEmpty ? 60 : (this._knowClustered ? 100 : 42)); this._knowScheduleGutterNudge(700); } - this._knowPinned = true; - // static layout: drop the (unused) layout forces so nothing can ever perturb the pins - try { G.d3Force('charge', null); G.d3Force('link', null); G.d3Force('center', null); } catch (e) {} - }) - // SPARSE LEFT->RIGHT PACKETS along the curved evidence->fact and category->agent - // bundles — the only motion in the otherwise-static picture. Flow-link sets cached by - // signature; gated on the Knowledge view being active (galaxy idle-perf lessons). - .onRenderFramePost((ctx, scale) => { - if (this._knowEmpty) return; - if (this.state.view !== 'brain') return; - let all = null; try { all = G.graphData().links; } catch (e) {} - if (!all) return; - if (this._knowFlowSig !== this._knowSig) { - this._knowFlowSig = this._knowSig; - const ev = [], ow = []; - for (let i = 0; i < all.length; i++) { const l = all[i]; if (l.kind === 'evidence') { if (l.__pf == null) l.__pf = (i * 0.6180339887) % 1; ev.push(l); } else if (l.kind === 'catagent') { if (l.__pf == null) l.__pf = (i * 0.6180339887) % 1; ow.push(l); } } - this._knowFlowEv = ev; this._knowFlowOw = ow; - } - const t = Date.now() / 1000; - ctx.save(); ctx.globalCompositeOperation = 'lighter'; - // evidence flow: sparse, dim (1 slow packet per filament, rides the curve) - const evs = this._knowFlowEv || [], Re = 1.4 / scale; - for (let i = 0; i < evs.length; i++) { const l = evs[i], s = l.source, d = l.target; if (!s || !d || s.x == null || d.x == null) continue; const c = ctrl(s, d, 'evidence'); const ph = (t * 0.12 + l.__pf) % 1; const p = bez(s, c, d, ph); ctx.beginPath(); ctx.arc(p.x, p.y, Re, 0, 2 * Math.PI); ctx.fillStyle = '#9aa0d8'; ctx.globalAlpha = 0.22; ctx.fill(); } - // owner flow (category->agent): brighter green, 2 packets with a hot core - const ows = this._knowFlowOw || [], Ro = 2.6 / scale, NP = 2; - for (let i = 0; i < ows.length; i++) { const l = ows[i], s = l.source, d = l.target; if (!s || !d || s.x == null || d.x == null) continue; const c = ctrl(s, d, 'catagent'); for (let k = 0; k < NP; k++) { const ph = (t * 0.28 + k / NP + l.__pf) % 1; const p = bez(s, c, d, ph); ctx.beginPath(); ctx.arc(p.x, p.y, Ro, 0, 2 * Math.PI); ctx.fillStyle = '#9ece6a'; ctx.globalAlpha = 0.5; ctx.fill(); ctx.beginPath(); ctx.arc(p.x, p.y, Ro * 0.5, 0, 2 * Math.PI); ctx.fillStyle = '#e8ffd0'; ctx.globalAlpha = 0.9; ctx.fill(); } } - ctx.globalAlpha = 1; ctx.restore(); - }) - .enableNodeDrag(false); - const r = this._knowGraphEl.getBoundingClientRect(); - G.width(r.width).height(r.height); - this._knowGraph = G; - // CUSTOM HIT-TESTING (force-graph's built-in picking is unusable at this scale): - // drive hover-cursor + click from pointer events via knowledgeNodeAt (screen-space). + subscribeEvents() { + try { if (this._es) this._es.close(); } catch (e) {} try { - const el = this._knowGraphEl; - let downX = 0, downY = 0, dragged = false; - el.addEventListener('pointerdown', (e) => { downX = e.clientX; downY = e.clientY; dragged = false; this._knowNudgeCancel(); }); - // A user pan/zoom must win over a pending gutter nudge (a one-shot centerAt fired - // 500-700ms after a fit), so cancel it on any direct interaction with the canvas. - el.addEventListener('wheel', () => this._knowNudgeCancel(), { passive: true }); - el.addEventListener('pointermove', (e) => { - if (e.buttons && (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4)) dragged = true; - this._knowPointer = { x: e.clientX, y: e.clientY }; - if (this._knowHoverRAF) return; - this._knowHoverRAF = requestAnimationFrame(() => { - this._knowHoverRAF = 0; - const p = this._knowPointer; if (!p) return; - const badge = this.knowledgeExpandBadgeAt(p.x, p.y); - const node = badge ? null : this.knowledgeNodeAt(p.x, p.y); - this._knowSetHoveredFact(node && node.type === 'fact' ? node : null); - const hit = badge || node || this.knowledgeBandAt(p.x, p.y); - try { el.style.cursor = hit ? 'pointer' : 'default'; } catch (e2) {} - }); - }); - el.addEventListener('pointerup', (e) => { - if (dragged) return; - const badge = this.knowledgeExpandBadgeAt(e.clientX, e.clientY); - if (badge) { this._knowExpandCluster(badge.id); return; } - // Try NODES first: the band label region reaches to pf.x - 6 while fact nodes carry - // an 11px hit threshold, so a ~5px sliver left of a fact center would otherwise let - // the band swallow a fact click. Band labels live in the gutter (far from nodes), so - // node-first costs the band nothing; fall back to the band only when no node is hit. - const node = this.knowledgeNodeAt(e.clientX, e.clientY); - if (node) { this.openKnowledgeDetail(node); return; } - const band = this.knowledgeBandAt(e.clientX, e.clientY); - if (band) { this.openKnowledgeDetail(band.detail); return; } - this.closeKnowledgeDetail(); - this._knowCollapseHierarchy(); - }); - el.addEventListener('pointerleave', () => { if (this._knowHoverRAF) { try { cancelAnimationFrame(this._knowHoverRAF); } catch (e2) {} this._knowHoverRAF = 0; } this._knowPointer = null; this._knowSetHoveredFact(null); try { el.style.cursor = 'default'; } catch (e2) {} }); + const run = this.currentRunId || ''; + this._es = new EventSource('/events' + (run ? '?run=' + encodeURIComponent(run) : '')); + this._es.onmessage = (e) => { try { this.applyState(JSON.parse(e.data)); } catch (_) {} }; } catch (e) {} - this.fetchKnowledge(false); - } - - // Nearest node to a client point in SCREEN space, within a per-type pixel radius - // (adapts galaxyNodeAt). Screen-space thresholds stay constant px at any zoom. - knowledgeNodeAt(clientX, clientY) { - const G = this._knowGraph; if (!G) return null; - let el = null; try { el = this._knowGraphEl.querySelector('canvas'); } catch (e) {} - if (!el) el = this._knowGraphEl; if (!el) return null; - const rect = el.getBoundingClientRect(); - const cx = clientX - rect.left, cy = clientY - rect.top; - let nodes = null; try { nodes = (G.graphData() || {}).nodes; } catch (e) {} - if (!nodes) return null; - let best = null, bestScore = Infinity; - for (let i = 0; i < nodes.length; i++) { - const n = nodes[i]; if (n.x == null || n.y == null) continue; - if (n.type === 'evidence') continue; // input-layer dots are non-interactive - if (n.type === 'cluster' && n.__knowVisible === false) continue; - let sp; try { sp = G.graph2ScreenCoords(n.x, n.y); } catch (e) { continue; } - const dx = sp.x - cx, dy = sp.y - cy; const d = Math.sqrt(dx * dx + dy * dy); - const boost = this._coarsePointer ? 1.4 : 1; - const thr = (n.type === 'agent' ? 20 : (n.type === 'category' || n.type === 'cluster') ? 14 : 11) * boost; - if (d > thr) continue; - const score = d / thr; - if (score < bestScore) { bestScore = score; best = n; } - } - return best; - } - - knowledgeExpandBadgeAt(clientX, clientY) { - const G = this._knowGraph; if (!G || this.state.isMobile) return null; - let el = null; try { el = this._knowGraphEl.querySelector('canvas'); } catch (e) {} - if (!el) el = this._knowGraphEl; if (!el) return null; - const rect = el.getBoundingClientRect(), cx = clientX - rect.left, cy = clientY - rect.top; - let nodes = null; try { nodes = (G.graphData() || {}).nodes; } catch (e) {} - if (!nodes) return null; - for (let i = 0; i < nodes.length; i++) { - const n = nodes[i]; if (n.type !== 'cluster' || n.__knowVisible === false || !(n.__knowExpandCount > 0) || n.x == null || n.y == null) continue; - let sp; try { sp = G.graph2ScreenCoords(n.x, n.y); } catch (e) { continue; } - const isSub = n.__knowRole === 'frontier' || (!n.__knowRole && n.parentId); - const bx = sp.x + (isSub ? 17 : -17), by = sp.y - 11; - if (Math.abs(cx - bx) <= 17 && Math.abs(cy - by) <= 11) return n; - } - return null; - } - - _knowExpandCluster(id) { - const h = this._knowHierarchy; if (!h || !(h.children[id] || []).length) return; - if (!this._knowExpanded) this._knowExpanded = {}; - this._knowExpanded[id] = true; - this.renderKnowledge(true); - } - - _knowCollapseHierarchy() { - const expanded = this._knowExpanded || {}; - if (!Object.keys(expanded).some(id => expanded[id])) return false; - this._knowExpanded = {}; - this.renderKnowledge(true); - return true; - } - - _knowSetHoveredFact(node) { - const id = node && node.type === 'fact' ? node.id : ''; - if ((this._knowHoveredFact || '') === id) return; - this._knowHoveredFact = id; - this._knowHoverFocus = id && this._knowHoverByFact ? (this._knowHoverByFact[id] || null) : null; - try { if (this._knowGraph && this._knowGraph.refresh) this._knowGraph.refresh(); } catch (e) {} - } - - // Repo swimlane label hit-test (option A). Converts each band's rect corners - // graph -> screen and matches a pointer against a GENEROUS label region: the left - // tint edge across the gutter (to the facts column, capped ~120px) at the band's - // full height. Returns the band (with its synthetic .detail) or null. Clustered - // desktop only — mobile uses the accordion, the fallback view has no bands. - knowledgeBandAt(clientX, clientY) { - if (!this._knowClustered || this._knowEmpty || this.state.isMobile) return null; - const bands = this._knowBands; if (!bands || !bands.length) return null; - const G = this._knowGraph; if (!G) return null; - let el = null; try { el = this._knowGraphEl.querySelector('canvas'); } catch (e) {} - if (!el) el = this._knowGraphEl; if (!el) return null; - const rect = el.getBoundingClientRect(); - const cx = clientX - rect.left, cy = clientY - rect.top; - for (let i = 0; i < bands.length; i++) { - const bd = bands[i]; - let p0, p1, pf; try { p0 = G.graph2ScreenCoords(bd.tintX0, bd.y); p1 = G.graph2ScreenCoords(bd.tintX1, bd.y + bd.h); pf = G.graph2ScreenCoords(bd.factX, bd.y); } catch (e) { continue; } - const x0 = p0.x - 6; - const xR = Math.min(p0.x + 120, pf.x - 6); // don't reach into the facts column - const yA = Math.min(p0.y, p1.y), yB = Math.max(p0.y, p1.y); - if (cx >= x0 && cx <= xR && cy >= yA && cy <= yB) return bd; - } - return null; } - - // After a zoomToFit settles, nudge the clustered view RIGHT just enough that no - // band label sits under the bottom-left legend chip (the design's reserved-gutter - // rule: the legend must never cover band labels). zoomToFit centers the node bbox, - // so at narrow widths the smallest (bottom) band's gutter can land behind the - // legend — measure the real overlap and pan only what the right edge can spare. - _knowScheduleGutterNudge(delayMs) { - clearTimeout(this._knowNudgeT); - this._knowNudgeT = setTimeout(() => this._knowEnsureGutterClear(200), delayMs); + loadState() { + const run = this.currentRunId || ''; + fetch('/api/state' + (run ? '?run=' + encodeURIComponent(run) : '')) + .then(r => r.ok ? r.json() : null) + .then(s => { if (s && (this.currentRunId || '') === run) this.applyState(s); }) // drop stale after a switch + .catch(() => {}); } - // Cancel a pending one-shot gutter nudge so a user pan/zoom is never overridden. - _knowNudgeCancel() { clearTimeout(this._knowNudgeT); this._knowNudgeT = null; } - _knowEnsureGutterClear(ms) { - try { - if (!this._knowClustered || this._knowEmpty || this.state.isMobile) return; - const bands = this._knowBands; if (!bands || !bands.length) return; - const G = this._knowGraph, root = this._learningRoot; if (!G || !root) return; - const el = this._knowGraphEl; const rect = el.getBoundingClientRect(); if (!rect.width) return; - const legend = root.querySelector('#lr-know-legend'); - if (!legend || legend.style.display === 'none') return; - const lr = legend.getBoundingClientRect(); if (!lr.width) return; - let need = 0; - for (let i = 0; i < bands.length; i++) { - const bd = bands[i]; - const p0 = G.graph2ScreenCoords(bd.tintX0, bd.y), p1 = G.graph2ScreenCoords(bd.tintX1, bd.y + bd.h); - const yA = Math.min(p0.y, p1.y) + rect.top, yB = Math.max(p0.y, p1.y) + rect.top; - if (yB < lr.top || yA > lr.bottom) continue; // band doesn't cross the legend row - const dx = (lr.right - rect.left + 10) - p0.x; - if (dx > need) need = dx; - } - if (need <= 0) return; - const k = G.zoom(); if (!k) return; - // Cap the shift so the agent labels keep their full reserved room at the right - // edge (the clustered fit reserves geom.padR for the constant-size labels — - // eating into it here is what used to clip them after the nudge). - let slack = Infinity; - const rpad = (this._knowGeom && this._knowGeom.padR) ? this._knowGeom.padR : 100; - try { const bb = G.getGraphBbox(); const rEdge = G.graph2ScreenCoords(bb.x[1], 0).x; slack = Math.max(0, rect.width - rpad - rEdge); } catch (e) {} - const shift = Math.min(need, slack); - if (shift <= 0.5) return; - const c = G.centerAt(); - G.centerAt(c.x - shift / k, c.y, ms || 200); - } catch (e) {} - } - - fetchKnowledge(isPoll) { - fetch('/api/learning/knowledge', { cache: 'no-store' }) - .then(r => r.ok ? r.text() : Promise.reject(new Error('HTTP ' + r.status))) - .then(txt => { - if (isPoll && this._knowRawSig === txt) return; // unchanged — leave the layout/loop alone - this._knowRawSig = txt; - let json = null; try { json = JSON.parse(txt); } catch (e) { json = null; } - this._knowRaw = json || { agents: [], facts: [], edges: [] }; - this.renderKnowledge(isPoll); - const l = this._learningRoot && this._learningRoot.querySelector('#lr-know-loading'); - if (l) { l.classList.add('hidden'); setTimeout(() => { l.style.display = 'none'; }, 600); } - }) - .catch(err => { - if (isPoll) return; // keep the current graph on a transient poll failure - const l = this._learningRoot && this._learningRoot.querySelector('#lr-know-loading'); - if (l) { l.classList.remove('hidden'); l.style.display = 'flex'; l.textContent = 'could not load /api/learning/knowledge (' + (err && err.message) + ')'; } - }); - } - - // Normalize arbitrary-depth cluster ancestry once per payload. All hierarchy - // consumers read this index so dangling parents, cycles and pathological chains - // cannot produce different answers in layout, ownership, isolate or details. - _knowBuildHierarchyIndex(clusters) { - const rawById = {}, ids = []; - clusters.forEach(c => { if (c && c.id && !rawById[c.id]) { rawById[c.id] = c; ids.push(c.id); } }); - ids.sort(); - const parent = {}; - ids.forEach(id => { - const p = rawById[id] && rawById[id].parent_id; - parent[id] = (p && p !== id && rawById[p]) ? p : ''; - }); - const walkCap = Math.max(16, Math.min(512, ids.length + 1)); - // Break one stable edge in every cycle. Repeating from sorted starts makes the - // normalized forest independent of payload ordering. - ids.forEach(start => { - let cur = start, steps = 0; - const order = [], pos = {}; - while (cur && steps++ < walkCap) { - if (pos[cur] != null) { - const cyc = order.slice(pos[cur]).sort(); - if (cyc.length) parent[cyc[0]] = ''; - break; - } - pos[cur] = order.length; order.push(cur); cur = parent[cur] || ''; - } - if (cur && order.length) parent[order.slice().sort()[0]] = ''; - }); - const children = {}; ids.forEach(id => { children[id] = []; }); - ids.forEach(id => { const p = parent[id]; if (p && children[p]) children[p].push(id); }); - ids.forEach(id => children[id].sort()); - const roots = ids.filter(id => !parent[id]); - const chain = {}, root = {}, depth = {}; - ids.forEach(id => { - const rev = [], seen = {}; let cur = id, steps = 0; - while (cur && !seen[cur] && steps++ < walkCap) { seen[cur] = 1; rev.push(cur); cur = parent[cur] || ''; } - const path = rev.reverse(); chain[id] = path; root[id] = path[0] || id; depth[id] = Math.max(0, path.length - 1); - }); - const descendants = {}, leaves = {}, subtreeDepth = {}; - ids.forEach(id => { - const out = [], stack = (children[id] || []).slice().reverse(), seen = {}; - let steps = 0; - while (stack.length && steps++ < walkCap * Math.max(1, ids.length)) { - const cur = stack.pop(); if (!cur || seen[cur]) continue; seen[cur] = 1; out.push(cur); - const ch = children[cur] || []; for (let i = ch.length - 1; i >= 0; i--) stack.push(ch[i]); - } - descendants[id] = out; - const all = [id].concat(out); - leaves[id] = all.filter(cid => !(children[cid] || []).length); - let max = 0; out.forEach(cid => { max = Math.max(max, (depth[cid] || 0) - (depth[id] || 0)); }); - subtreeDepth[id] = max; - }); - return { rawById: rawById, ids: ids, parent: parent, children: children, roots: roots, chain: chain, root: root, depth: depth, descendants: descendants, leaves: leaves, subtreeDepth: subtreeDepth, walkCap: walkCap, hasSplits: ids.some(id => !!parent[id]), hasDeep: ids.some(id => (depth[id] || 0) > 1) }; - } - - // The two-column progressive frontier. Shallow trees retain today's direct - // children exactly. A deep tree starts at its leaves; expanding a visible hub - // replaces that branch with its direct children inside the same sub-column. - _knowHierarchyFrontier(rootId) { - const h = this._knowHierarchy, children = h && h.children[rootId] ? h.children[rootId] : []; - if (!h || !children.length) return []; - if ((h.subtreeDepth[rootId] || 0) <= 1) return children.slice(); - const expanded = this._knowExpanded || {}; - if (!expanded[rootId]) return (h.leaves[rootId] || []).filter(id => id !== rootId); - const out = []; - const visit = (id, guard) => { - if (guard > h.walkCap) return; - const ch = h.children[id] || []; - if (ch.length && expanded[id]) ch.forEach(cid => visit(cid, guard + 1)); - else out.push(id); - }; - children.forEach(id => visit(id, 0)); - return out; - } - - _knowHierarchyDisplayFor(clusterId, frontier) { - const h = this._knowHierarchy; if (!h || !h.chain[clusterId]) return clusterId; - const visible = {}; (frontier || []).forEach(id => { visible[id] = 1; }); - const path = h.chain[clusterId]; - for (let i = path.length - 1; i >= 0; i--) if (visible[path[i]]) return path[i]; - return h.root[clusterId] || clusterId; - } - - // Build the graph node/link arrays for the 4 columns. Agents + facts become nodes; - // the server's `cat:` category-edge targets become 'category' hub nodes; the - // owner edges are dropped in favour of a client-DERIVED category->agent layer; and an - // evidence input layer is synthesized from each fact's witness count. - _knowBuild(raw) { - const agents = Array.isArray(raw.agents) ? raw.agents : []; - const allFacts = Array.isArray(raw.facts) ? raw.facts : []; - const facts = this._knowHistoryOn ? allFacts : allFacts.filter(f => f && !f.superseded); - const visibleFact = {}; facts.forEach(f => { if (f && f.id) visibleFact[f.id] = 1; }); - const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter(e => { - if (!e || !visibleFact[e.source]) return false; - return e.kind !== 'supersede' && e.kind !== 'link' ? true : !!visibleFact[e.target]; - }); - const clusters = Array.isArray(raw.clusters) ? raw.clusters : []; - // Detail panels look facts/clusters up by id (member lists + [[wikilink]] jumps). - this._knowFactById = {}; facts.forEach(f => { if (f && f.id) this._knowFactById[f.id] = f; }); - this._knowClusterById = {}; clusters.forEach(c => { if (c && c.id) this._knowClusterById[c.id] = c; }); - this._knowHierarchy = this._knowBuildHierarchyIndex(clusters); - this._knowHasSplits = this._knowHierarchy.hasSplits; - // CLUSTERED MODE (Knowledge graph v2, gitmoot #763): a gitmoot build that emits - // emergent clusters drives the repo -> cluster -> fact proportional layered view. - // A pre-cluster build emits no clusters, so we fall back to the scope/category - // columns below (unknown-field tolerance — the new UI must not crash old binaries). - this._knowClustered = clusters.length > 0; - if (this._knowClustered) return this._knowBuildClustered(raw, agents, facts, edges, clusters); - const nodes = [], seen = {}; - agents.forEach(a => { if (a && !seen[a.name]) { seen[a.name] = 1; nodes.push({ id: a.name, type: 'agent', label: a.name, enrolled: !!a.enrolled, facts: a.facts || 0, observations: a.observations || 0 }); } }); - facts.forEach(f => { if (f && !seen[f.id]) { seen[f.id] = 1; nodes.push({ id: f.id, type: 'fact', label: f.id, content: f.content || '', repo: f.repo || '', key: f.key || '', owner: f.owner || '', witnesses: f.witnesses || 0, firstSeen: f.firstSeen || 0, lastSeen: f.lastSeen || 0, superseded: !!f.superseded }); } }); - const ownerByFact = {}; facts.forEach(f => { if (f) ownerByFact[f.id] = f.owner || ''; }); - const links = []; - // fact->category (violet) + supersede (red). The server's owner edges (fact->agent) - // are NOT drawn directly — they'd skip the category column — but are re-expressed as - // the DERIVED category->agent layer below. - const catAgent = {}; // "catId|agent" -> owned-fact count (drives the derived edge alpha) - edges.forEach(e => { - if (!e || e.source == null || e.target == null) return; - if (e.kind === 'owner') return; // replaced by the derived category->agent layer - if (e.kind === 'link') return; // fact galaxy links are clustered-mode only - if (e.kind === 'category') { - if (!seen[e.target]) { seen[e.target] = 1; nodes.push({ id: e.target, type: 'category', label: this._knowCatLabel(e.target) }); } - links.push({ source: e.source, target: e.target, kind: 'category' }); - const ag = ownerByFact[e.source]; - if (ag && seen[ag]) { const k = e.target + '|' + ag; catAgent[k] = (catAgent[k] || 0) + 1; } - return; - } - // supersede (fact->fact) + any other kind: endpoints are already fact nodes - [e.source, e.target].forEach(id => { if (!seen[id]) { seen[id] = 1; nodes.push({ id: id, type: 'category', label: this._knowCatLabel(id) }); } }); - links.push({ source: e.source, target: e.target, kind: e.kind || '' }); - }); - // DERIVED category->agent layer (green): one edge per (category, owning agent) so the - // 3rd->4th column reads as ownership fans; the fact count rides on the link for alpha. - Object.keys(catAgent).forEach(k => { const i = k.indexOf('|'); const cat = k.slice(0, i), ag = k.slice(i + 1); if (seen[cat] && seen[ag]) links.push({ source: cat, target: ag, kind: 'catagent', count: catAgent[k] }); }); - // EVIDENCE input layer (client-synthesized): min(witnesses,5) dim observation dots per - // fact, each linked fact-ward. Deterministic seeded offsets (no Math.random) so a poll - // never reshuffles the input column. - facts.forEach(f => { - if (!f) return; - const k = Math.min(Math.max(0, f.witnesses || 0), 5); - for (let i = 0; i < k; i++) { - const id = 'ev:' + f.id + ':' + i; - if (seen[id]) continue; seen[id] = 1; - nodes.push({ id: id, type: 'evidence', factId: f.id, __eox: (this._knowRand(id + 'x') - 0.5) * 22, __eoy: (this._knowRand(id + 'y') - 0.5) * 20 }); - links.push({ source: id, target: f.id, kind: 'evidence' }); // evidence->fact reads left->right - } - }); - return { nodes: nodes, links: links, agentCount: agents.length, factCount: facts.length }; - } - - // Map a fact/cluster repo scope to its repo-hub node id ("" = the general bucket). - _knowRepoNodeId(scope) { return scope ? 'repo:' + scope : 'repo:~general'; } - - // Unknown-cluster facts get one synthetic hub per repo lane. The legacy id remains - // the general bucket so repo-less payloads preserve their existing graph identity. - _knowUnclusteredNodeId(scope) { return scope ? 'cluster:~unclustered:' + encodeURIComponent(scope) : 'cluster:~unclustered'; } - - // CLUSTERED build (Knowledge graph v2, gitmoot #763): repo -> cluster -> fact -> - // owner-agent. Repo hubs are the leftmost column (derived from cluster/fact scopes), - // cluster hubs the 2nd column, facts the 3rd column, agents the rightmost column. - // Facts with no cluster fall into a synthesized 'unclustered' hub so they are - // still visibly grouped (never silently dropped). - _knowBuildClustered(raw, agents, facts, edges, clusters) { - if (this._knowHasSplits) return this._knowBuildClusteredSplit(raw, agents, facts, edges, clusters); - return this._knowBuildClusteredFlat(raw, agents, facts, edges, clusters); - } - - // Preserve the backend's undirected, once-per-pair fact wiki links. Invalid or - // dangling pairs are ignored defensively; the live server may not emit this - // additive edge kind yet, so an empty result is a normal constellation input. - _knowAppendFactLinks(edges, seen, links) { - let count = 0; - const pairs = {}; - edges.forEach(e => { - if (!e || e.kind !== 'link' || !seen[e.source] || !seen[e.target] || e.source === e.target) return; - if (!this._knowFactById[e.source] || !this._knowFactById[e.target]) return; - const a = e.source < e.target ? e.source : e.target, b = e.source < e.target ? e.target : e.source; - const rawScore = Number(e.score); if (!isFinite(rawScore) || rawScore <= 0) return; - const pair = a + '|' + b; if (pairs[pair]) return; pairs[pair] = 1; - const score = this._knowClamp(rawScore, 0, 1); - links.push({ source: e.source, target: e.target, kind: 'link', score: score }); - count++; - }); - return count; - } - - // Original no-parent implementation. Keeping this path byte-for-byte in behavior is - // the hierarchy regression bar: payloads without parent_id render exactly as before. - _knowBuildClusteredFlat(raw, agents, facts, edges, clusters) { - const nodes = [], links = [], seen = {}; - // --- repo scopes (option A: repo swimlanes): still counted for the header pill, - // but no longer materialized as graph nodes — each distinct CLUSTER scope becomes - // a horizontal band painted behind its clusters + facts (see this._knowRepoBands - // built below + the band-paint pass in onRenderFramePre). --- - const repoScopes = {}; - clusters.forEach(c => { if (c) repoScopes[c.repo || ''] = 1; }); - facts.forEach(f => { if (f) repoScopes[f.repo || ''] = 1; }); - // --- cluster hubs (server-provided) + a synthetic 'unclustered' hub if needed --- - const clusterById = {}; - clusters.forEach(c => { - if (!c || !c.id || seen[c.id]) return; seen[c.id] = 1; - const node = { id: c.id, type: 'cluster', label: c.label || c.id, count: c.count || 0, repo: c.repo || '', medoid: c.medoid || '' }; - clusterById[c.id] = node; nodes.push(node); - }); - const ensureUnclustered = (scope) => { - scope = scope || ''; - const id = this._knowUnclusteredNodeId(scope); - if (seen[id]) return clusterById[id]; - seen[id] = 1; - const node = { id: id, type: 'cluster', label: 'unclustered', count: 0, repo: scope, medoid: '' }; - clusterById[id] = node; nodes.push(node); - return node; - }; - // --- agent wells (right rail) --- - agents.forEach(a => { if (a && a.name && !seen[a.name]) { seen[a.name] = 1; nodes.push({ id: a.name, type: 'agent', label: a.name, enrolled: !!a.enrolled, facts: a.facts || 0, observations: a.observations || 0 }); } }); - // --- fact leaves + fact->cluster + cluster->agent (owner) links --- - const clusterAgent = {}; // "clusterId|agent" -> owned-fact count (drives owner-fan alpha) - facts.forEach(f => { - if (!f || !f.id || seen[f.id]) return; seen[f.id] = 1; - let cid = f.cluster || ''; - if (!cid || !clusterById[cid]) { const u = ensureUnclustered(f.repo || ''); cid = u.id; u.count += 1; } - nodes.push({ id: f.id, type: 'fact', label: f.id, content: f.content || '', repo: f.repo || '', key: f.key || '', owner: f.owner || '', witnesses: f.witnesses || 0, firstSeen: f.firstSeen || 0, lastSeen: f.lastSeen || 0, superseded: !!f.superseded, cluster: cid, sourceJob: f.sourceJob || '', sourceFile: f.sourceFile || '', links: Array.isArray(f.links) ? f.links : [] }); - links.push({ source: f.id, target: cid, kind: 'cluster' }); - if (f.owner && seen[f.owner]) { const k = cid + '|' + f.owner; clusterAgent[k] = (clusterAgent[k] || 0) + 1; } - }); - // --- derived cluster->agent owner fans (green, count-weighted; reuses catagent) --- - Object.keys(clusterAgent).forEach(k => { const i = k.indexOf('|'); const cid = k.slice(0, i), ag = k.slice(i + 1); if (seen[cid] && seen[ag]) links.push({ source: cid, target: ag, kind: 'catagent', count: clusterAgent[k] }); }); - // --- supersede chains (fact->fact) carried straight through --- - edges.forEach(e => { if (e && e.kind === 'supersede' && seen[e.source] && seen[e.target]) links.push({ source: e.source, target: e.target, kind: 'supersede' }); }); - const factLinkCount = this._knowAppendFactLinks(edges, seen, links); - // --- repo bands (option A): one swimlane per distinct CLUSTER repo scope. Each - // band owns the clusters carrying that scope + the facts inside those clusters - // (cross-repo fact membership is real — a general fact can live in an acme - // cluster's band). Bands sort biggest-first (general recedes to the bottom) and - // each carries a SYNTHETIC repo detail object so a band-label tap opens the repo - // detail panel with no graph node behind it. --- - const clusterNodesList = nodes.filter(n => n.type === 'cluster'); - const bandMap = {}; - clusterNodesList.forEach(c => { - const scope = c.repo || ''; - let bm = bandMap[scope]; - if (!bm) bm = bandMap[scope] = { scope: scope, label: this._knowRepoShort(scope), color: this._knowRepoColor(scope), general: scope === '', clusters: [], clusterIds: [], factCount: 0 }; - bm.clusters.push({ id: c.id, label: c.label || c.id, count: c.count || 0 }); - bm.clusterIds.push(c.id); - }); - const clusterScope = {}; clusterNodesList.forEach(c => { clusterScope[c.id] = c.repo || ''; }); - // Stash the cluster -> band-scope map so the repo detail panel can list a band's - // members by the SAME dominant-scope rule the band build uses (not each fact's own - // repo), keeping panel == band == highlight. Cluster ids missing from this map fell - // into the unclustered bucket (scope ''). - this._knowClusterScope = clusterScope; - nodes.forEach(n => { if (n.type !== 'fact') return; const sc = clusterScope[n.cluster]; if (sc != null && bandMap[sc]) bandMap[sc].factCount += 1; }); - const bandList = Object.keys(bandMap).map(k => bandMap[k]); - bandList.sort((a, c) => { - if (a.factCount !== c.factCount) return c.factCount - a.factCount; // biggest band on top - if (a.general !== c.general) return a.general ? 1 : -1; // general recedes to the bottom - return a.scope < c.scope ? -1 : a.scope > c.scope ? 1 : 0; - }); - bandList.forEach(bm => { bm.detail = { type: 'repo', id: this._knowRepoNodeId(bm.scope), repoName: bm.scope, general: bm.general, label: bm.scope || 'general' }; }); - this._knowRepoBands = bandList; - const repoCount = Object.keys(repoScopes).length; - const clusterCount = nodes.filter(n => n.type === 'cluster').length; - return { nodes: nodes, links: links, agentCount: agents.length, factCount: facts.length, factLinkCount: factLinkCount, clusterCount: clusterCount, repoCount: repoCount }; - } - - // Split-aware clustered build (gitmoot #779). Parents and children occupy the same - // visual cluster column. Facts still attach to their leaf cluster, ownership fans still - // originate at that leaf, and each child inherits its parent's repo swimlane. - _knowBuildClusteredSplit(raw, agents, facts, edges, clusters) { - const nodes = [], links = [], seen = {}; - const h = this._knowHierarchy; - const expanded = this._knowExpanded || {}; - const frontierByRoot = {}, displayByCluster = {}, visibleById = {}; - h.roots.forEach(rid => { - const frontier = this._knowHierarchyFrontier(rid); - frontierByRoot[rid] = frontier; visibleById[rid] = 1; frontier.forEach(id => { visibleById[id] = 1; }); - [rid].concat(h.descendants[rid] || []).forEach(id => { displayByCluster[id] = this._knowHierarchyDisplayFor(id, frontier); }); - }); - h.frontierByRoot = frontierByRoot; h.displayByCluster = displayByCluster; h.visibleById = visibleById; - - const repoScopes = {}; - h.roots.forEach(id => { const c = h.rawById[id]; if (c) repoScopes[c.repo || ''] = 1; }); - facts.forEach(f => { if (f) repoScopes[f.repo || ''] = 1; }); - - const clusterById = {}; - h.ids.forEach(id => { - const c = h.rawById[id]; if (!c || seen[id]) return; - const parentId = h.parent[id] || '', rootId = h.root[id] || id, rootRaw = h.rawById[rootId] || c; - const role = id === rootId ? 'root' : (visibleById[id] ? 'frontier' : 'hidden'); - let expandCount = 0; - const hiddenChildren = (h.children[id] || []).filter(cid => !visibleById[cid]); - if (role === 'root' && (h.subtreeDepth[id] || 0) > 1 && !expanded[id]) expandCount = hiddenChildren.length; - else if (role === 'frontier' && hiddenChildren.length && !expanded[id]) expandCount = hiddenChildren.length; - seen[id] = 1; - const node = { - id: id, type: 'cluster', label: c.label || id, count: c.count || 0, - repo: rootRaw.repo || '', medoid: c.medoid || '', parentId: parentId, - isParent: !!(h.children[id] || []).length, childIds: (h.children[id] || []).slice(), - __knowRole: role, __knowVisible: role !== 'hidden', __knowRootId: rootId, __knowExpandCount: expandCount - }; - clusterById[id] = node; nodes.push(node); - }); - - const ensureUnclustered = (scope) => { - scope = scope || ''; - const id = this._knowUnclusteredNodeId(scope); - if (seen[id]) return clusterById[id]; - seen[id] = 1; - const node = { id: id, type: 'cluster', label: 'unclustered', count: 0, repo: scope, medoid: '', parentId: '', isParent: false, childIds: [], __knowRole: 'root', __knowVisible: true, __knowRootId: id, __knowExpandCount: 0 }; - clusterById[id] = node; nodes.push(node); repoScopes[scope] = 1; - return node; - }; - - agents.forEach(a => { if (a && a.name && !seen[a.name]) { seen[a.name] = 1; nodes.push({ id: a.name, type: 'agent', label: a.name, enrolled: !!a.enrolled, facts: a.facts || 0, observations: a.observations || 0 }); } }); - - const clusterAgent = {}; - facts.forEach(f => { - if (!f || !f.id || seen[f.id]) return; seen[f.id] = 1; - let cid = f.cluster || ''; - if (!cid || !clusterById[cid]) { const u = ensureUnclustered(f.repo || ''); cid = u.id; u.count += 1; } - const displayCid = displayByCluster[cid] || cid, rootId = h.root[cid] || cid; - nodes.push({ id: f.id, type: 'fact', label: f.id, content: f.content || '', repo: f.repo || '', key: f.key || '', owner: f.owner || '', witnesses: f.witnesses || 0, firstSeen: f.firstSeen || 0, lastSeen: f.lastSeen || 0, superseded: !!f.superseded, cluster: cid, displayCluster: displayCid, sourceJob: f.sourceJob || '', sourceFile: f.sourceFile || '', links: Array.isArray(f.links) ? f.links : [] }); - links.push({ source: f.id, target: displayCid, kind: 'cluster' }); - if (f.owner && seen[f.owner]) { const k = rootId + '|' + f.owner; clusterAgent[k] = (clusterAgent[k] || 0) + 1; } - }); - Object.keys(frontierByRoot).sort().forEach(rid => { - frontierByRoot[rid].forEach(cid => { if (cid !== rid && clusterById[cid] && clusterById[rid]) links.push({ source: cid, target: rid, kind: 'subcluster' }); }); - }); - Object.keys(clusterAgent).forEach(k => { const i = k.indexOf('|'); const cid = k.slice(0, i), ag = k.slice(i + 1); if (seen[cid] && seen[ag]) links.push({ source: cid, target: ag, kind: 'catagent', count: clusterAgent[k] }); }); - edges.forEach(e => { if (e && e.kind === 'supersede' && seen[e.source] && seen[e.target]) links.push({ source: e.source, target: e.target, kind: 'supersede' }); }); - const factLinkCount = this._knowAppendFactLinks(edges, seen, links); - - // Bands retain every descendant for membership/isolate, but layoutClusterIds - // contains only root + current deterministic sub-column frontier. - const clusterNodesList = nodes.filter(n => n.type === 'cluster'); - const topNodes = clusterNodesList.filter(c => c.__knowRole === 'root'); - const bandMap = {}; - topNodes.forEach(c => { - const scope = c.repo || ''; - let bm = bandMap[scope]; - if (!bm) bm = bandMap[scope] = { scope: scope, label: this._knowRepoShort(scope), color: this._knowRepoColor(scope), general: scope === '', clusters: [], clusterIds: [], layoutClusterIds: [], topClusterIds: [], factCount: 0 }; - const allIds = h.rawById[c.id] ? [c.id].concat(h.descendants[c.id] || []) : [c.id]; - const frontier = h.rawById[c.id] ? (frontierByRoot[c.id] || []) : []; - const frontierNodes = frontier.map(id => clusterById[id]).filter(Boolean); - bm.clusters.push({ id: c.id, label: c.label || c.id, count: c.count || 0, isParent: frontierNodes.length > 0, expandCount: c.__knowExpandCount || 0, children: frontierNodes.map(ch => ({ id: ch.id, label: ch.label || ch.id, count: ch.count || 0, parentId: h.parent[ch.id] || '', expandCount: ch.__knowExpandCount || 0 })) }); - bm.topClusterIds.push(c.id); - allIds.forEach(id => { if (bm.clusterIds.indexOf(id) < 0) bm.clusterIds.push(id); }); - [c.id].concat(frontier).forEach(id => { if (bm.layoutClusterIds.indexOf(id) < 0) bm.layoutClusterIds.push(id); }); - }); - const clusterScope = {}; - topNodes.forEach(c => { - const scope = c.repo || ''; - const ids = h.rawById[c.id] ? [c.id].concat(h.descendants[c.id] || []) : [c.id]; - ids.forEach(id => { clusterScope[id] = scope; }); - }); - this._knowClusterScope = clusterScope; - nodes.forEach(n => { if (n.type !== 'fact') return; const sc = clusterScope[n.cluster]; if (sc != null && bandMap[sc]) bandMap[sc].factCount += 1; }); - const bandList = Object.keys(bandMap).map(k => bandMap[k]); - bandList.sort((a, c) => { - if (a.factCount !== c.factCount) return c.factCount - a.factCount; - if (a.general !== c.general) return a.general ? 1 : -1; - return a.scope < c.scope ? -1 : a.scope > c.scope ? 1 : 0; - }); - bandList.forEach(bm => { bm.detail = { type: 'repo', id: this._knowRepoNodeId(bm.scope), repoName: bm.scope, general: bm.general, label: bm.scope || 'general' }; }); - this._knowRepoBands = bandList; - const clusterCount = clusterNodesList.length; - const subclusterCount = clusterNodesList.filter(c => c.__knowRole !== 'root').length; - return { nodes: nodes, links: links, agentCount: agents.length, factCount: facts.length, factLinkCount: factLinkCount, clusterCount: clusterCount, subclusterCount: subclusterCount, repoCount: Object.keys(repoScopes).length }; - } - - // CLUSTERED layout (option A, repo swimlanes): THREE vertical node columns — - // facts | clusters | agents (left -> right) — laid over horizontal repo BANDS. - // Every band's HEIGHT is proportional to its fact count (floored + normalized so - // bands + gaps fill GH exactly), so a big repo reads as a tall lane at a glance. - // Inside each band the clusters stack centered and the facts (grouped contiguously - // by cluster) stack centered; agents sit in a full-height right column OUTSIDE the - // band tint, ordered by the barycenter of the clusters they own. The band rects - // (graph units) are stashed on this._knowBands for the paint pass + hit-test. - // Static + deterministic: positions are computed, pinned, committed — no physics. - _knowLayoutClustered(nodes, links) { - if (this._knowHasSplits) return this._knowLayoutClusteredSplit(nodes, links); - return this._knowLayoutClusteredFlat(nodes, links); - } - - // Two-phase deterministic fact layout inside one repo band. Phase 1 settles - // leaf-cluster centroids with mutual repulsion, cross-clump link affinity and - // parent cohesion. Phase 2 packs facts around those centroids with score-driven - // springs, collision separation and soft walls. Positions are pinned once and - // never handed to the live force engine. - _knowSettleFactGalaxy(facts, clusterNodes, factLinks, rect, seed, px) { - if (!facts.length) { rect.clumps = []; return; } - const rng = this._knowRng(seed); - const byId = {}; facts.forEach(f => { byId[f.id] = f; }); - const leafMap = {}; - facts.forEach(f => { (leafMap[f.cluster] = leafMap[f.cluster] || []).push(f); }); - const leafIds = Object.keys(leafMap).sort(); - const cx = (rect.galaxyX0 + rect.galaxyX1) / 2, cy = rect.cy; - const gw = Math.max(px(36), rect.galaxyX1 - rect.galaxyX0), gh = Math.max(px(36), rect.h); - const C = leafIds.map((id, i) => { - const a = (i / Math.max(1, leafIds.length)) * Math.PI * 2 + 0.7 + (rng() - 0.5) * 0.12; - return { id: id, x: cx + Math.cos(a) * gw * 0.18, y: cy + Math.sin(a) * gh * 0.2 }; - }); - const ci = {}; C.forEach((c, i) => { ci[c.id] = i; }); - const cross = {}; - factLinks.forEach(l => { - const a = byId[l.__sourceId], b = byId[l.__targetId]; - if (!a || !b || a.cluster === b.cluster) return; - const key = a.cluster < b.cluster ? a.cluster + '|' + b.cluster : b.cluster + '|' + a.cluster; - cross[key] = (cross[key] || 0) + l.score; - }); - const minDim = Math.min(gw, gh); - const kc = Math.max(px(18), Math.min(minDim * 0.38, 0.82 * Math.sqrt((gw * gh) / Math.max(1, C.length)))); - let temp = minDim * 0.1; - for (let it = 0; it < 190; it++) { - const d = C.map(() => ({ x: 0, y: 0 })); - for (let i = 0; i < C.length; i++) for (let j = i + 1; j < C.length; j++) { - let dx = C[i].x - C[j].x, dy = C[i].y - C[j].y, dist = Math.hypot(dx, dy); - if (dist < 0.01) { dx = rng() - 0.5; dy = rng() - 0.5; dist = Math.hypot(dx, dy) || 0.5; } - const force = kc * kc / dist, ux = dx / dist, uy = dy / dist; - d[i].x += ux * force; d[i].y += uy * force; d[j].x -= ux * force; d[j].y -= uy * force; - } - Object.keys(cross).forEach(key => { - const parts = key.split('|'), ia = ci[parts[0]], ib = ci[parts[1]]; - if (ia == null || ib == null) return; - let dx = C[ia].x - C[ib].x, dy = C[ia].y - C[ib].y, dist = Math.hypot(dx, dy) || 0.01; - const force = dist * dist / Math.max(kc, 0.01) * Math.min(0.5, cross[key] * 0.05), ux = dx / dist, uy = dy / dist; - d[ia].x -= ux * force; d[ia].y -= uy * force; d[ib].x += ux * force; d[ib].y += uy * force; - }); - const parentGroups = {}; - leafIds.forEach(id => { const pid = this._knowHierarchy && this._knowHierarchy.parent[id]; if (pid) (parentGroups[pid] = parentGroups[pid] || []).push(ci[id]); }); - Object.keys(parentGroups).forEach(pid => { - const ids = parentGroups[pid]; if (ids.length < 2) return; - const mx = ids.reduce((s, i) => s + C[i].x, 0) / ids.length, my = ids.reduce((s, i) => s + C[i].y, 0) / ids.length; - ids.forEach(i => { d[i].x += (mx - C[i].x) * 0.05; d[i].y += (my - C[i].y) * 0.05; }); - }); - C.forEach((c, i) => { - d[i].x += (cx - c.x) * 0.028; d[i].y += (cy - c.y) * 0.028; - const mag = Math.hypot(d[i].x, d[i].y) || 0.01, step = Math.min(mag, temp), pad = px(20); - c.x = this._knowClamp(c.x + d[i].x / mag * step, rect.galaxyX0 + pad, rect.galaxyX1 - pad); - c.y = this._knowClamp(c.y + d[i].y / mag * step, rect.y + pad, rect.y + rect.h - pad); - }); - temp *= 0.976; - } - const centroids = {}; C.forEach(c => { centroids[c.id] = { x: c.x, y: c.y }; }); - const dense = facts.length > 40, coll = px(dense ? 5.5 : 8.5); - facts.forEach(f => { - const c = centroids[f.cluster], a = rng() * Math.PI * 2; - const r = rng() * (px(10) + Math.sqrt(leafMap[f.cluster].length) * coll * 0.6); - f.x = c.x + Math.cos(a) * r; f.y = c.y + Math.sin(a) * r; - }); - const disp = facts.map(() => ({ x: 0, y: 0 })), idx = {}; - facts.forEach((f, i) => { idx[f.id] = i; }); - let temp2 = px(44); - for (let it = 0; it < 300; it++) { - for (let i = 0; i < facts.length; i++) { disp[i].x = 0; disp[i].y = 0; } - for (let i = 0; i < facts.length; i++) for (let j = i + 1; j < facts.length; j++) { - let dx = facts[i].x - facts[j].x, dy = facts[i].y - facts[j].y, dist = Math.hypot(dx, dy); - if (dist < 0.01) { dx = rng() - 0.5; dy = rng() - 0.5; dist = Math.hypot(dx, dy) || 0.5; } - if (dist < coll * 2.4) { - const force = coll * coll / dist, ux = dx / dist, uy = dy / dist; - disp[i].x += ux * force; disp[i].y += uy * force; disp[j].x -= ux * force; disp[j].y -= uy * force; - } - } - factLinks.forEach(l => { - const a = byId[l.__sourceId], b = byId[l.__targetId]; if (!a || !b) return; - const ia = idx[a.id], ib = idx[b.id], score = this._knowClamp(l.score, 0, 1); - let dx = b.x - a.x, dy = b.y - a.y, dist = Math.hypot(dx, dy) || 0.01; - const same = a.cluster === b.cluster; - const rest = coll * (same ? (2.3 - 1.2 * score) : (6.5 - 2.8 * score)); - const strength = same ? (0.035 + 0.09 * score) : (0.012 + 0.04 * score); - const force = (dist - rest) * strength, ux = dx / dist, uy = dy / dist; - disp[ia].x += ux * force; disp[ia].y += uy * force; disp[ib].x -= ux * force; disp[ib].y -= uy * force; - }); - const live = {}; - leafIds.forEach(id => { let sx = 0, sy = 0; leafMap[id].forEach(f => { sx += f.x; sy += f.y; }); live[id] = { x: sx / leafMap[id].length, y: sy / leafMap[id].length }; }); - facts.forEach((f, i) => { - const a = centroids[f.cluster], b = live[f.cluster], tx = a.x * 0.55 + b.x * 0.45, ty = a.y * 0.55 + b.y * 0.45; - disp[i].x += (tx - f.x) * 0.1; disp[i].y += (ty - f.y) * 0.1; - const wall = coll * 3, left = rect.galaxyX0 + wall, right = rect.galaxyX1 - wall, top = rect.y + wall, bottom = rect.y + rect.h - wall; - if (f.x < left) disp[i].x += (left - f.x) * 0.18; else if (f.x > right) disp[i].x -= (f.x - right) * 0.18; - if (f.y < top) disp[i].y += (top - f.y) * 0.18; else if (f.y > bottom) disp[i].y -= (f.y - bottom) * 0.18; - }); - facts.forEach((f, i) => { - const mag = Math.hypot(disp[i].x, disp[i].y) || 0.01, step = Math.min(mag, temp2), pad = coll; - f.x = this._knowClamp(f.x + disp[i].x / mag * step, rect.galaxyX0 + pad, rect.galaxyX1 - pad); - f.y = this._knowClamp(f.y + disp[i].y / mag * step, rect.y + pad, rect.y + rect.h - pad); - }); - temp2 *= 0.985; - } - // A short fixed collision cleanup removes any residual pileups caused by wall - // clamps, then every point is hard-clamped for the containment guarantee. - for (let it = 0; it < 24; it++) { - for (let i = 0; i < facts.length; i++) for (let j = i + 1; j < facts.length; j++) { - let dx = facts[i].x - facts[j].x, dy = facts[i].y - facts[j].y, dist = Math.hypot(dx, dy); - if (dist < 0.01) { dx = rng() - 0.5; dy = rng() - 0.5; dist = Math.hypot(dx, dy) || 0.5; } - const minD = coll * 1.9; if (dist >= minD) continue; - const push = (minD - dist) * 0.5, ux = dx / dist, uy = dy / dist; - facts[i].x += ux * push; facts[i].y += uy * push; facts[j].x -= ux * push; facts[j].y -= uy * push; - } - facts.forEach(f => { f.x = this._knowClamp(f.x, rect.galaxyX0 + coll, rect.galaxyX1 - coll); f.y = this._knowClamp(f.y, rect.y + coll, rect.y + rect.h - coll); }); - } - rect.clumps = leafIds.map(id => { - const fs = leafMap[id], mx = fs.reduce((s, f) => s + f.x, 0) / fs.length, my = fs.reduce((s, f) => s + f.y, 0) / fs.length; - let spread = px(8); fs.forEach(f => { spread = Math.max(spread, Math.hypot(f.x - mx, f.y - my)); }); - return { x: mx, y: my, r: spread + px(22) }; - }); - facts.forEach(f => { f.fx = f.x; f.fy = f.y; f.vx = 0; f.vy = 0; f.__knowBand = rect; }); - } - - // Original no-parent layout. Payloads without parent_id stay on this path unchanged. - _knowLayoutClusteredFlat(nodes, links) { - const cb = this._knowComputeBands(); - const GH = cb.GH, W = cb.W, H = cb.H; - const bands = this._knowRepoBands || []; - const lid = (v) => (v && v.id != null) ? v.id : v; - - const clusterNodes = {}; nodes.forEach(n => { if (n.type === 'cluster') clusterNodes[n.id] = n; }); - const factNodes = nodes.filter(n => n.type === 'fact'); - const agents = nodes.filter(n => n.type === 'agent'); - const agentSet = {}; agents.forEach(a => { agentSet[a.id] = 1; }); - - // --- horizontal geometry (clustered-only; derived independently of the fallback - // cols so _knowComputeBands' output is untouched). facts left, clusters center, - // agents right; the band tint spans a little left of facts through past clusters, - // agents fall OUTSIDE it. --- - const aspect = Math.max(0.5, Math.min(2.4, W / Math.max(1, H))); - const spanFactor = 0.46 * Math.max(0.6, Math.min(1, (W - 40) / 700)); - const half = spanFactor * (GH * aspect); - const xF = -half * 0.74; // facts column - const xC = -half * 0.10; // clusters column (classic 3-column view) - const xA = half * 0.66; // agents column (outside the tint) - // When cluster HIERARCHIES exist, the sub-clusters get a PROPER level of their - // own: the span between facts and agents splits into equal thirds — facts | - // sub-clusters | clusters | agents — instead of tucking children a token - // offset beside the hub column (which read as jitter, not structure). Without - // splits the classic 3-column geometry is untouched. - const G3 = (xA - xF) / 3; - const xSub = xF + G3; // sub-cluster level (populated by the split pass) - const xClu = this._knowHasSplits ? xF + 2 * G3 : xC; // cluster level - // The lane label + "N facts" sub-line live in a left gutter. It is drawn at a - // constant SCREEN size (font/scale), so reserve a gutter whose WIDTH tracks the - // zoom the graph will settle at (estimate it the way zoomToFit does) — otherwise - // the label would overrun the facts at narrow widths or clip at wide ones. - // Asymmetric fit padding: the left gutter needs ~100px (74px band label + tint - // margin); the RIGHT needs ~210px because agent labels render at a constant 11px - // to the right of their node ("waybread-baseline-reviewer" is ~180px) and must - // never clip at the settled zoom. - const PADL = 100, PADR = 210; - const bboxW = xA - xF; - // WIDTH-anchored scale: the clustered view settles at fit-to-WIDTH (_knowFit), - // so every screen-pixel spacing floor below converts to graph units through THIS - // scale and holds exactly on screen. The old estimate also folded in the height - // fit — which is precisely what compressed dense lanes until their constant - // screen-size labels smeared together. Height no longer participates: the band - // stack may grow taller than the viewport and the user pans down for the rest. - const scaleW = Math.max(0.02, (W - PADL - PADR) / Math.max(1, bboxW)); - const px = (v) => v / scaleW; // screen px -> graph units - const gutterGU = px(74); // ~74px of label room - const labelX = xF - gutterGU; - const tintX0 = labelX - px(8); // tint left edge, just left of the label - const tintX1 = this._knowHasSplits ? xClu + 0.3 * (xA - xClu) : xC + half * 0.22; // tint right edge, past the clusters - const galaxyX0 = xF + px(6); - const galaxyX1 = Math.max(galaxyX0 + px(72), (this._knowHasSplits ? xSub : xClu) - px(this._knowHasSplits ? 112 : 82)); - - // --- vertical bands: CONTENT-DRIVEN heights — each band is exactly tall enough - // for its cluster labels and its constellation area (fact count + number of - // independent clumps), floored for tiny bands. NO scale-to-fit: bands remain - // unequal and the stack grows as knowledge grows. - const CPITCH = px(18), CMAXP = px(30), CINSET = px(24); - const GAPB = px(12), MINH = px(72); - const n = bands.length; - const raw = bands.map(bd => { - const nC = (bd.layoutClusterIds || bd.clusterIds || []).length, nF = bd.factCount || 0; - const needC = nC > 0 ? (nC - 1) * CPITCH + CINSET : 0; - const leafCount = Math.max(1, (bd.clusterIds || []).filter(id => factNodes.some(f => f.cluster === id)).length); - const galaxyWidthPx = Math.max(120, (galaxyX1 - galaxyX0) * scaleW); - const spreadPx = Math.sqrt(Math.max(1, nF)) * 24 + Math.sqrt(leafCount) * 18; - const areaPx = nF > 0 ? (nF * 170) / galaxyWidthPx + 44 : 0; - const needGalaxy = nF > 0 ? px(Math.max(72, spreadPx, areaPx)) : 0; - return Math.max(MINH, needC, needGalaxy); - }); - const totalH = raw.reduce((s, v) => s + v, 0) + GAPB * Math.max(0, n - 1); - const top = -totalH / 2; - - const rects = []; - let y = top; - bands.forEach((bd, bi) => { - const h = raw[bi]; - const cy = y + h / 2; - // clusters of this band, stacked centered: NEVER closer than CPITCH (the - // whole point — labels can't overlap), spread up to CMAXP when the band is - // tall because facts dominate, so 1-2 clusters don't span a huge band. - const cs = (bd.layoutClusterIds || bd.clusterIds || []).map(id => clusterNodes[id]).filter(Boolean); - const cGap = cs.length > 1 ? Math.min(Math.max((h - CINSET) / (cs.length - 1), CPITCH), CMAXP) : 0; - const cInner = cGap * Math.max(0, cs.length - 1); - const cTop = cy - cInner / 2; - cs.forEach((c, k) => { const yy = cs.length > 1 ? cTop + k * cGap : cy; c.fx = xClu; c.fy = yy; c.x = xClu; c.y = yy; c.vx = 0; c.vy = 0; }); - // Facts are no longer a vertical pitch column. The fixed-iteration galaxy - // solver below places them within this band's dedicated left-hand sky. - const fs = []; - (bd.clusterIds || []).forEach(cid => { factNodes.forEach(f => { if (f.cluster === cid) fs.push(f); }); }); - fs.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0); - fs.forEach(f => { f.__knowBandScope = bd.scope; }); - rects.push({ y: y, h: h, cy: cy, tintX0: tintX0, tintX1: tintX1, labelX: labelX, factX: xF, galaxyX0: galaxyX0, galaxyX1: galaxyX1, scope: bd.scope, color: bd.color, general: bd.general, label: bd.label, factCount: bd.factCount, detail: bd.detail, facts: fs, clumps: [] }); - y += h + GAPB; - }); - this._knowBands = rects; - const factById = {}; factNodes.forEach(f => { factById[f.id] = f; f.__knowDegree = 0; f.__knowPersistentLabel = false; }); - const factLinks = links.filter(l => l.kind === 'link'); - factLinks.forEach(l => { - const sid = lid(l.source), tid = lid(l.target), s = factById[sid], t = factById[tid]; - l.__sourceId = sid; l.__targetId = tid; - if (!s || !t) return; - l.factRelation = s.__knowBandScope !== t.__knowBandScope ? 'repo' : (s.cluster === t.cluster ? 'in' : 'cross'); - s.__knowDegree++; t.__knowDegree++; - }); - rects.forEach((bd, bi) => { - const ids = {}; bd.facts.forEach(f => { ids[f.id] = 1; }); - const local = factLinks.filter(l => l.factRelation !== 'repo' && ids[l.__sourceId] && ids[l.__targetId]); - this._knowSettleFactGalaxy(bd.facts, clusterNodes, local, bd, this._knowSig + '|band|' + bd.scope + '|' + bi, px); - // Persistent labels: only genuinely LINKED facts earn one (degree >= 1 — - // with zero links a "top 6" is an arbitrary alphabetical pick that smears - // long keys over the clumps), capped at 6, and de-conflicted vertically so - // two kept labels in one band are never closer than ~11 screen px. - const kept = []; - bd.facts.slice().sort((a, b) => b.__knowDegree - a.__knowDegree || (a.id < b.id ? -1 : 1)).forEach(f => { - if (f.__knowDegree < 1 || kept.length >= 6) return; - if (kept.some(k => Math.abs(k.y - f.y) < px(11))) return; - kept.push(f); f.__knowPersistentLabel = true; - }); - }); - // Safety: a fact whose cluster somehow landed in no band still gets a position. - factNodes.forEach(f => { if (f.x == null) { f.fx = xF; f.fy = 0; f.x = xF; f.y = 0; f.vx = 0; f.vy = 0; } }); - - // --- agents: full-height right column, ordered by the barycenter of the y of the - // clusters they own (via catagent links). A min-gap floor keeps labels legible - // when many agents share the rail. --- - const agentClY = {}; - for (let i = 0; i < links.length; i++) { - const l = links[i]; - if (l.kind !== 'catagent') continue; - const cid = lid(l.source), ag = lid(l.target); - const c = clusterNodes[cid]; - if (c && agentSet[ag]) (agentClY[ag] = agentClY[ag] || []).push(c.y); - } - const ags = agents.map(a => { const ys = agentClY[a.id] || []; return { a: a, by: ys.length ? ys.reduce((s, v) => s + v, 0) / ys.length : 0 }; }); - ags.sort((x, z) => x.by - z.by); - // The rail stretches over the FULL band-stack height (barycenter order keeps - // each agent beside its clusters), with the min gap now a true screen-px floor. - const aN = ags.length, aTop = top + px(8), aBot = top + totalH - px(8), aSpan = aBot - aTop, AMINGAP = px(16); - let aSpacing = aN > 1 ? aSpan / (aN - 1) : 0, aStart = aTop; - if (aN > 1 && aSpacing < AMINGAP) { aSpacing = AMINGAP; aStart = -(aSpacing * (aN - 1)) / 2; } - ags.forEach((o, i) => { const yy = aN <= 1 ? 0 : aStart + i * aSpacing; o.a.fx = xA; o.a.fy = yy; o.a.x = xA; o.a.y = yy; o.a.vx = 0; o.a.vy = 0; }); - // Geometry handoff for _knowFit (width-anchored zoom + top-anchor) and the split - // pass (min-pitch sweeps in the same screen-px terms). - this._knowGeom = { scaleW: scaleW, xF: xF, xA: xA, xSub: xSub, xClu: xClu, top: top, totalH: totalH, padL: PADL, padR: PADR }; - } - - // Split layout starts from the proven three-column swimlane geometry, then tightens - // each hierarchy inside the existing cluster column: children shift toward facts and - // their slightly larger parent sits just behind them. No fourth rail is introduced. - _knowLayoutClusteredSplit(nodes, links) { - this._knowLayoutClusteredFlat(nodes, links); - // The flat pass already put every cluster on the CLUSTER level (xClu, shifted - // right when splits exist to make room). Here the children drop down to the - // dedicated SUB level (xSub, an equal third of the span) so a hierarchy reads - // as a proper extra level — facts | sub-clusters | clusters | agents — instead - // of a token offset beside the hub column. Parents keep their level; only - // their Y re-anchors to the children barycenter. - const geom = this._knowGeom || {}; - const xSub = (geom.xSub != null) ? geom.xSub : 0; - const lid = (v) => (v && v.id != null) ? v.id : v; - const h = this._knowHierarchy; - const clusterNodes = {}, factsByAncestor = {}; - nodes.forEach(n => { - if (n.type === 'cluster') clusterNodes[n.id] = n; - else if (n.type === 'fact') { - const path = h && h.chain[n.cluster] ? h.chain[n.cluster] : [n.cluster]; - path.forEach(cid => { (factsByAncestor[cid] = factsByAncestor[cid] || []).push(n); }); - } - }); - (h ? h.roots : []).forEach(rid => { - const root = clusterNodes[rid]; if (!root) return; - const frontier = ((h.frontierByRoot && h.frontierByRoot[rid]) || []).map(id => clusterNodes[id]).filter(Boolean); - frontier.forEach(ch => { - const fs = factsByAncestor[ch.id] || []; - const yy = fs.length ? fs.reduce((s, f) => s + f.y, 0) / fs.length : root.y; - ch.fx = xSub; ch.fy = yy; ch.x = xSub; ch.y = yy; ch.vx = 0; ch.vy = 0; - }); - const py = frontier.length ? frontier.reduce((s, ch) => s + ch.y, 0) / frontier.length : root.y; - root.fy = py; root.y = py; root.vx = 0; root.vy = 0; - }); - - // Barycenter placement can land two sub-clusters (or two hub-level nodes) - // closer than a label height — enforce the flat pass's minimum pitch on each - // level with an ordered push-down sweep per band, re-anchoring each parent on - // its swept children first. The hub sweep covers ALL non-child clusters: after - // the barycenter re-anchor a parent can land on a childless hub's row, and the - // two now share the cluster level. Pitches in screen px via scaleW. - const kpx = (v) => v / Math.max(0.02, geom.scaleW || 1); - const CHPITCH = kpx(15), PPITCH = kpx(18); - const sweep = (arr, pitch, y0, y1) => { - if (arr.length < 2) return; - arr.sort((a, b) => a.y - b.y); - const need = pitch * (arr.length - 1); - let yy = Math.max(y0, Math.min(arr[0].y, y1 - need)); - for (let i = 0; i < arr.length; i++) { - const t = Math.max(arr[i].y, yy); - arr[i].fy = t; arr[i].y = t; arr[i].vy = 0; - yy = t + pitch; - } - }; - const bandsSrc = this._knowRepoBands || []; // rects carry no clusterIds; index-aligned with the source bands - (this._knowBands || []).forEach((bd, bi) => { - const y0 = bd.y + kpx(8), y1 = bd.y + bd.h - kpx(8); - const kids = [], hubs = []; - ((bandsSrc[bi] || {}).layoutClusterIds || (bandsSrc[bi] || {}).clusterIds || []).forEach(id => { - const c = clusterNodes[id]; if (!c) return; - if (c.__knowRole === 'frontier') kids.push(c); else if (c.__knowRole === 'root') hubs.push(c); - }); - sweep(kids, CHPITCH, y0, y1); - hubs.forEach(p => { - const ch = ((h.frontierByRoot && h.frontierByRoot[p.id]) || []).map(id => clusterNodes[id]).filter(Boolean); - if (ch.length) { const yy = ch.reduce((s, c) => s + c.y, 0) / ch.length; p.fy = yy; p.y = yy; } - }); - sweep(hubs, PPITCH, y0, y1); - }); - - // Hidden intermediates stay inside their root's row so force-graph's bbox - // cannot widen or lengthen the visible layout even though detail lookup keeps - // their node objects available. - nodes.forEach(n => { - if (n.type !== 'cluster' || n.__knowVisible !== false) return; - const root = clusterNodes[n.__knowRootId]; if (!root) return; - n.fx = root.x; n.fy = root.y; n.x = root.x; n.y = root.y; n.vx = 0; n.vy = 0; - }); - - // Reorder the agent rail from the adjusted leaf positions so ownership fans keep - // their clean barycentric flow after children move within the cluster column. - const agents = nodes.filter(n => n.type === 'agent'); - const agentSet = {}; agents.forEach(a => { agentSet[a.id] = 1; }); - const agentClY = {}; - links.forEach(l => { - if (l.kind !== 'catagent') return; - const cid = lid(l.source), ag = lid(l.target), c = clusterNodes[cid]; - if (c && agentSet[ag]) (agentClY[ag] = agentClY[ag] || []).push(c.y); - }); - const ags = agents.map(a => { const ys = agentClY[a.id] || []; return { a: a, by: ys.length ? ys.reduce((s, v) => s + v, 0) / ys.length : 0 }; }); - ags.sort((a, b) => a.by - b.by || (a.a.id < b.a.id ? -1 : a.a.id > b.a.id ? 1 : 0)); - // Respread over the flat pass's content-driven stack height (not the old fixed - // GH), same screen-px min gap. - const top = (geom.top != null) ? geom.top : -GH / 2, totalH = geom.totalH || GH; - const aN = ags.length, aTop = top + kpx(8), aBot = top + totalH - kpx(8), aSpan = aBot - aTop, AMINGAP = kpx(16); - let aSpacing = aN > 1 ? aSpan / (aN - 1) : 0, aStart = aTop; - if (aN > 1 && aSpacing < AMINGAP) { aSpacing = AMINGAP; aStart = -(aSpacing * (aN - 1)) / 2; } - ags.forEach((o, i) => { const yy = aN <= 1 ? 0 : aStart + i * aSpacing; o.a.fy = yy; o.a.y = yy; o.a.vx = 0; o.a.vy = 0; }); - } - - renderKnowledge(isPoll) { - if (!this._knowGraph) return; - const built = this._knowBuild(this._knowRaw || { agents: [], facts: [], edges: [] }); - const nodes = built.nodes, links = built.links; - // change signature over ids + superseded flags + repo scope + labels (state that - // changes the layout/render — repo folds in so a fact/cluster changing repo re-bands; - // label folds in so a server-side `memory cluster rename` re-renders even when the - // node/link topology is otherwise unchanged). - let h = 0; - for (let i = 0; i < nodes.length; i++) { const n = nodes[i]; const str = (n.id || '') + ':' + (n.superseded ? '1' : '0') + ':' + (n.repo || '') + ':' + (n.label || '') + ':' + (n.__knowVisible === false ? '0' : '1') + ':' + (n.__knowRole || '') + ':' + (n.__knowExpandCount || 0); for (let j = 0; j < str.length; j++) h = (h * 31 + str.charCodeAt(j)) | 0; } - // Fold link topology (endpoints + kind) into the same hash so that a fact moving - // cluster (same node/link COUNTS but different cluster edges) still re-triggers a - // re-layout. Endpoints may be raw string ids (fresh from _knowBuild) or resolved - // node objects, so normalize with the (v && v.id != null) ? v.id : v pattern. - for (let i = 0; i < links.length; i++) { const l = links[i]; const sv = l.source, tv = l.target; const s = (sv && sv.id != null) ? sv.id : sv; const t = (tv && tv.id != null) ? tv.id : tv; const str = '~' + s + '>' + t + ':' + (l.kind || '') + ':' + (l.score == null ? '' : l.score); for (let j = 0; j < str.length; j++) h = (h * 31 + str.charCodeAt(j)) | 0; } - const sig = (this._knowHistoryOn ? 'history/' : 'current/') + nodes.length + '/' + links.length + '/' + h; - // sig-skip: leave the COMMITTED graph (its pinned node objects) untouched. No instance - // map holds node-object references (adjacency/selection are id strings), so returning - // here can never strand a map on the position-less rebuild. - if (isPoll && this._knowSig === sig) return; - this._knowSig = sig; - this._knowBuilt = built; - const ca = this._learningRoot.querySelector('#lr-kAgents'); if (ca) ca.textContent = built.agentCount; - const cf = this._learningRoot.querySelector('#lr-kFacts'); if (cf) cf.textContent = built.factCount; - // Clustered mode: fold the cluster count into the header chip + swap the legend - // to the repo -> cluster -> fact -> agent columns (left -> right). Fallback view - // keeps the original left -> right column legend untouched. - this._knowSyncChrome(built); - // adjacency (id -> neighbor ids / connected link keys) for the selected-node highlight - const neighbors = {}, nodeLinks = {}; - nodes.forEach(n => { neighbors[n.id] = new Set(); nodeLinks[n.id] = new Set(); }); - links.forEach(l => { const s = l.source, t = l.target, key = s + ' ' + t; if (neighbors[s]) { neighbors[s].add(t); nodeLinks[s].add(key); } if (neighbors[t]) { neighbors[t].add(s); nodeLinks[t].add(key); } }); - const factLinks = links.filter(l => l.kind === 'link'); - const factsByCluster = {}, fanKey = {}; - nodes.forEach(n => { if (n.type === 'fact') (factsByCluster[n.cluster] = factsByCluster[n.cluster] || []).push(n.id); }); - links.forEach(l => { if (l.kind === 'cluster') fanKey[l.source] = l.source + ' ' + l.target; }); - // Cluster selection is aggregate: isolate all descendant facts and only the - // wiki links whose endpoints both belong to that selected clump. - const collectFacts = (cid, out, seenCl) => { - if (seenCl[cid]) return; seenCl[cid] = 1; - const ids = [cid].concat((this._knowHierarchy && this._knowHierarchy.descendants[cid]) || []); - ids.forEach(id => { seenCl[id] = 1; (factsByCluster[id] || []).forEach(fid => out.add(fid)); }); - }; - nodes.filter(n => n.type === 'cluster').forEach(c => { - const members = new Set(); collectFacts(c.id, members, {}); - members.forEach(id => { neighbors[c.id].add(id); if (fanKey[id]) nodeLinks[c.id].add(fanKey[id]); }); - ((this._knowHierarchy && this._knowHierarchy.descendants[c.id]) || []).forEach(id => neighbors[c.id].add(id)); - factLinks.forEach(l => { if (members.has(l.source) && members.has(l.target)) { neighbors[c.id].add(l.source); neighbors[c.id].add(l.target); nodeLinks[c.id].add(l.source + ' ' + l.target); } }); - const rootId = (this._knowHierarchy && this._knowHierarchy.root[c.id]) || c.id; - if (rootId !== c.id) neighbors[c.id].add(rootId); - links.forEach(l => { if (l.kind === 'catagent' && l.source === rootId) { neighbors[c.id].add(l.target); nodeLinks[c.id].add(l.source + ' ' + l.target); } }); - }); - // Hovering a fact has a narrower focus than clicking it: linked facts + those - // links, its own leaf-cluster node and exactly one membership fan. - const hoverByFact = {}; - nodes.filter(n => n.type === 'fact').forEach(f => { const display = f.displayCluster || f.cluster; hoverByFact[f.id] = { id: f.id, neighbors: new Set(display ? [display] : []), links: new Set(), hover: true }; if (fanKey[f.id]) hoverByFact[f.id].links.add(fanKey[f.id]); }); - factLinks.forEach(l => { - const key = l.source + ' ' + l.target; - if (hoverByFact[l.source]) { hoverByFact[l.source].neighbors.add(l.target); hoverByFact[l.source].links.add(key); } - if (hoverByFact[l.target]) { hoverByFact[l.target].neighbors.add(l.source); hoverByFact[l.target].links.add(key); } - }); - this._knowHoverByFact = hoverByFact; - if (this._knowHoveredFact) this._knowHoverFocus = hoverByFact[this._knowHoveredFact] || null; - // Repo band PSEUDO-entries (option A): a band has no graph node, so give its - // synthetic detail id an adjacency entry covering all member clusters + their - // facts + owning agents (and the matching cluster/catagent link keys). Selecting - // a band then highlights its members + dims the rest, exactly like a node click. - if (this._knowClustered && Array.isArray(this._knowRepoBands) && this._knowRepoBands.length) { - const clScope = {}; // cluster id -> band scope - this._knowRepoBands.forEach(bd => (bd.clusterIds || []).forEach(cid => { clScope[cid] = bd.scope; })); - const factScope = {}; nodes.forEach(n => { if (n.type === 'fact') factScope[n.id] = clScope[n.cluster]; }); - const acc = {}; // scope -> { id, nb:Set, lk:Set } - this._knowRepoBands.forEach(bd => { acc[bd.scope] = { id: bd.detail.id, nb: new Set(bd.clusterIds || []), lk: new Set() }; }); - links.forEach(l => { - const s = l.source, t = l.target; - if (l.kind === 'cluster') { const sc = clScope[t]; const e = sc != null ? acc[sc] : null; if (e) { e.nb.add(s); e.lk.add(s + ' ' + t); } } - else if (l.kind === 'subcluster') { const sc = clScope[s]; const e = sc != null ? acc[sc] : null; if (e) e.lk.add(s + ' ' + t); } - else if (l.kind === 'catagent') { const sc = clScope[s]; const e = sc != null ? acc[sc] : null; if (e) { e.nb.add(t); e.lk.add(s + ' ' + t); } } - else if (l.kind === 'link' && factScope[s] != null && factScope[s] === factScope[t]) { const e = acc[factScope[s]]; if (e) { e.nb.add(s); e.nb.add(t); e.lk.add(s + ' ' + t); } } - }); - Object.keys(acc).forEach(sc => { const e = acc[sc]; neighbors[e.id] = e.nb; nodeLinks[e.id] = e.lk; }); - } - this._knowAdj = { neighbors: neighbors, nodeLinks: nodeLinks }; - const empty = built.factCount === 0; - const emptyEl = this._learningRoot.querySelector('#lr-empty'); - if (empty && emptyEl) { - emptyEl.innerHTML = 'knowledge graph is empty - facts appear as enrolled agents hit qualifying outcomes (' + built.agentCount + ' agent' + (built.agentCount === 1 ? '' : 's') + ' enrolled)'; - emptyEl.style.display = 'block'; - } else if (emptyEl) { emptyEl.style.display = 'none'; } - this._knowEmpty = empty; - if (empty) { - // EMPTY (columns would look broken with no facts): keep the ring-of-wells design — - // pin the enrolled agents on a ring of dim wells behind the centered note (static). - const R = 92, m = nodes.length || 1; - nodes.forEach((n, i) => { const ang = (i / m) * 2 * Math.PI - Math.PI / 2; n.x = n.fx = R * Math.cos(ang); n.y = n.fy = R * Math.sin(ang); n.vx = 0; n.vy = 0; }); - } else { - this._knowLayout(nodes, links); // STATIC 4-column pinned layout — positions computed + committed - } - if (!isPoll) this.closeKnowledgeDetail(); - // commit the data; cooldownTicks(0) stops the engine immediately (nodes are already - // pinned), then onEngineStop / the backstop timeout fits the columns to the container. - this._knowNeedFit = true; this._knowFitDone = false; - try { this._knowGraph.cooldownTicks(0); } catch (e) {} - this._knowGraph.graphData({ nodes: nodes, links: links }); - const pad = empty ? 60 : (this._knowClustered ? 100 : 42); - setTimeout(() => { if (!this._knowFitDone) { this._knowFit(isPoll ? 0 : 600, pad); this._knowFitDone = true; this._knowNeedFit = false; this._knowScheduleGutterNudge(isPoll ? 100 : 700); } }, isPoll ? 40 : 220); - // Mobile (option A): swap the canvas for the repo accordion when clustered + narrow. - this._knowApplyMobile(); - } - - // Sync the header count chip + legend to the active mode. Only clustered mode - // rewrites them (the fallback view keeps its original DOM chip/legend, ids - // intact); called every render so the counts track the feed. - _knowSyncChrome(built) { - const root = this._learningRoot; if (!root) return; - if (this._brainView === 'changelog') { this._brainSyncStats(); return; } - const linkCountEl = root.querySelector('#lr-know-linkcount'); - const controlsEl = root.querySelector('#lr-know-controls'); - if (!this._knowClustered) { - if (linkCountEl) linkCountEl.style.display = 'none'; - if (controlsEl) controlsEl.style.display = 'none'; - // FALLBACK: clustered mode rewrote #lr-know-count's innerHTML (destroying the - // #lr-kAgents / #lr-kFacts spans) + the repo->cluster legend, so a later payload - // with no clusters would render the fallback view against stale clustered chrome. - // Restore the ORIGINAL static count pill (with the spans) + the static fallback - // legend, then fill the spans from `built`. Guarded on _knowChromeMode so this only - // rewrites on an actual mode flip, not every poll. - if (this._knowChromeMode !== 'fallback') { - this._knowChromeMode = 'fallback'; - const countEl = root.querySelector('#lr-know-count'); - if (countEl) countEl.innerHTML = 'showing 0 agents / 0 facts'; - const ca = root.querySelector('#lr-kAgents'); if (ca) ca.textContent = built.agentCount || 0; - const cf = root.querySelector('#lr-kFacts'); if (cf) cf.textContent = built.factCount || 0; - const legendEl = root.querySelector('#lr-know-legend'); - if (legendEl) legendEl.innerHTML = [ - '
nodes · left → right
', - '
evidence
', - '
repo fact
', - '
general fact
', - '
superseded
', - '
category hub
', - '
agent
' - ].join(''); - } - return; - } - this._knowChromeMode = 'clustered'; - if (linkCountEl) { const n = built.factLinkCount || 0; linkCountEl.style.display = ''; linkCountEl.innerHTML = '' + n + ' fact link' + (n === 1 ? '' : 's'); } - if (controlsEl) { - controlsEl.style.display = 'flex'; - controlsEl.querySelectorAll('[data-know-toggle]').forEach(b => { - const which = b.getAttribute('data-know-toggle'); - const on = which === 'links' ? this._knowFactLinksOn : (which === 'cross' ? this._knowCrossRepoOn : this._knowHistoryOn); - b.classList.toggle('on', !!on); b.setAttribute('aria-pressed', on ? 'true' : 'false'); - }); - } - const bold = (v) => '' + v + ''; - const countEl = root.querySelector('#lr-know-count'); - const sub = built.subclusterCount || 0; - if (countEl) countEl.innerHTML = 'showing ' + bold(built.repoCount || 0) + ' repos / ' + bold(built.clusterCount || 0) + ' clusters' + (sub ? ' (' + bold(sub) + ' sub)' : '') + ' / ' + bold(built.factCount || 0) + ' facts'; - const legendEl = root.querySelector('#lr-know-legend'); - if (legendEl) { - const rows = [ - '
fact galaxy · columns
', - '
repo lane
', - '
cluster hub
', - '
repo fact
', - '
general fact
', - '
superseded
', - '
fact link (weight = score)
', - '
cross-clump
', - '
agent
' - ]; - if (sub) rows.splice(3, 0, '
subcluster
'); - if (this._knowCrossRepoOn) rows.splice(rows.length - 1, 0, '
cross-repo
'); - legendEl.innerHTML = rows.join(''); - } - } - - _knowSetMobileView(view) { - this._knowMobileView = view === 'graph' ? 'graph' : 'list'; - this._knowApplyMobile(); - } - - // MOBILE: clustered data keeps the legible repo accordion as its default, with an - // explicit List/Graph switch that makes the real ForceGraph reachable. Desktop and - // fallback (non-clustered) data keep the graph. Idempotent across polls and breakpoints. - _knowApplyMobile() { - const root = this._learningRoot; if (!root) return; - if (this._brainView === 'changelog') return; - const graphEl = root.querySelector('#lr-know-graph'); - const legendEl = root.querySelector('#lr-know-legend'); - const emptyEl = root.querySelector('#lr-empty'); - const switchEl = root.querySelector('#lr-know-mobile-view'); - const mobileEligible = !!(this.state.isMobile && this._knowClustered && !this._knowEmpty); - const showMobileGraph = mobileEligible && this._knowMobileView === 'graph'; - const graphWasMobileHidden = !!(graphEl && graphEl.getAttribute('data-mobile-hidden') === 'true'); - let mob = root.querySelector('#lr-know-mobile'); - if (switchEl) { - switchEl.style.display = mobileEligible ? 'flex' : 'none'; - switchEl.querySelectorAll('[data-know-mobile-view]').forEach(b => { - const on = b.getAttribute('data-know-mobile-view') === (showMobileGraph ? 'graph' : 'list'); - b.classList.toggle('on', on); - b.setAttribute('aria-pressed', on ? 'true' : 'false'); - }); - } - if (mobileEligible && !showMobileGraph) { - if (graphEl) { graphEl.style.display = 'none'; graphEl.setAttribute('data-mobile-hidden', 'true'); } - if (legendEl) legendEl.style.display = 'none'; - if (emptyEl) emptyEl.style.display = 'none'; - if (!mob) { - mob = document.createElement('div'); - mob.id = 'lr-know-mobile'; - const host = root.querySelector('#lr-knowledge'); - if (host) host.appendChild(mob); - mob.addEventListener('click', (e) => { - const ex = e.target.closest && e.target.closest('[data-kexpand]'); - if (ex) { e.stopPropagation(); this._knowExpandCluster(ex.getAttribute('data-kexpand')); return; } - const cl = e.target.closest && e.target.closest('[data-kcluster]'); - if (cl) { this._knowOpenMobileCluster(cl.getAttribute('data-kcluster')); return; } - const rp = e.target.closest && e.target.closest('[data-krepo]'); - if (rp) { this._knowOpenMobileRepo(rp.getAttribute('data-krepo')); return; } - const tg = e.target.closest && e.target.closest('[data-ktog]'); - if (tg) { this._knowMobToggle(tg.getAttribute('data-ktog')); return; } - this.closeKnowledgeDetail(); - this._knowCollapseHierarchy(); - }); - } - mob.style.display = 'block'; - this._knowRenderMobileList(mob); - } else { - if (graphEl) { graphEl.style.display = ''; graphEl.removeAttribute('data-mobile-hidden'); } - if (legendEl) legendEl.style.display = mobileEligible ? 'none' : ''; - if (mob) mob.style.display = 'none'; - if (graphEl && graphWasMobileHidden && this._knowGraph) { - requestAnimationFrame(() => { - if (!this._knowGraph || graphEl.style.display === 'none') return; - const r = graphEl.getBoundingClientRect(); - if (!r.width || !r.height) return; - this._knowGraph.width(r.width).height(r.height); - try { if (this._knowGraph.resumeAnimation) this._knowGraph.resumeAnimation(); } catch (e) {} - if (this._knowEmpty) this._knowFit(0, 60); - else this._knowRelayout(); - }); - } - } - } - - // Render the repo accordion sections from this._knowRepoBands (already ordered - // biggest-first). The largest band starts expanded; the open/closed set persists in - // this._knowMobOpen across polls + toggles. - _knowRenderMobileList(mob) { - const esc = (s) => this._galaxyEsc(s); - const bands = this._knowRepoBands || []; - if (!this._knowMobOpen) { this._knowMobOpen = {}; if (bands.length) this._knowMobOpen[bands[0].scope] = true; } - const html = bands.map(bd => { - const open = !!this._knowMobOpen[bd.scope]; - const rows = this._knowHasSplits - ? ((bd.clusters || []).map(c => { - const parentRow = '
' + - '' + - '' + esc(c.label) + '' + - (c.expandCount ? '' : '') + - '' + (c.count || 0) + '' + - '
'; - const childRows = (c.children || []).map(ch => - '
' + - '' + - '' + esc(ch.label) + '' + - (ch.expandCount ? '' : '') + - '' + (ch.count || 0) + '' + - '
').join(''); - return '
' + parentRow + childRows + '
'; - }).join('') || '
no clusters
') - : ((bd.clusters || []).map(c => - '
' + - '' + - '' + esc(c.label) + '' + - '' + (c.count || 0) + '' + - '
').join('') || '
no clusters
'); - return '
' + - '
' + - '' + - '' + esc(bd.label) + '' + - '' + bd.factCount + ' fact' + (bd.factCount === 1 ? '' : 's') + '' + - '' + (open ? '▾' : '▸') + '' + - '
' + - '
' + rows + '
' + - '
'; - }).join(''); - mob.innerHTML = html || '
no repos
'; - } - _knowMobToggle(scope) { - if (!this._knowMobOpen) this._knowMobOpen = {}; - this._knowMobOpen[scope] = !this._knowMobOpen[scope]; - const mob = this._learningRoot && this._learningRoot.querySelector('#lr-know-mobile'); - if (mob) this._knowRenderMobileList(mob); - } - // Tapping a repo header label opens the repo detail (synthetic band detail object). - _knowOpenMobileRepo(scope) { - const bd = (this._knowRepoBands || []).find(b => b.scope === scope); - if (bd) this.openKnowledgeDetail(bd.detail); - } - // Tapping a cluster row opens the existing cluster detail panel. - _knowOpenMobileCluster(cid) { - let node = null; - try { const ns = (this._knowGraph.graphData() || {}).nodes || []; node = ns.find(n => n.id === cid && n.type === 'cluster') || null; } catch (e) {} - if (!node) { - const c = this._knowClusterById && this._knowClusterById[cid], h = this._knowHierarchy; - if (c && h) { - const root = h.rawById[h.root[cid]] || c; - node = { id: cid, type: 'cluster', label: c.label || cid, count: c.count || 0, repo: root.repo || '', medoid: c.medoid || '', parentId: h.parent[cid] || '', isParent: !!(h.children[cid] || []).length, childIds: (h.children[cid] || []).slice(), __knowRole: h.root[cid] === cid ? 'root' : 'frontier' }; - } - } - if (node) this.openKnowledgeDetail(node); - } - - ensureKnowledgeDetailEl() { - if (this._knowDetailEl && this._knowDetailEl.parentNode) return this._knowDetailEl; - const el = document.createElement('div'); - el.className = 'lr-detail'; - this._learningRoot.querySelector('#lr-knowledge').appendChild(el); - this._knowDetailEl = el; - return el; - } - closeKnowledgeDetail() { - this._knowSelected = null; - try { if (this._knowDetailEl) this._knowDetailEl.remove(); } catch (e) {} - this._knowDetailEl = null; - } - openKnowledgeDetail(node) { - if (!node) { this.closeKnowledgeDetail(); return; } - if (this._knowAdj) this._knowSelected = { id: node.id, neighbors: this._knowAdj.neighbors[node.id] || new Set(), links: this._knowAdj.nodeLinks[node.id] || new Set() }; - else this._knowSelected = { id: node.id, neighbors: new Set(), links: new Set() }; - if (node.type === 'repo') this.renderKnowledgeHubDetail(node, 'repo'); - else if (node.type === 'cluster') { - if (node.isParent || (this._knowHierarchy && (this._knowHierarchy.children[node.id] || []).length)) this.renderKnowledgeParentDetail(node); - else this.renderKnowledgeHubDetail(node, 'cluster'); - } - else if (node.type === 'agent') { if (this._knowClustered) this.renderKnowledgeHubDetail(node, 'agent'); else this.renderKnowledgeAgentDetail(node); } - else if (node.type === 'category') this.renderKnowledgeCategoryDetail(node); - else this.renderKnowledgeFactDetail(node); - } - - // Select a fact by id from within a detail panel (member-list row or a - // [[wikilink]] / linked-fact click). Highlights it in the graph and swaps the - // panel to that fact — the same path as clicking the node directly. - selectKnowledgeFactById(id) { - const f = this._knowFactById && this._knowFactById[id]; - if (!f) return; - let node = null; - try { const nodes = (this._knowGraph.graphData() || {}).nodes || []; node = nodes.find(n => n.id === id && n.type === 'fact') || null; } catch (e) {} - // Fall back to a synthetic node carrying the raw fact so the panel still renders - // even if the fact is not currently a graph node (e.g. filtered/superseded edge case). - this.openKnowledgeDetail(node || this._knowFactNode(f)); - } - selectKnowledgeClusterById(id) { - let node = null; - try { const nodes = (this._knowGraph.graphData() || {}).nodes || []; node = nodes.find(n => n.id === id && n.type === 'cluster') || null; } catch (e) {} - if (!node) { - const c = this._knowClusterById && this._knowClusterById[id]; - const h = this._knowHierarchy; - if (c && h) { const root = h.rawById[h.root[id]] || c; node = { id: c.id, type: 'cluster', label: c.label || c.id, count: c.count || 0, repo: root.repo || '', medoid: c.medoid || '', parentId: h.parent[id] || '', isParent: !!(h.children[id] || []).length, childIds: (h.children[id] || []).slice(), __knowRole: h.root[id] === id ? 'root' : 'frontier' }; } - } - if (node) this.openKnowledgeDetail(node); - } - // Build a graph-shaped fact node object from a raw fact (for panel rendering). - _knowFactNode(f) { - return { id: f.id, type: 'fact', label: f.id, content: f.content || '', repo: f.repo || '', key: f.key || '', owner: f.owner || '', witnesses: f.witnesses || 0, firstSeen: f.firstSeen || 0, lastSeen: f.lastSeen || 0, superseded: !!f.superseded, cluster: f.cluster || '', sourceJob: f.sourceJob || '', sourceFile: f.sourceFile || '', links: Array.isArray(f.links) ? f.links : [] }; - } - - _knowHierarchyBreadcrumb(clusterId) { - const h = this._knowHierarchy; if (!h || !h.chain[clusterId]) return ''; - const rootId = h.root[clusterId] || clusterId; - if ((h.subtreeDepth[rootId] || 0) <= 1) return ''; // preserve shallow detail markup exactly - const esc = (s) => this._galaxyEsc(s), path = h.chain[clusterId]; - return '
' + path.map((id, i) => { - const c = h.rawById[id], label = esc((c && c.label) || id); - const item = i === path.length - 1 ? '' + label + '' : ''; - return (i ? '›' : '') + item; - }).join('') + '
'; - } - - renderKnowledgeFactDetail(node) { - const el = this.ensureKnowledgeDetailEl(); - const esc = (s) => this._galaxyEsc(s); - const scope = node.repo ? node.repo : 'general'; - const scopeCol = node.repo ? '#7dcfff' : '#e0af68'; - const col = node.superseded ? '#5a6088' : scopeCol; - // Cluster label (override wins server-side; rendered verbatim). - const cl = node.cluster ? (this._knowClusterById && this._knowClusterById[node.cluster]) : null; - // Provenance line: learned from a job OR ingested from a file, plus the date. - let provHtml = ''; - if (node.sourceJob || node.sourceFile) { - const when = esc(this._relFromMs(node.firstSeen || node.lastSeen || 0)); - const prov = node.sourceJob - ? 'learned from job ' + esc(node.sourceJob) + '' - : 'ingested from ' + esc(node.sourceFile) + ''; - provHtml = '
' + prov + ' · ' + when + '
'; - } - // Linked facts (the [[wikilinks]]): first-line previews, click to jump. - const links = Array.isArray(node.links) ? node.links : []; - let linksHtml = ''; - if (links.length) { - const rows = links.map(id => { - const f = this._knowFactById && this._knowFactById[id]; - const first = f ? this._knowFirstLine(f.content, 90) : id; - return '
↔' + esc(first) + '
'; - }).join(''); - linksHtml = '
linked facts (' + links.length + ')
'; - } - el.innerHTML = [ - '
', - '', - '
confirmed fact
owned by ' + esc(node.owner || '-') + '
', - '', - '
', - '' + esc(scope) + '', - (cl ? '' + esc(cl.label || cl.id) + '' : ''), - (node.superseded ? 'superseded' : ''), - '
', - '
', - this._knowHierarchyBreadcrumb(node.cluster), - '
' + this._knowRenderMarkdown(node.content || '') + '
', - provHtml, - '
', - '
owner
' + esc(node.owner || '-') + '
', - '
witnesses
' + (node.witnesses || 0) + '
', - (node.key ? '
key
' + esc(node.key) + '
' : ''), - '
scope
' + esc(scope) + '
', - '
', - '
seen
', - '
', - '
first seen
' + esc(this._relFromMs(node.firstSeen)) + '
', - '
last seen
' + esc(this._relFromMs(node.lastSeen)) + '
', - '
', - linksHtml, - '
' - ].join(''); - el.querySelector('.lr-dclose').addEventListener('click', () => this.closeKnowledgeDetail()); - this._knowWireDetailLinks(el); - this._knowWireClusterLinks(el); - } - - // Wire [[wikilink]] chips and linked-fact rows in a detail panel to select the - // target fact. Both carry a data-fact id derived from ALREADY-ESCAPED text. - _knowWireDetailLinks(el) { - el.querySelectorAll('[data-fact]').forEach(a => { - a.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); this.selectKnowledgeFactById(a.getAttribute('data-fact')); }); - }); - } - - _knowWireClusterLinks(el) { - el.querySelectorAll('[data-kcluster]').forEach(a => { - a.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); this.selectKnowledgeClusterById(a.getAttribute('data-kcluster')); }); - }); - } - - // First non-empty line of a fact body, collapsed + capped at `max` chars with an - // ellipsis. Used for member-fact and linked-fact previews. - _knowFirstLine(s, max) { - const raw = String(s == null ? '' : s).replace(/\r\n?/g, '\n'); - let line = ''; - const parts = raw.split('\n'); - for (let i = 0; i < parts.length; i++) { if (parts[i].trim() !== '') { line = parts[i].trim(); break; } } - if (line === '') line = raw.trim(); - line = line.replace(/\s+/g, ' '); - const cap = max || 90; - if (line.length > cap) line = line.slice(0, cap - 1).replace(/\s+\S*$/, '') + '…'; - return line; - } - - // Render an UNTRUSTED fact body as SAFE HTML. Same escape-FIRST contract as the - // chat renderer (_chatRenderMarkdown): every '<'/'>' in the output is a literal - // tag THIS function emits, never anything derived from input, so it is XSS-safe - // by construction (the stored-XSS lesson: escape, THEN transform). Supported - // subset: **bold**, `inline code`, fenced ``` code, - / * lists, plain https - // links (rendered inert-safe with rel=noopener), and [[fact:id]] wikilinks - // (styled clickable cross-references). Deliberately NOT supported: raw HTML, - // images, headings, javascript: URLs. - _knowRenderMarkdown(raw) { - const esc = (s) => this._galaxyEsc(s); - let src = String(raw == null ? '' : raw).replace(/\r\n?/g, '\n'); - const MAX = 16384; - let truncated = false; - if (src.length > MAX) { src = src.slice(0, MAX); truncated = true; } - // Inline transforms run on ALREADY html-escaped text: captured groups can only - // hold escaped chars and can never break out of a tag/attribute. Split on - // inline-code spans; transform links/wikilinks/bold only OUTSIDE code. - const linkify = (t) => { - // Plain http(s) links. The URL is matched from ESCAPED text, so it cannot - // contain a quote/angle-bracket; still, gate the scheme and escape the href. - return t.replace(/(https?:\/\/[^\s<]+)/g, (m) => { - const clean = m.replace(/[.,;:)\]]+$/, ''); - const trail = m.slice(clean.length); - const url = this._galaxySafeUrl(clean.replace(/&/g, '&')); - if (!url) return m; - return '' + clean + '' + trail; - }); - }; - const wikilink = (t) => { - // [[fact:id]] — the id charset is restricted so the captured group stays inert. - return t.replace(/\[\[([A-Za-z0-9][A-Za-z0-9_.:\-]*)\]\]/g, (mm, id) => { - const f = this._knowFactById && this._knowFactById[id]; - const label = f ? this._knowFirstLine(f.content, 40) : id; - const cls = f ? 'lr-wikilink' : 'lr-wikilink dead'; - return '🔗 ' + esc(label) + ''; - }); - }; - const inline = (t) => { - return t.split(/(`[^`\n]+`)/).map((seg) => { - if (seg.length > 1 && seg.charCodeAt(0) === 96 && seg.charCodeAt(seg.length - 1) === 96) { - return '' + seg.slice(1, -1) + ''; - } - return wikilink(linkify(seg.replace(/\*\*([^*\n]+)\*\*/g, '$1'))); - }).join(''); - }; - const lines = esc(src).split('\n'); - const out = []; - let i = 0; - const n = lines.length; - const isFence = (l) => /^\s*```/.test(l); - const isBullet = (l) => /^\s*[-*]\s+/.test(l); - while (i < n) { - const line = lines[i]; - if (isFence(line)) { - const buf = []; - i++; - while (i < n && !/^\s*```\s*$/.test(lines[i])) { buf.push(lines[i]); i++; } - if (i < n) i++; // consume the closing fence - out.push('
' + buf.join('\n') + '
'); - continue; - } - if (isBullet(line)) { - const items = []; - while (i < n && isBullet(lines[i])) { items.push('
  • ' + inline(lines[i].replace(/^\s*[-*]\s+/, '')) + '
  • '); i++; } - out.push('
      ' + items.join('') + '
    '); - continue; - } - const para = []; - while (i < n) { - const l = lines[i]; - if (isFence(l) || isBullet(l)) break; - if (l.trim() === '') { i++; break; } - para.push(inline(l)); - i++; - } - if (para.length) out.push('
    ' + para.join('
    ') + '
    '); - } - if (truncated) out.push('
    … (truncated)
    '); - return out.join(''); - } - - // A split parent has no direct fact fan. Its panel summarizes the hierarchy and - // lets each child open the normal cluster panel, while preserving the rename command - // on the stable parent id. - renderKnowledgeParentDetail(node) { - const el = this.ensureKnowledgeDetailEl(); - const esc = (s) => this._galaxyEsc(s); - const h = this._knowHierarchy; - const childIds = (node.childIds && node.childIds.length) - ? node.childIds.slice() - : ((h && h.children[node.id]) || []).slice(); - childIds.sort(); - const allFacts = this._knowFactById ? Object.keys(this._knowFactById).map(k => this._knowFactById[k]) : []; - const graphNodes = {}; - try { ((this._knowGraph.graphData() || {}).nodes || []).forEach(n => { graphNodes[n.id] = n; }); } catch (e) {} - let totalFacts = 0; - const children = childIds.map(id => { - const raw = this._knowClusterById && this._knowClusterById[id]; - const ch = graphNodes[id] || raw || { id: id, label: id, count: 0 }; - const members = {}; [id].concat((h && h.descendants[id]) || []).forEach(cid => { members[cid] = 1; }); - const count = allFacts.reduce((n, f) => n + (members[f.cluster || ''] ? 1 : 0), 0); - totalFacts += count; - return { id: id, label: ch.label || id, count: count }; - }); - const scope = node.repo || ((this._knowClusterById && this._knowClusterById[node.id] && this._knowClusterById[node.id].repo) || ''); - const scopeLabel = scope || 'general'; - const scopeCol = scope ? '#7dcfff' : '#e0af68'; - const rows = children.length - ? children.map(ch => '
    ' + - '' + - '' + esc(ch.label) + '' + - '' + ch.count + ' fact' + (ch.count === 1 ? '' : 's') + '' + - '
    ').join('') - : '
    no subclusters
    '; - el.innerHTML = [ - '
    ', - '', - '
    ' + esc(node.label || node.id) + '
    parent cluster
    ', - '', - '
    ', - '' + esc(scopeLabel) + '', - '' + totalFacts + ' facts', - '
    ', - '
    ', - this._knowHierarchyBreadcrumb(node.id), - '
    gitmoot memory cluster rename ' + esc(node.id) + ' <label>
    ', - '
    ' + children.length + ' subcluster' + (children.length === 1 ? '' : 's') + ' · ' + totalFacts + ' total facts
    ', - '
    ' + rows + '
    ', - '
    ' - ].join(''); - el.querySelector('.lr-dclose').addEventListener('click', () => this.closeKnowledgeDetail()); - this._knowWireClusterLinks(el); - } - - // Unified hub detail (repo / cluster / agent): header + a member-fact list - // (first line each, newest-first, with per-repo count badges). Clicking a row - // selects that fact. Members are gathered from the raw facts by the hub kind. - renderKnowledgeHubDetail(node, kind) { - const el = this.ensureKnowledgeDetailEl(); - const esc = (s) => this._galaxyEsc(s); - const facts = []; - const allFacts = this._knowFactById ? Object.keys(this._knowFactById).map(k => this._knowFactById[k]) : []; - allFacts.forEach(f => { - if (!f) return; - if (kind === 'repo') { - // CLUSTERED (option A repo swimlanes): a band's membership is the fact's CLUSTER - // dominant scope, not the fact's own repo — so filter by the same clusterScope - // map the band build used, keeping panel members == band members == highlight. - // A cross-scope member (its own f.repo differs from the lane scope) still shows - // its own repo badge in the row below — the honest view. Non-clustered category/ - // repo detail keeps the fact.repo filter as the fallback path. - if (this._knowClustered && this._knowClusterScope) { - let sc = this._knowClusterScope[f.cluster || '']; - if (sc === undefined) sc = ''; // fell into the unclustered bucket (scope '') - if (node.general ? sc === '' : sc === node.repoName) facts.push(f); - } else { - const rp = f.repo || ''; - if (node.general ? rp === '' : rp === node.repoName) facts.push(f); - } - } - else if (kind === 'cluster') { if ((f.cluster || '') === node.id) facts.push(f); } - else if (kind === 'agent') { if ((f.owner || '') === node.id) facts.push(f); } - }); - // Newest-first by firstSeen, id tie-break (deterministic). - facts.sort((a, b) => { const av = a.firstSeen || 0, bv = b.firstSeen || 0; if (av !== bv) return bv - av; return a.id < b.id ? -1 : a.id > b.id ? 1 : 0; }); - // Per-repo count badges. - const repoCount = {}; - facts.forEach(f => { const rp = f.repo ? f.repo : 'general'; repoCount[rp] = (repoCount[rp] || 0) + 1; }); - const badgeRepos = Object.keys(repoCount).sort(); - const badges = badgeRepos.map(rp => { - const isGen = rp === 'general'; - const c = isGen ? '#e0af68' : '#7dcfff'; - return '' + esc(rp) + ' · ' + repoCount[rp] + ''; - }).join(''); - const meta = (kind === 'cluster') - ? { dot: '#bb9af7', title: node.label || node.id, sub: 'emergent cluster' } - : (kind === 'agent') - ? { dot: '#bb9af7', title: node.label || node.id, sub: 'memory agent' } - : { dot: (node.general ? '#e0af68' : '#7dcfff'), title: node.label || node.id, sub: 'repository' }; - const rows = facts.length - ? facts.map(f => { - const superCls = f.superseded ? ' sup' : ''; - const scopeCol = f.superseded ? '#5a6088' : (f.repo ? '#7dcfff' : '#e0af68'); - return '
    ' + - '' + - '' + esc(this._knowFirstLine(f.content, 90)) + '' + - '
    '; - }).join('') - : '
    no facts
    '; - // Cluster panels also carry a rename hint (owner override wins; label verbatim). - const renameHint = (kind === 'cluster') - ? '
    gitmoot memory cluster rename ' + esc(node.id) + ' <label>
    ' - : ''; - const parentId = kind === 'cluster' && this._knowHierarchy ? this._knowHierarchy.parent[node.id] : (node.parentId || ''); - const parent = parentId ? (this._knowClusterById && this._knowClusterById[parentId]) : null; - const breadcrumb = kind === 'cluster' ? this._knowHierarchyBreadcrumb(node.id) : ''; - const parentLine = breadcrumb || (parent - ? '
    parent: ' + esc(parent.label || parent.id) + '
    ' - : ''); - el.innerHTML = [ - '
    ', - '', - '
    ' + esc(meta.title) + '
    ' + esc(meta.sub) + '
    ', - '', - '
    ' + badges + '
    ', - '
    ', - parentLine, - renameHint, - '
    ' + facts.length + ' fact' + (facts.length === 1 ? '' : 's') + ' · newest first
    ', - '
    ' + rows + '
    ', - (kind === 'agent' ? 'View agent→' : ''), - '
    ' - ].join(''); - el.querySelector('.lr-dclose').addEventListener('click', () => this.closeKnowledgeDetail()); - this._knowWireDetailLinks(el); - this._knowWireClusterLinks(el); - const go = el.querySelector('[data-goagent]'); - if (go) go.addEventListener('click', () => this._learningGotoAgent(go.getAttribute('data-goagent'))); - } - - renderKnowledgeAgentDetail(node) { - const el = this.ensureKnowledgeDetailEl(); - const esc = (s) => this._galaxyEsc(s); - const col = '#bb9af7'; - const enrolled = !!node.enrolled; - el.innerHTML = [ - '
    ', - '', - '
    ' + esc(node.label || node.id) + '
    memory agent
    ', - '', - '
    ', - (enrolled ? 'enrolled' : 'not enrolled'), - '
    ', - '
    ', - '
    ', - '
    facts
    ' + (node.facts || 0) + '
    ', - '
    observations
    ' + (node.observations || 0) + '
    ', - '
    ', - 'View agent→', - '
    ' - ].join(''); - el.querySelector('.lr-dclose').addEventListener('click', () => this.closeKnowledgeDetail()); - const link = el.querySelector('.lr-dlink'); - if (link) link.addEventListener('click', () => this._learningGotoAgent(node.id)); - } - - renderKnowledgeCategoryDetail(node) { - const el = this.ensureKnowledgeDetailEl(); - const esc = (s) => this._galaxyEsc(s); - const col = '#bb9af7'; - let n = 0; try { const set = this._knowAdj && this._knowAdj.neighbors[node.id]; n = set ? set.size : 0; } catch (e) {} - el.innerHTML = [ - '
    ', - '', - '
    ' + esc(this._knowCatLabel(node.id)) + '
    category hub
    ', - '', - '
    ', - 'category', - '
    ', - '
    connected nodes
    ' + n + '
    ' - ].join(''); - el.querySelector('.lr-dclose').addEventListener('click', () => this.closeKnowledgeDetail()); - } - - // ---- live feed: /api/state (graph) + /events (SSE) + /api/runs (list) ---- - connectLive() { - this.currentRunId = new URLSearchParams(location.search).get('run') || ''; - this.loadState(); - this.subscribeEvents(); - } - subscribeEvents() { - try { if (this._es) this._es.close(); } catch (e) {} - try { - const run = this.currentRunId || ''; - this._es = new EventSource('/events' + (run ? '?run=' + encodeURIComponent(run) : '')); - this._es.onmessage = (e) => { try { this.applyState(JSON.parse(e.data)); } catch (_) {} }; - } catch (e) {} - } - loadState() { - const run = this.currentRunId || ''; - fetch('/api/state' + (run ? '?run=' + encodeURIComponent(run) : '')) - .then(r => r.ok ? r.json() : null) - .then(s => { if (s && (this.currentRunId || '') === run) this.applyState(s); }) // drop stale after a switch - .catch(() => {}); - } - loadRuns() { - fetch('/api/runs').then(r => r.ok ? r.json() : []).then(rs => { - if (!Array.isArray(rs)) { this.setState({ listLoading: false }); return; } - const now = Date.now(); - this.runs = rs.map(r => ({ - runId: r.runId, title: r.title || r.runId, state: r.state || 'queued', - kind: r.kind || '', significance: r.significance || 'one-shot', - agent: r.agent || '', repo: r.repo || '', pr: r.pr || 0, - nodeCount: r.nodeCount || 0, depth: r.depth || 1, doneCount: r.doneCount || 0, - snippet: r.snippet || '', ago: (r.updated && r.updated > 0) ? Math.max(0, now - r.updated) : Number.MAX_SAFE_INTEGER - })); - const uniq = (k) => Array.from(new Set(this.runs.map(r => r[k]).filter(Boolean))); - this.facetDefs = Object.assign({}, this.facetDefs, { agent: uniq('agent'), repo: uniq('repo') }); - // NB: the graph load (applyState) owns currentRunId/selectedRunId — see below. - this.setState({ listLoading: false, listError: false }); - }).catch(() => this.setState({ listLoading: false, listError: !this.runs.length })); // keep the list on a transient poll failure + loadRuns() { + fetch('/api/runs').then(r => r.ok ? r.json() : []).then(rs => { + if (!Array.isArray(rs)) { this.setState({ listLoading: false }); return; } + const now = Date.now(); + this.runs = rs.map(r => ({ + runId: r.runId, title: r.title || r.runId, state: r.state || 'queued', + kind: r.kind || '', significance: r.significance || 'one-shot', + agent: r.agent || '', repo: r.repo || '', pr: r.pr || 0, + nodeCount: r.nodeCount || 0, depth: r.depth || 1, doneCount: r.doneCount || 0, + snippet: r.snippet || '', ago: (r.updated && r.updated > 0) ? Math.max(0, now - r.updated) : Number.MAX_SAFE_INTEGER + })); + const uniq = (k) => Array.from(new Set(this.runs.map(r => r[k]).filter(Boolean))); + this.facetDefs = Object.assign({}, this.facetDefs, { agent: uniq('agent'), repo: uniq('repo') }); + // NB: the graph load (applyState) owns currentRunId/selectedRunId — see below. + this.setState({ listLoading: false, listError: false }); + }).catch(() => this.setState({ listLoading: false, listError: !this.runs.length })); // keep the list on a transient poll failure } renderWorkflowContext(label) { this.currentWorkflow = label || ''; @@ -10867,7 +7578,6 @@ // lesson: a duplicate member name silently overrides an existing one). // ========================================================================== - // Absolute local time (month/day + HH:MM), matching the Jobs/Health idiom. _plFmtAbsTime(ms) { if (!ms || ms <= 0) return '-'; @@ -11128,49 +7838,6 @@ return { id: e.id, pipeline: detail.name, trigger: e.trigger, state: e.state, haltStage: e.haltStage, startedAt: e.startedAt, finishedAt: e.finishedAt, stages: stages }; } - // ============================================================ - // Chat view (gitmoot #534): repo-scoped agent coordination - // threads. A card list (open/all/archived filter + client-side - // search) plus a slide-in message history (like the Jobs - // detail). Same body-appended overlay + signature-skip poll - // pattern as Jobs/Pipelines. Bodies are UNTRUSTED — every render - // path escapes through _galaxyEsc + white-space:pre-wrap. - // ============================================================ - startChatPoll() { - if (this._chatPoll) return; - this._chatPoll = setInterval(() => { - if (this.state.view !== 'chat') return; - this.fetchChatThreads(true); - // relative last-activity labels are derived from Date.now(), so the - // signature-skip would freeze them; refresh them every tick regardless. - this.refreshChatTimes(); - }, 12000); - } - stopChatPoll() { try { clearInterval(this._chatPoll); } catch (e) {} this._chatPoll = null; } - // Second poll: while a thread is open, refresh JUST that thread so new - // messages / a resumed job_result surface live. Self-guarded. - startChatThreadPoll() { - if (this._chatThreadPoll) return; - this._chatThreadPoll = setInterval(() => { - if (this.state.view !== 'chat' || !this._chatSelected) return; - this.fetchChatThread(this._chatSelected, true); - }, 12000); - } - stopChatThreadPoll() { try { clearInterval(this._chatThreadPoll); } catch (e) {} this._chatThreadPoll = null; } - - // Seed / update the nav attention dot: true when any OPEN thread has unread - // @mentions. Only re-renders the shell when the flag actually flips. - loadChatAttn() { - fetch('/api/chat/threads', { cache: 'no-store' }) - .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status))) - .then(json => { if (Array.isArray(json)) this._updateChatAttn(json); }) - .catch(() => {}); // fail-open: the dot just stays off - } - _updateChatAttn(threads) { - const attn = (Array.isArray(threads) ? threads : []).some(t => t && t.state === 'open' && (t.unreadMentions || 0) > 0); - if (attn !== this.state.chatAttn) this.setState({ chatAttn: attn }); - } - // ---- Persistent top bar + nav "needs you" dots ---------------------------- // One light batch fetch that feeds the always-visible signals (daemon liveness // for the top bar; amber needs-you dots for Health/Pipelines/Learning/Attention). @@ -11255,12 +7922,10 @@ _navMoreTasks = () => { this.setState({ moreOpen: false }); this.showTasks(); }; _navMoreWorkflows = () => { this.setState({ moreOpen: false }); this.showWorkflows(); }; _navMoreJobs = () => { this.setState({ moreOpen: false }); this.showJobs(); }; - _navMoreBrain = () => { this.setState({ moreOpen: false }); this.showBrain(); }; _navMoreCharts = () => { this.setState({ moreOpen: false }); this.showCharts(); }; _navMoreLearning = () => { this.setState({ moreOpen: false }); this.showLearning(); }; _navMoreConfig = () => { this.setState({ moreOpen: false }); this.showConfig(); }; _navMorePipelines = () => { this.setState({ moreOpen: false }); this.showPipelines(); }; - _navMoreChat = () => { this.setState({ moreOpen: false }); this.showChat(); }; _navMoreAgents = () => { this.setState({ moreOpen: false }); this.showAgents(); }; _navMoreOrg = () => { this.setState({ moreOpen: false }); this.showOrg(); }; _navMoreAttention = () => { this.setState({ moreOpen: false }); this.showAttention(); }; @@ -11280,858 +7945,6 @@ } catch (e) { this._copyFallback(cmd); flash(); } } - // ============================================================ - // Chat view (gitmoot #534) — THREE-PANE: thread rail | conversation - // | thread details. Body-appended imperative overlay (#chat-root), - // same signature-skip poll pattern as Jobs/Pipelines. Message - // bodies are UNTRUSTED — every render path escapes through - // _galaxyEsc + the chat-safe markdown whitelist (_chatRenderMarkdown). - // ============================================================ - ensureChatDom() { - if (this._chatRoot) return this._chatRoot; - if (!this._chatFilter) this._chatFilter = 'open'; - // Collapse prefs (persisted; mobile ignores the info column). Clone the - // Graph runsOpen pattern: read once, default open. - if (this._chatListOpen == null) { let v = true; try { const s = localStorage.getItem('gitmoot.chatListOpen'); if (s != null) v = s === '1'; } catch (e) {} this._chatListOpen = v; } - if (this._chatInfoOpen == null) { let v = true; try { const s = localStorage.getItem('gitmoot.chatInfoOpen'); if (s != null) v = s === '1'; } catch (e) {} this._chatInfoOpen = v; } - const st = document.createElement('style'); - st.textContent = [ - "#chat-root{font-family:Inter,system-ui,sans-serif;color:#c8cce6;background:#0b0d16;display:none;grid-template-rows:100%;overflow:hidden}", - // ---- LEFT: thread rail ---- - "#chat-root .ch-rail{background:#0a0b16;border-right:1px solid rgba(160,168,220,0.08);display:flex;flex-direction:column;min-height:0;min-width:0;overflow:hidden}", - "#chat-root .ch-rail-full{display:flex;flex-direction:column;min-height:0;flex:1}", - "#chat-root .ch-rail-mini{display:none;flex-direction:column;align-items:center;padding-top:14px;gap:12px;flex:1}", - "#chat-root .ch-rail-mini .ch-vlabel{writing-mode:vertical-rl;font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:0.16em;color:#5a6088}", - "#chat-root .ch-rail-head{display:flex;align-items:center;padding:15px 14px 10px;flex:none}", - "#chat-root .ch-rail-title{font-family:'JetBrains Mono',monospace;font-size:10.5px;letter-spacing:0.15em;color:#868db5;font-weight:600}", - "#chat-root .ch-rail-count{margin-left:7px;font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#5a6088}", - "#chat-root .ch-icbtn{width:24px;height:24px;display:flex;align-items:center;justify-content:center;background:rgba(160,168,220,0.06);border:1px solid rgba(160,168,220,0.14);border-radius:7px;color:#868db5;font-size:14px;line-height:1;cursor:pointer;padding:0;flex:none}", - "#chat-root .ch-icbtn:hover{border-color:rgba(125,207,255,0.4);color:#c8f0ff}", - "#chat-root .ch-filters{padding:0 14px 10px;display:flex;gap:8px;align-items:center;flex:none}", - "#chat-root .ch-seg{display:flex;background:#14172a;border:1px solid rgba(160,168,220,0.14);border-radius:8px;padding:2px;gap:2px}", - "#chat-root .ch-seg button{appearance:none;padding:5px 13px;border-radius:6px;border:none;cursor:pointer;font-family:Inter,sans-serif;font-size:11.5px;font-weight:500;background:transparent;color:#868db5}", - "#chat-root .ch-seg button.on{background:rgba(158,206,106,0.14);color:#c5f882}", - "#chat-root .ch-searchwrap{padding:0 14px 11px;position:relative;flex:none}", - "#chat-root .ch-searchwrap svg{position:absolute;left:24px;top:50%;transform:translateY(-50%);color:#5a6088;pointer-events:none}", - "#chat-root .ch-search{width:100%;box-sizing:border-box;padding:8px 12px 8px 32px;background:#0f1120;border:1px solid rgba(160,168,220,0.14);border-radius:9px;color:#eef0ff;font-size:12.5px;font-family:Inter,sans-serif;outline:none}", - "#chat-root .ch-search:focus{border-color:rgba(125,207,255,0.4)}", - "#chat-root .ch-list{flex:1;overflow-y:auto;min-height:0;padding:0 6px 12px}", - "#chat-root .ch-row{padding:9px 11px;margin:2px 4px;border-radius:9px;cursor:pointer;border:1px solid transparent}", - "#chat-root .ch-row:hover{background:rgba(160,168,220,0.05)}", - "#chat-root .ch-row.sel{background:rgba(158,206,106,0.09);border-color:rgba(158,206,106,0.22)}", - "#chat-root .ch-row-top{display:flex;align-items:center;gap:8px}", - "#chat-root .ch-dot{width:8px;height:8px;border-radius:50%;flex:none}", - "#chat-root .ch-dot.open{background:#9ece6a;box-shadow:0 0 8px rgba(158,206,106,0.5)}", - "#chat-root .ch-dot.archived{background:#5a6088}", - "#chat-root .ch-row-name{flex:1;min-width:0;font-size:12.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#c7c9e5}", - "#chat-root .ch-row.sel .ch-row-name{color:#eef0ff}", - "#chat-root .ch-ment{font-family:'JetBrains Mono',monospace;font-size:9.5px;font-weight:700;color:#e0af68;background:rgba(224,175,104,0.14);border:1px solid rgba(224,175,104,0.3);border-radius:8px;padding:1px 6px;flex:none}", - "#chat-root .ch-row-time{font-family:'JetBrains Mono',monospace;font-size:9.5px;color:#5a6088;flex:none}", - "#chat-root .ch-row-prev{font-size:11.5px;color:#7c83a8;margin-top:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-row-prev b{color:#a8aecf;font-weight:600}", - "#chat-root .ch-ktag{font-family:'JetBrains Mono',monospace;font-size:9px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;padding:0 5px;border-radius:4px;margin-right:5px}", - "#chat-root .ch-empty{padding:44px 18px;text-align:center;color:#5a6088;font-size:12.5px;line-height:1.7}", - "#chat-root .ch-empty code{font-family:'JetBrains Mono',monospace;font-size:12px;color:#c7c9e5;background:#0a0b16;border:1px solid rgba(160,168,220,0.14);border-radius:6px;padding:2px 7px}", - // ---- CENTER: conversation ---- - "#chat-root .ch-conv{display:flex;flex-direction:column;min-width:0;min-height:0;position:relative;background:#0b0d16}", - "#chat-root .ch-conv-head{flex:none;padding:13px 22px;border-bottom:1px solid rgba(160,168,220,0.08);display:flex;align-items:center;gap:11px}", - "#chat-root .ch-conv-head.mob{padding:12px 14px;gap:10px}", - "#chat-root .ch-conv-htext{flex:1;min-width:0}", - "#chat-root .ch-conv-name{font-size:15px;font-weight:600;color:#eef0ff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-conv-sub{font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#5a6088;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-conv-repo{font-family:'JetBrains Mono',monospace;font-size:11.5px;color:#5a6088;margin-left:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-cdot{width:8px;height:8px;border-radius:50%;flex:none;background:#5a6088}", - "#chat-root .ch-statechip{font-family:'JetBrains Mono',monospace;font-size:10px;font-weight:600;letter-spacing:0.4px;padding:2px 8px;border-radius:6px;text-transform:lowercase}", - "#chat-root .ch-statechip.open{color:#9ece6a;background:rgba(158,206,106,0.12);border:1px solid rgba(158,206,106,0.3)}", - "#chat-root .ch-statechip.archived{color:#8a91b8;background:rgba(138,145,184,0.10);border:1px solid rgba(138,145,184,0.3)}", - "#chat-root .cd-body{flex:1;overflow-y:auto;min-height:0}", - "#chat-root .cd-empty{padding:30px 22px;color:#5a6088;font-size:12.5px}", - "#chat-root .cd-empty-view{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:#5a6088;padding:20px;text-align:center}", - "#chat-root .cd-empty-ic{width:52px;height:52px;border-radius:14px;background:#14172a;border:1px solid rgba(160,168,220,0.14);display:flex;align-items:center;justify-content:center;color:#5a6088}", - "#chat-root .cd-empty-t{font-size:15px;color:#a8aecf;font-weight:500}", - "#chat-root .cd-empty-d{font-size:12.5px;color:#5a6088;max-width:300px;line-height:1.5}", - "#chat-root .cd-msg{display:flex;gap:13px;padding:13px 22px;border-bottom:1px solid rgba(160,168,220,0.04)}", - "#chat-root .cd-msg.you{background:linear-gradient(90deg,rgba(122,162,247,0.06),transparent 70%);border-left:2px solid rgba(122,162,247,0.4)}", - "#chat-root .ch-av{border-radius:50%;flex:none;display:grid;place-items:center;font-family:'JetBrains Mono',monospace;font-weight:700}", - "#chat-root .cd-mbody{flex:1;min-width:0}", - "#chat-root .cd-mhead{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin-bottom:5px}", - "#chat-root .cd-author{font-size:13px;font-weight:700}", - "#chat-root .cd-you{font-family:'JetBrains Mono',monospace;font-size:9px;color:#7aa2f7;background:rgba(122,162,247,0.14);border:1px solid rgba(122,162,247,0.3);border-radius:5px;padding:1px 6px}", - "#chat-root .cd-kindbadge{font-family:'JetBrains Mono',monospace;font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.04em;padding:1px 6px;border-radius:5px}", - "#chat-root .cd-time{font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#5a6088}", - "#chat-root .cd-cont{font-size:13.5px;line-height:1.6;color:#c7c9e5;word-break:break-word}", - "#chat-root .cd-cont.code{background:rgba(122,162,247,0.07);border:1px solid rgba(122,162,247,0.2);border-left:3px solid #7aa2f7;border-radius:9px;padding:12px 14px;font-family:'JetBrains Mono',monospace;font-size:12px;line-height:1.7;color:#b7c3ea}", - "#chat-root .cd-cont.gate{background:rgba(224,175,104,0.07);border:1px solid rgba(224,175,104,0.22);border-left:3px solid #e0af68;border-radius:9px;padding:11px 14px;color:#e6d3b0}", - "#chat-root .cd-askgate{display:flex;align-items:center;gap:7px;font-family:'JetBrains Mono',monospace;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:#e0af68;margin-bottom:8px}", - "#chat-root .cd-cont > :first-child{margin-top:0}", - "#chat-root .cd-cont .cd-p{margin:0}", - "#chat-root .cd-cont .cd-p + .cd-p{margin-top:7px}", - "#chat-root .cd-cont strong{color:#eef0ff;font-weight:700}", - "#chat-root .cd-cont .cd-trunc{margin-top:7px;font-size:10px;font-style:italic;color:#7a82a8}", - "#chat-root .cd-cont .cd-code{font-family:'JetBrains Mono',monospace;font-size:0.9em;background:rgba(160,168,220,0.13);border:1px solid rgba(160,168,220,0.16);border-radius:5px;padding:0.5px 5px;color:#c8f0ff;white-space:pre-wrap;word-break:break-word}", - "#chat-root .cd-cont .cd-pre{margin:8px 0;background:#06070d;border:1px solid rgba(160,168,220,0.16);border-radius:8px;padding:9px 11px;overflow-x:auto;white-space:normal}", - "#chat-root .cd-cont .cd-pre code{display:block;font-family:'JetBrains Mono',monospace;font-size:11px;line-height:1.5;color:#c7d3f0;white-space:pre}", - "#chat-root .cd-cont .cd-quote{margin:8px 0;padding:2px 0 2px 11px;border-left:3px solid rgba(122,162,247,0.5);color:#aab2d8;font-style:italic}", - "#chat-root .cd-cont .cd-ul{margin:6px 0;padding-left:20px;list-style:disc}", - "#chat-root .cd-cont .cd-ul li{margin:2px 0}", - "#chat-root .cd-mention{font-family:'JetBrains Mono',monospace;font-size:0.92em;font-weight:600;color:#7dcfff;background:rgba(125,207,255,0.12);border:1px solid rgba(125,207,255,0.26);border-radius:5px;padding:0 5px;white-space:nowrap}", - "#chat-root .cd-mention.you{color:#e0af68;background:rgba(224,175,104,0.12);border-color:rgba(224,175,104,0.26)}", - "#chat-root .cd-refs{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:8px}", - "#chat-root .cd-ref{display:inline-flex;align-items:center;gap:5px;font-family:'JetBrains Mono',monospace;font-size:10px;color:#a8aecf;background:rgba(160,168,220,0.06);border:1px solid rgba(160,168,220,0.14);padding:2px 8px;border-radius:6px;text-decoration:none}", - "#chat-root a.cd-ref,#chat-root .cd-ref[data-job]{cursor:pointer}", - "#chat-root a.cd-ref:hover,#chat-root .cd-ref[data-job]:hover{border-color:rgba(125,207,255,0.4);color:#c8f0ff}", - "#chat-root .cd-ref.job{color:#7aa2f7;border-color:rgba(122,162,247,0.3)}", - "#chat-root .cd-ref.pr{color:#9ece6a;border-color:rgba(158,206,106,0.3)}", - "#chat-root .cd-promo{display:inline-flex;align-items:center;gap:5px;font-family:'JetBrains Mono',monospace;font-size:10px;color:#bb9af7;background:rgba(187,154,247,0.08);border:1px solid rgba(187,154,247,0.3);padding:2px 8px;border-radius:6px;cursor:pointer}", - "#chat-root .cd-promo:hover{border-color:rgba(187,154,247,0.55)}", - "#chat-root .ch-composer{flex:none;padding:12px 22px 16px;border-top:1px solid rgba(160,168,220,0.08);background:rgba(10,11,22,0.4)}", - "#chat-root .ch-composer-bar{display:flex;align-items:center;gap:10px;padding:11px 14px;background:#0f1120;border:1px solid rgba(160,168,220,0.16);border-radius:11px}", - "#chat-root .ch-term{color:#5a6088;display:flex;flex:none}", - "#chat-root .ch-composer-ph{flex:1;min-width:0;font-size:13px;color:#5a6088;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-composer-hint{margin-top:8px;font-family:'JetBrains Mono',monospace;font-size:10.5px;color:#5a6088;padding-left:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - "#chat-root .ch-composer-hint span{color:#868db5}", - "#chat-root .ch-newpill{position:absolute;left:50%;transform:translateX(-50%);bottom:92px;display:flex;align-items:center;gap:7px;padding:7px 14px;background:rgba(122,162,247,0.18);border:1px solid rgba(122,162,247,0.4);border-radius:20px;color:#bcd0ff;font-size:12px;font-weight:500;cursor:pointer;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);box-shadow:0 8px 24px rgba(0,0,0,0.4);z-index:5}", - // ---- RIGHT: thread details ---- - "#chat-root .ch-info{background:#0a0b16;border-left:1px solid rgba(160,168,220,0.08);display:flex;flex-direction:column;min-height:0;min-width:0;overflow:hidden}", - "#chat-root .ch-info.mini{align-items:center;padding-top:14px}", - "#chat-root .ci-head{display:flex;align-items:center;padding:16px 18px 12px;border-bottom:1px solid rgba(160,168,220,0.08);flex:none}", - "#chat-root .ci-htitle{font-family:'JetBrains Mono',monospace;font-size:10.5px;letter-spacing:0.14em;color:#868db5;font-weight:600}", - "#chat-root .ci-scroll{flex:1;overflow-y:auto;min-height:0;padding:0 0 18px}", - "#chat-root .ci-rows{padding:16px 18px;display:flex;flex-direction:column;gap:9px}", - "#chat-root .ci-kv{display:flex;align-items:center;gap:9px}", - "#chat-root .ci-k{font-size:10px;color:#5a6088;text-transform:uppercase;letter-spacing:0.05em;width:78px;flex:none}", - "#chat-root .ci-val{font-size:12.5px;color:#a8aecf}", - "#chat-root .ci-mono{font-family:'JetBrains Mono',monospace;font-size:12px;color:#a8aecf;word-break:break-word}", - "#chat-root .ci-sec{padding:8px 18px 6px;font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:0.13em;color:#5a6088}", - "#chat-root .ci-members{padding:2px 12px 6px;display:flex;flex-direction:column;gap:2px}", - "#chat-root .ci-member{display:flex;align-items:center;gap:11px;padding:7px 10px;border-radius:9px}", - "#chat-root .ci-mtext{flex:1;min-width:0}", - "#chat-root .ci-mname{display:flex;align-items:center;gap:6px;font-size:12.5px;font-weight:600;color:#eef0ff}", - "#chat-root .ci-mkind{font-family:'JetBrains Mono',monospace;font-size:9px;color:#868db5;background:rgba(160,168,220,0.08);border-radius:4px;padding:1px 5px;font-weight:400}", - "#chat-root .ci-mmeta{font-family:'JetBrains Mono',monospace;font-size:10px;color:#5a6088;margin-top:2px}", - "#chat-root .ci-linked{padding:4px 16px 8px;display:flex;flex-wrap:wrap;gap:7px}", - "#chat-root .ci-none{padding:2px 18px 8px;font-size:11.5px;color:#5a6088}", - "#chat-root .ci-sendwrap{padding:12px 16px 4px}", - "#chat-root .ci-sendbar{display:flex;align-items:center;gap:9px;padding:9px 10px 9px 12px;background:#0f1120;border:1px solid rgba(160,168,220,0.16);border-radius:9px;margin-top:6px}", - "#chat-root .ci-sendcmd{flex:1;min-width:0;font-family:'JetBrains Mono',monospace;font-size:11px;color:#868db5;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}", - // ---- mobile info bottom sheet ---- - "#chat-root .ch-scrim{position:absolute;inset:0;background:rgba(4,5,10,0.5);z-index:44}", - "#chat-root .ch-sheet{position:absolute;left:0;right:0;bottom:0;max-height:80%;z-index:45;background:#0a0b16;border-top:1px solid rgba(160,168,220,0.14);border-radius:16px 16px 0 0;box-shadow:0 -20px 50px rgba(0,0,0,0.5);display:flex;flex-direction:column;overflow:hidden}", - // ---- responsive tweaks ---- - "@media (max-width:768px){#chat-root .cd-msg{padding:11px 14px;gap:11px}#chat-root .ch-composer{padding:10px 12px 12px}#chat-root .ch-composer-bar{border-radius:10px}#chat-root .ch-newpill{bottom:80px}}", - "@media (pointer:coarse){#chat-root .ch-icbtn{width:34px;height:34px;font-size:16px}}" - ].join('\n'); - document.head.appendChild(st); - - const searchIcon = ""; - - const root = document.createElement('div'); - root.id = 'chat-root'; - root.style.cssText = 'position:fixed;left:216px;top:54px;right:0;bottom:0;z-index:40;background:#0b0d16;display:none;grid-template-rows:100%;overflow:hidden;font-family:Inter,system-ui,sans-serif;color:#c8cce6'; - root.innerHTML = [ - '
    ', - '
    ', - '
    THREADS
    ', - '
    ', - '
    ' + searchIcon + '
    ', - '
    loading…
    ', - '
    ', - '
    THREADS
    ', - '
    ', - '
    ', - '
    ', - '', - '' - ].join(''); - document.body.appendChild(root); - this._dockOverlay(root); // mobile: left:0 + bottom clears the tab bar - this._chatRoot = root; - - const inp = root.querySelector('.ch-search'); - if (inp) inp.value = this._chatQuery || ''; - - // One delegated click listener for the whole chat surface. - root.addEventListener('click', (e) => { - const t = e.target; - const act = t.closest ? t.closest('[data-chat-act]') : null; - if (act) { - const a = act.getAttribute('data-chat-act'); - e.stopPropagation(); - if (a === 'toggle-list') this._chatToggleList(); - else if (a === 'toggle-info') this._chatToggleInfo(); - else if (a === 'open-info') this._chatOpenInfoSheet(); - else if (a === 'close-info') this._chatCloseInfoSheet(); - else if (a === 'back') { this.closeChatThread(); this._navRoute('chat'); } - else if (a === 'new-pill') this._chatScrollBottom(); - return; - } - const seg = t.closest ? t.closest('.ch-seg button[data-filter]') : null; - if (seg) { this._chatFilter = seg.getAttribute('data-filter') || 'open'; this._chatFilterUserSet = true; this.renderChatThreads(); this._chatLayout(); return; } - const cp = t.closest ? t.closest('.gm-copy') : null; - if (cp) { e.stopPropagation(); this._gmCopyChip(cp); return; } - const jobEl = t.closest ? t.closest('[data-job]') : null; - if (jobEl) { e.stopPropagation(); const jid = jobEl.getAttribute('data-job'); if (jid) this._chatOpenJob(jid); return; } - const row = t.closest ? t.closest('.ch-row[data-id]') : null; - if (row) { const id = row.getAttribute('data-id'); this.openChatThread(id); this._navRoute('chat', { name: id }); return; } - }); - // Search input (delegated so it survives list re-renders — the input itself is static). - root.addEventListener('input', (e) => { - const el = e.target; - if (el && el.classList && el.classList.contains('ch-search')) { this._chatQuery = el.value; this.renderChatThreads(); } - }); - // Escape: close the mobile info sheet, else deselect the thread (desktop back-out). - this._chatKeydown = (e) => { - if (e.key !== 'Escape' || this.state.view !== 'chat') return; - if (this._chatSheetOpen) { this._chatCloseInfoSheet(); return; } - if (this._chatSelected) { this.closeChatThread(); this._navRoute('chat'); } - }; - document.addEventListener('keydown', this._chatKeydown); - - this.renderChatThreads(); - this._renderChatConv(null, null, 'ok'); - this._renderChatInfo(null, null); - this._chatLayout(); - return root; - } - - // ---- Layout: grid columns + rail/info collapse + mobile single-column ------ - _chatLayout() { - const root = this._chatRoot; - if (!root) return; - const rail = root.querySelector('.ch-rail'); - const conv = root.querySelector('.ch-conv'); - const info = root.querySelector('.ch-info'); - const scrim = root.querySelector('.ch-scrim'); - const sheet = root.querySelector('.ch-sheet'); - const full = rail && rail.querySelector('.ch-rail-full'); - const mini = rail && rail.querySelector('.ch-rail-mini'); - const mobile = this.state.isMobile; - if (mobile) { - const threadOpen = !!this._chatSelected; - if (rail) rail.style.display = threadOpen ? 'none' : 'flex'; - if (full) full.style.display = 'flex'; - if (mini) mini.style.display = 'none'; - if (conv) conv.style.display = threadOpen ? 'flex' : 'none'; - if (info) info.style.display = 'none'; - root.style.gridTemplateColumns = '1fr'; - if (scrim) scrim.style.display = this._chatSheetOpen ? 'block' : 'none'; - if (sheet) sheet.style.display = this._chatSheetOpen ? 'flex' : 'none'; - return; - } - // desktop: the mobile bottom sheet never applies. - if (scrim) scrim.style.display = 'none'; - if (sheet) sheet.style.display = 'none'; - this._chatSheetOpen = false; - const listOpen = this._chatListOpen; - if (rail) rail.style.display = 'flex'; - if (full) full.style.display = listOpen ? 'flex' : 'none'; - if (mini) mini.style.display = listOpen ? 'none' : 'flex'; - const railW = listOpen ? '300px' : '46px'; - if (conv) conv.style.display = 'flex'; - if (!this._chatSelected) { - if (info) info.style.display = 'none'; - root.style.gridTemplateColumns = railW + ' 1fr'; - } else { - if (info) info.style.display = 'flex'; - root.style.gridTemplateColumns = railW + ' 1fr ' + (this._chatInfoOpen ? '320px' : '44px'); - } - } - - _chatToggleList() { - this._chatListOpen = !this._chatListOpen; - try { localStorage.setItem('gitmoot.chatListOpen', this._chatListOpen ? '1' : '0'); } catch (e) {} - this._chatLayout(); - } - _chatToggleInfo() { - if (this.state.isMobile) { this._chatOpenInfoSheet(); return; } - this._chatInfoOpen = !this._chatInfoOpen; - try { localStorage.setItem('gitmoot.chatInfoOpen', this._chatInfoOpen ? '1' : '0'); } catch (e) {} - this._renderChatInfo((this._chatByID && this._chatByID[this._chatSelected]) || null, this._chatDetailData || null); - this._chatLayout(); - } - _chatOpenInfoSheet() { - if (!this._chatSelected) return; - this._chatSheetOpen = true; - this._renderChatInfo((this._chatByID && this._chatByID[this._chatSelected]) || null, this._chatDetailData || null); - this._chatLayout(); - } - _chatCloseInfoSheet() { - this._chatSheetOpen = false; - this._chatLayout(); - } - - // Re-render everything from cache (used on the mobile<->desktop breakpoint flip). - _chatRerender() { - if (!this._chatRoot) return; - this.renderChatThreads(); - if (this._chatSelected) { - const summary = (this._chatByID && this._chatByID[this._chatSelected]) || { id: this._chatSelected }; - this.renderChatThreadDetail(summary, this._chatDetailData || null, this._chatDetailData ? 'ok' : 'loading'); - } else { - this._renderChatConv(null, null, 'ok'); - this._renderChatInfo(null, null); - } - this._chatLayout(); - } - - // ---- THREAD LIST ----------------------------------------------------------- - fetchChatThreads(isPoll) { - fetch('/api/chat/threads', { cache: 'no-store' }) - .then(r => r.ok ? r.text() : Promise.reject(new Error('HTTP ' + r.status))) - .then(txt => { - if (isPoll && this._chatSig === txt) return; // unchanged — skip the re-render - this._chatSig = txt; - let json = null; try { json = JSON.parse(txt); } catch (e) { json = null; } - this._chatData = Array.isArray(json) ? json : []; - this._chatByID = {}; - this._chatData.forEach(t => { if (t && t.id) this._chatByID[t.id] = t; }); - this._chatLoaded = true; - // Default filter: prefer 'open', but if the user has NOT chosen a filter and - // 'open' matches nothing, fall back to 'all' (avoid the showing-0 trap). - if (!this._chatFilterUserSet && this._chatFilter === 'open') { - const openN = this._chatData.filter(t => t && t.state === 'open').length; - if (openN === 0 && this._chatData.length > 0) this._chatFilter = 'all'; - } - this._updateChatAttn(this._chatData); - this.renderChatThreads(); - this._chatLayout(); - // a pending deep-link (/chat/): open it now the data has landed. - if (this._pendingChatThread) { - if (this._chatByID[this._pendingChatThread]) { - const id = this._pendingChatThread; this._pendingChatThread = null; this.openChatThread(id); - } else if (!isPoll) { - this._pendingChatThread = null; - } - } - }) - .catch(err => { - if (isPoll) return; // keep the current list on a transient poll failure - this._chatLoaded = true; - const list = this._chatRoot && this._chatRoot.querySelector('.ch-list'); - if (list) list.innerHTML = '
    could not load /api/chat/threads (' + this._galaxyEsc(err && err.message) + ')
    '; - }); - } - - renderChatThreads() { - if (!this._chatRoot) return; - const esc = (s) => this._galaxyEsc(s); - const data = Array.isArray(this._chatData) ? this._chatData : []; - const filter = this._chatFilter || 'open'; - const q = (this._chatQuery || '').trim().toLowerCase(); - // sync the segmented control's active button - this._chatRoot.querySelectorAll('.ch-seg button[data-filter]').forEach(b => b.classList.toggle('on', b.getAttribute('data-filter') === filter)); - const filtered = data.filter(t => { - if (filter === 'open' && t.state !== 'open') return false; // 'all' shows everything, incl. archived - if (q) { - const hay = ((t.name || '') + ' ' + (t.repo || '')).toLowerCase(); - if (hay.indexOf(q) < 0) return false; - } - return true; - }); - const count = this._chatRoot.querySelector('.ch-rail-count'); - if (count) count.textContent = data.length ? ('(' + filtered.length + ')') : ''; - const list = this._chatRoot.querySelector('.ch-list'); - if (!list) return; - if (!filtered.length) { - let msg; - if (!this._chatLoaded) msg = 'loading…'; - else if (!data.length) msg = 'No chat threads yet.
    Create one with gitmoot chat create <name> --repo owner/repo'; - else if (q) msg = 'No threads match “' + esc(q) + '”'; - else if (filter === 'open') msg = 'No open threads - try All'; - else msg = 'No threads'; - list.innerHTML = '
    ' + msg + '
    '; - return; - } - const prev = list.scrollTop; - list.innerHTML = filtered.map(t => this._chatThreadCardHtml(t, esc)).join(''); - list.scrollTop = prev; - } - - _chatKindTag(kind, esc) { - if (kind === 'promotion_request') return 'promote'; - if (kind === 'job_result') return 'result'; - if (kind === 'system') return 'ask'; - return ''; - } - - _chatThreadCardHtml(t, esc) { - const isSel = this._chatSelected === t.id; - const arch = t.state === 'archived'; - const dot = ''; - const ment = (t.unreadMentions || 0) > 0 ? '@' + (t.unreadMentions > 99 ? '99+' : t.unreadMentions) + '' : ''; - const time = t.updatedAt ? '' + esc(this._relFromMs(t.updatedAt)) + '' : ''; - const ktag = this._chatKindTag(t.lastKind, esc); - const who = t.lastAuthor ? ('' + esc(t.lastAuthor) + ': ') : ''; - const prev = t.lastSnippet ? (ktag + who + esc(t.lastSnippet)) : 'no messages yet'; - return '
    ' + - '
    ' + dot + '' + esc(t.name || t.id) + '' + ment + time + '
    ' + - '
    ' + prev + '
    ' + - '
    '; - } - - // Refresh just the relative-time labels (rows + message times + Updated) without - // a re-render, so they stay live between the 12s signature-skipped fetches. - refreshChatTimes() { - if (!this._chatRoot) return; - this._chatRoot.querySelectorAll('[data-ts]').forEach(el => { - const ts = +el.getAttribute('data-ts'); - if (ts > 0) el.textContent = this._relFromMs(ts); - }); - } - - // ---- THREAD SELECTION ------------------------------------------------------ - closeChatThread() { - this._chatSelected = null; - this._chatDetailSig = null; - this._chatDetailFetchId = null; - this._chatDetailData = null; - this._chatDetailAnchored = false; - this._chatMsgCount = 0; - this._chatNewCount = 0; - this._chatSheetOpen = false; - this.stopChatThreadPoll(); - this._renderChatConv(null, null, 'ok'); - this._renderChatInfo(null, null); - this.renderChatThreads(); // clear the selected-row highlight - this._chatLayout(); - } - openChatThread(id) { - if (!id) { this.closeChatThread(); return; } - const summary = this._chatByID && this._chatByID[id]; - if (!summary) { this._pendingChatThread = id; return; } // opens after fetchChatThreads - this._chatSelected = id; - this._chatDetailSig = null; // reset the per-thread signature so a switch always renders - this._chatDetailData = null; - this._chatDetailAnchored = false; // a fresh open pins to the newest message - this._chatMsgCount = 0; - this._chatNewCount = 0; - this._chatSheetOpen = false; - this.renderChatThreadDetail(summary, null, 'loading'); - this.renderChatThreads(); // highlight the selected row - this._chatLayout(); - this.fetchChatThread(id, false); - this.startChatThreadPoll(); - } - fetchChatThread(id, isPoll) { - const fid = (this._chatDetailFetchId = id); - fetch('/api/chat/thread?id=' + encodeURIComponent(id), { cache: 'no-store' }) - .then(r => r.ok ? r.text() : Promise.reject(new Error('HTTP ' + r.status))) - .then(txt => { - if (this._chatDetailFetchId !== fid || this._chatSelected !== id) return; // superseded - if (isPoll && this._chatDetailSig === txt) return; // unchanged — skip - this._chatDetailSig = txt; - let json = null; try { json = JSON.parse(txt); } catch (e) { json = null; } - this.renderChatThreadDetail(json || (this._chatByID && this._chatByID[id]) || { id: id }, json, 'ok'); - }) - .catch(() => { - if (isPoll || this._chatDetailFetchId !== fid || this._chatSelected !== id) return; - const summary = (this._chatByID && this._chatByID[id]) || { id: id }; - this.renderChatThreadDetail(summary, null, 'error'); - }); - } - - // Render both the center conversation and the right details from one thread. - renderChatThreadDetail(summary, detail, status) { - if (detail) this._chatDetailData = detail; - this._renderChatConv(summary, detail, status); - this._renderChatInfo(summary, detail); - this._chatLayout(); - } - - // ---- CENTER: conversation -------------------------------------------------- - _renderChatConv(summary, detail, status) { - const conv = this._chatRoot && this._chatRoot.querySelector('.ch-conv'); - if (!conv) return; - const esc = (s) => this._galaxyEsc(s); - if (!this._chatSelected) { - const ic = ""; - conv.innerHTML = '
    ' + ic + '
    Select a thread
    Pick a conversation from the left to read its messages.
    '; - return; - } - // Preserve reading position across the 12s live-detail poll's innerHTML replace. - const oldBody = conv.querySelector('.cd-body'); - const hadBody = !!oldBody; - const prevTop = oldBody ? oldBody.scrollTop : 0; - const wasAtBottom = oldBody ? (oldBody.scrollHeight - oldBody.scrollTop - oldBody.clientHeight) <= 24 : false; - - const name = (detail && detail.name) || (summary && summary.name) || (summary && summary.id) || ''; - const repo = (detail && detail.repo) || (summary && summary.repo) || ''; - const state = (detail && detail.state) || (summary && summary.state) || 'open'; - const arch = state === 'archived'; - const parts = (detail && Array.isArray(detail.participants)) ? detail.participants : ((summary && Array.isArray(summary.participants)) ? summary.participants : []); - - const msgs = (detail && Array.isArray(detail.messages)) ? detail.messages.slice() : null; - // @mention coloring context: human authors -> amber; everyone else -> cyan. - const humans = {}; - if (msgs) msgs.forEach(m => { if (m && m.authorKind === 'human' && m.authorName) humans[m.authorName] = 1; }); - const mctx = { humans: humans }; - - let bodyHtml; - if (msgs && msgs.length) { - // Order by the server's authoritative per-thread seq; tsMs then id break ties. - msgs.sort((a, b) => (a.seq || 0) - (b.seq || 0) || (a.tsMs || 0) - (b.tsMs || 0) || String(a.id || '').localeCompare(String(b.id || ''))); - bodyHtml = msgs.map(m => this._chatMessageHtml(m, esc, mctx)).join(''); - } else if (status === 'loading') { - bodyHtml = '
    loading…
    '; - } else if (status === 'error') { - bodyHtml = '
    could not load this thread
    '; - } else { - bodyHtml = '
    No messages in this thread yet.
    '; - } - - // "N new" delta: if the tail grew while the reader was scrolled up, count it. - const msgCount = (msgs && msgs.length) || 0; - const prevCount = this._chatMsgCount || 0; - if (hadBody && this._chatDetailAnchored && !wasAtBottom && msgCount > prevCount) { - this._chatNewCount = (this._chatNewCount || 0) + (msgCount - prevCount); - } - this._chatMsgCount = msgCount; - const newN = this._chatNewCount || 0; - - const mobile = this.state.isMobile; - // Header dot mirrors the thread list's state colors (green open / grey archived) — - // the pulsing .ch-live dot overstated activity on idle open threads (review catch). - const liveDot = ''; - const infoIcon = ""; - let header; - if (mobile) { - const memb = parts.length ? (parts.length + ' member' + (parts.length === 1 ? '' : 's')) : ''; - const sub = [memb, esc(repo)].filter(Boolean).join(' · '); - header = '
    ' + - '' + - liveDot + - '
    ' + esc(name) + '
    ' + (sub ? '
    ' + sub + '
    ' : '') + '
    ' + - '' + - '
    '; - } else { - header = '
    ' + - liveDot + - '' + esc(name) + '' + - '' + esc(state) + '' + - (repo ? '' + esc(repo) + '' : '') + - '
    ' + - '' + - '
    '; - } - const newPill = ''; - const termIcon = ""; - const sendCmd = 'gitmoot chat send ' + (this._chatSelected || '') + ' "…"'; - const composer = '
    ' + - '
    ' + - '' + termIcon + '' + - 'Reply from your terminal…' + - '' + - '
    ' + - (mobile ? '' : '
    copies ' + esc(sendCmd) + '
    ') + - '
    '; - - conv.innerHTML = header + '
    ' + bodyHtml + '
    ' + newPill + composer; - - const newBody = conv.querySelector('.cd-body'); - if (newBody) { - newBody.addEventListener('scroll', this._chatOnScroll); - const hasMsgs = !!(msgs && msgs.length); - if (hasMsgs && (!this._chatDetailAnchored || wasAtBottom || !hadBody)) { - this._chatDetailAnchored = true; - this._chatNewCount = 0; - this._pinChatDetailBottom(newBody, this._chatSelected); // pin to the newest message - const np = conv.querySelector('.ch-newpill'); if (np) np.style.display = 'none'; - } else { - newBody.scrollTop = prevTop; // preserve the reader's position - } - } - } - - // When the reader scrolls back to the bottom, clear the "N new" pill. - _chatOnScroll = (e) => { - const el = e.target; - if (!el) return; - const dist = el.scrollHeight - el.scrollTop - el.clientHeight; - if (dist <= 24 && this._chatNewCount) { - this._chatNewCount = 0; - const np = this._chatRoot && this._chatRoot.querySelector('.ch-newpill'); - if (np) np.style.display = 'none'; - } - }; - _chatScrollBottom() { - const b = this._chatRoot && this._chatRoot.querySelector('.ch-conv .cd-body'); - if (b) b.scrollTop = b.scrollHeight; - this._chatNewCount = 0; - const np = this._chatRoot && this._chatRoot.querySelector('.ch-newpill'); - if (np) np.style.display = 'none'; - } - - // Pin the conversation body to its newest message; re-pin once webfonts / late - // layout settle. Guarded so a thread switch or a superseding render cancels it. - _pinChatDetailBottom(body, id) { - if (!body) return; - body.scrollTop = body.scrollHeight; - const again = () => { - if (this._chatSelected !== id) return; - const cur = this._chatRoot && this._chatRoot.querySelector('.ch-conv .cd-body'); - if (cur === body) body.scrollTop = body.scrollHeight; - }; - try { requestAnimationFrame(again); } catch (e) {} - try { if (document.fonts && document.fonts.ready) document.fonts.ready.then(again); } catch (e) {} - } - - // Stable per-author color: system amber; everyone else hashed into a palette so - // each agent/human keeps a distinct monogram + name hue (the design's per-seat color). - _chatAuthorColor(kind, name) { - if (kind === 'system') return '#e0af68'; - const pal = ['#7aa2f7', '#bb9af7', '#7dcfff', '#9ece6a', '#e0af68', '#f7768e', '#2ac3de', '#b4f9f8', '#c0caf5']; - const s = String(name || ''); - let h = 0; - for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0; - return pal[h % pal.length]; - } - _chatRGBA(hex, a) { - let h = String(hex || '').replace('#', ''); - if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2]; - const n = parseInt(h || '0', 16); - return 'rgba(' + ((n >> 16) & 255) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')'; - } - _chatAvatarHtml(name, kind, size) { - const col = this._chatAuthorColor(kind, name); - const m = (name && name[0] ? name[0] : (kind === 'system' ? 'S' : '?')).toUpperCase(); - const sz = size || 34; - const style = 'width:' + sz + 'px;height:' + sz + 'px;font-size:' + Math.round(sz * 0.37) + 'px;color:' + col + ';background:' + this._chatRGBA(col, 0.16) + ';border:1px solid ' + this._chatRGBA(col, 0.32); - return '
    ' + this._galaxyEsc(m) + '
    '; - } - _chatKindBadge(kind, esc) { - if (kind === 'system') return 'ask-gate'; - if (kind === 'job_result') return 'job result'; - if (kind === 'promotion_request') return 'promotion'; - return ''; - } - - // Render an UNTRUSTED chat message body (agent- or human-authored) as SAFE HTML. - // Design contract: escape-first, then apply a strict markdown whitelist to the - // ALREADY-ESCAPED text. Because escaping runs before any transform, the ONLY - // '<'/'>' in the result are the literal tags this function emits — never anything - // derived from the input — so the output is XSS-safe by construction. Supported: - // fenced ``` code, > blockquotes, - / * lists, **bold**, `inline code`, @mentions, - // and line breaks. Deliberately NOT supported: raw HTML, images, headings, links - // (URLs stay INERT plain text — no linkification — to avoid a phishing surface). - _chatRenderMarkdown(raw, ctx) { - ctx = ctx || {}; - const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => c === '&' ? '&' : c === '<' ? '<' : c === '>' ? '>' : c === '"' ? '"' : '''); - let src = String(raw == null ? '' : raw).replace(/\r\n?/g, '\n'); - const MAX_BODY = 32768; - let truncated = false; - if (src.length > MAX_BODY) { src = src.slice(0, MAX_BODY); truncated = true; } - // Inline transforms run on ALREADY html-escaped text, so captured groups can only - // contain escaped chars and can never break out of a tag or attribute. We split on - // inline-code spans and apply **bold** + @mentions only OUTSIDE code. - const mention = (t) => t.replace(/@([A-Za-z0-9][A-Za-z0-9_.\-]*)/g, (mm, nm) => this._chatMentionChip(nm, ctx)); - const inline = (t) => { - return t.split(/(`[^`\n]+`)/).map((seg) => { - if (seg.length > 1 && seg.charCodeAt(0) === 96 && seg.charCodeAt(seg.length - 1) === 96) { - return '' + seg.slice(1, -1) + ''; - } - return mention(seg.replace(/\*\*([^*\n]+)\*\*/g, '$1')); - }).join(''); - }; - const lines = esc(src).split('\n'); - const out = []; - let i = 0; - const n = lines.length; - const isFence = (l) => /^\s*```/.test(l); - const isQuote = (l) => /^\s*>\s?/.test(l); // escaped '>' is '>' - const isBullet = (l) => /^\s*[-*]\s+/.test(l); - while (i < n) { - const line = lines[i]; - if (isFence(line)) { - const buf = []; - i++; - while (i < n && !/^\s*```\s*$/.test(lines[i])) { buf.push(lines[i]); i++; } - if (i < n) i++; // consume the closing fence - out.push('
    ' + buf.join('\n') + '
    '); - continue; - } - if (isQuote(line)) { - const buf = []; - while (i < n && isQuote(lines[i])) { buf.push(inline(lines[i].replace(/^\s*>\s?/, ''))); i++; } - out.push('
    ' + buf.join('
    ') + '
    '); - continue; - } - if (isBullet(line)) { - const items = []; - while (i < n && isBullet(lines[i])) { items.push('
  • ' + inline(lines[i].replace(/^\s*[-*]\s+/, '')) + '
  • '); i++; } - out.push('
      ' + items.join('') + '
    '); - continue; - } - const para = []; - while (i < n) { - const l = lines[i]; - if (isFence(l) || isQuote(l) || isBullet(l)) break; - if (l.trim() === '') { i++; break; } - para.push(inline(l)); - i++; - } - if (para.length) out.push('
    ' + para.join('
    ') + '
    '); - } - if (truncated) out.push('
    … (message truncated)
    '); - return out.join(''); - } - - // A single @mention chip. `nm` comes from ALREADY-ESCAPED text (alphanumerics + - // _.-), so it is inert; amber when the name authored a human message in this - // thread, cyan otherwise. - _chatMentionChip(nm, ctx) { - ctx = ctx || {}; - const isHuman = ctx.humans && ctx.humans[nm]; - return '@' + nm + ''; - } - - _chatMessageHtml(m, esc, ctx) { - const kind = m.kind || 'chat'; - const ak = m.authorKind || 'agent'; - const author = ak === 'system' ? 'system' : (m.authorName || 'unknown'); - const col = this._chatAuthorColor(ak, author); - const time = m.tsMs ? '' + esc(this._relFromMs(m.tsMs)) + '' : ''; - const youPill = ak === 'human' ? 'you' : ''; - const badge = this._chatKindBadge(kind, esc); - const av = this._chatAvatarHtml(author, ak, 34); - const contCls = kind === 'system' ? 'cd-cont gate' : (kind === 'job_result' ? 'cd-cont code' : 'cd-cont'); - const askHead = kind === 'system' ? '
    ⚠ ask-gate - awaiting an answer
    ' : ''; - let promo = ''; - if (kind === 'promotion_request' && m.promotedJobId) { - promo = '
    → promoted job ' + esc(m.promotedJobId) + '
    '; - } - const refs = Array.isArray(m.refs) ? m.refs : []; - const refsHtml = refs.length ? ('
    ' + refs.map(r => this._chatRefChipHtml(r, esc)).join('') + '
    ') : ''; - const rowCls = 'cd-msg' + (ak === 'human' ? ' you' : '') + (kind === 'system' ? ' system' : (kind === 'job_result' ? ' result' : '')); - return '
    ' + - av + - '
    ' + - '
    ' + esc(author) + '' + youPill + badge + time + '
    ' + - '
    ' + askHead + this._chatRenderMarkdown(m.body || '', ctx) + '
    ' + - promo + refsHtml + - '
    ' + - '
    '; - } - - _chatRefChipHtml(r, esc) { - if (!r || !r.kind) return ''; - const label = esc(r.kind) + (r.id ? ' ' + esc(r.id) : ''); - const cls = r.kind === 'job' ? ' job' : (r.kind === 'pr' ? ' pr' : ''); - if (r.kind === 'job' && r.id) { - return '◆ ' + label + ''; - } - const url = this._galaxySafeUrl(r.url); - if (url) { - return '' + label + ' ↗'; - } - return '' + label + ''; - } - - // ---- RIGHT: thread details (desktop pane + mobile bottom sheet) ------------- - _renderChatInfo(summary, detail) { - if (!this._chatRoot) return; - const info = this._chatRoot.querySelector('.ch-info'); - const sheet = this._chatRoot.querySelector('.ch-sheet'); - const inner = this._chatSelected ? this._chatInfoInnerHtml(summary, detail) : ''; - if (info) { - if (!this._chatSelected) { - info.classList.remove('mini'); - info.innerHTML = ''; - } else if (!this._chatInfoOpen && !this.state.isMobile) { - info.classList.add('mini'); - info.innerHTML = ''; - } else { - info.classList.remove('mini'); - info.innerHTML = '
    THREAD DETAILS
    ' + inner + '
    '; - } - } - if (sheet && this._chatSheetOpen) { - sheet.innerHTML = '
    THREAD DETAILS
    ' + inner + '
    '; - } - } - - _chatInfoInnerHtml(summary, detail) { - const esc = (s) => this._galaxyEsc(s); - const s = detail || summary || {}; - const state = s.state || 'open'; - const arch = state === 'archived'; - const repo = s.repo || ''; - const createdBy = s.createdBy || ''; - const updated = s.updatedAt || (summary && summary.updatedAt) || 0; - const count = (detail && Array.isArray(detail.messages)) ? detail.messages.length : (s.messageCount || (summary && summary.messageCount) || 0); - const kv = (k, v) => '
    ' + k + '' + v + '
    '; - const rows = [ - kv('State', '' + esc(state) + ''), - repo ? kv('Repo', '' + esc(repo) + '') : '', - createdBy ? kv('Created by', '' + esc(createdBy) + '') : '', - updated ? kv('Updated', '' + esc(this._relFromMs(updated)) + '') : '', - kv('Messages', '' + count + '') - ].join(''); - - // MEMBERS — participants[] with per-member activity derived from messages[]. - const parts = (detail && Array.isArray(detail.participants)) ? detail.participants : ((summary && Array.isArray(summary.participants)) ? summary.participants : []); - const msgs = (detail && Array.isArray(detail.messages)) ? detail.messages : []; - const kindByName = {}; const cntByName = {}; const lastByName = {}; - msgs.forEach(m => { - if (!m) return; - const nm = (m.authorKind === 'system') ? 'system' : (m.authorName || ''); - if (!nm) return; - kindByName[nm] = m.authorKind || 'agent'; - cntByName[nm] = (cntByName[nm] || 0) + 1; - if ((m.tsMs || 0) > (lastByName[nm] || 0)) lastByName[nm] = m.tsMs || 0; - }); - const memHtml = parts.length ? parts.map(p => { - const kind = kindByName[p] || 'agent'; - const av = this._chatAvatarHtml(p, kind, 30); - const cnt = cntByName[p] || 0; - const meta = detail - ? (cnt + ' msg' + (cnt === 1 ? '' : 's') + (lastByName[p] ? ' · active ' + this._relFromMs(lastByName[p]) : ' · no activity')) - : '…'; - return '
    ' + av + '
    ' + esc(p) + '' + esc(kind) + '
    ' + esc(meta) + '
    '; - }).join('') : '
    No members enrolled
    '; - - // LINKED — deduped rollup of every message's refs + promoted job ids. - const linked = this._chatLinkedChips(detail, esc); - const linkedHtml = linked ? linked : '
    No linked entities
    '; - - // SEND A MESSAGE — copy the chat send command (archive/reopen live on the CLI). - const sendCmd = 'gitmoot chat send ' + (this._chatSelected || '') + ' "…"'; - const send = '
    ' + esc(sendCmd) + '
    '; - - return '
    ' + rows + '
    ' + - '
    MEMBERS
    ' + memHtml + '
    ' + - '
    LINKED
    ' + linkedHtml + '
    ' + - '
    SEND A MESSAGE
    ' + send + '
    '; - } - - _chatLinkedChips(detail, esc) { - if (!detail || !Array.isArray(detail.messages)) return ''; - const seen = {}; const chips = []; - detail.messages.forEach(m => { - if (!m) return; - // Key promoted jobs with the SAME shape as a job ref (kind:id:url, url empty) - // so a job that is both promoted and referenced collapses to one chip. - if (m.promotedJobId && !seen['job:' + m.promotedJobId + ':']) { seen['job:' + m.promotedJobId + ':'] = 1; chips.push(this._chatRefChipHtml({ kind: 'job', id: m.promotedJobId }, esc)); } - (Array.isArray(m.refs) ? m.refs : []).forEach(r => { - if (!r || !r.kind) return; - const key = r.kind + ':' + (r.id || '') + ':' + (r.url || ''); - if (seen[key]) return; - seen[key] = 1; - chips.push(this._chatRefChipHtml(r, esc)); - }); - }); - return chips.join(''); - } - - // Deep-link a job chip into the Jobs view and open that job's detail rail. - _chatOpenJob(id) { - if (!id) return; - // Close the mobile info sheet before leaving, or it re-appears over the - // conversation when navigating back to Chat (review catch). - if (this._chatSheetOpen) this._chatCloseInfoSheet(); - this._pendingJobDetail = id; - this.showJobs(); - } - _overlayLeft() { return this.state.isMobile ? '0' : '216px'; } _overlayBottom() { return this.state.isMobile ? 'calc(60px + env(safe-area-inset-bottom))' : '0'; } _dockOverlay(el) { @@ -12140,7 +7953,7 @@ el.style.bottom = this._overlayBottom(); } _redockOverlays() { - [this._overviewRoot, this._tasksRoot, this._galaxyRoot, this._workflowRoot, this._jobsRoot, this._agentsRoot, this._orgRoot, this._chartsRoot, this._healthRoot, this._configRoot, this._learningRoot, this._pipelinesRoot, this._chatRoot] + [this._overviewRoot, this._tasksRoot, this._galaxyRoot, this._workflowRoot, this._jobsRoot, this._agentsRoot, this._orgRoot, this._chartsRoot, this._healthRoot, this._configRoot, this._learningRoot, this._pipelinesRoot] .forEach(r => this._dockOverlay(r)); } @@ -12740,7 +8553,6 @@ const isTasks = view === 'tasks'; const isGraph = view === 'graph'; const isGalaxy = view === 'galaxy'; - const isBrain = view === 'brain'; const isJobs = view === 'jobs'; const isAgents = view === 'agents'; const isOrg = view === 'org'; @@ -12750,7 +8562,6 @@ const isAttention = view === 'attention'; const isLearning = view === 'learning'; const isPipelines = view === 'pipelines'; - const isChat = view === 'chat'; const isWorkflows = view === 'workflows'; // shared nav-item base; active items pick up the green highlight const navBase = { display: 'flex', alignItems: 'center', gap: '11px', padding: '9px 11px', borderRadius: '9px', fontSize: '13.5px', fontWeight: 500, cursor: 'pointer', marginTop: '2px' }; @@ -12763,11 +8574,9 @@ const overviewNavStyle = { ...navActive(isOverview), marginTop: 0, position: 'relative' }; const tasksNavStyle = { ...navActive(isTasks), position: 'relative' }; const galaxyNavStyle = { ...navActive(isGalaxy), position: 'relative' }; - const brainNavStyle = { ...navActive(isBrain), position: 'relative' }; const jobsNavStyle = { ...navActive(isJobs), position: 'relative' }; const pipelinesNavStyle = { ...navActive(isPipelines), position: 'relative' }; const workflowsNavStyle = { ...navActive(isWorkflows), position: 'relative' }; - const chatNavStyle = { ...navActive(isChat), position: 'relative' }; const agentsNavStyle = { ...navActive(isAgents), position: 'relative' }; const orgNavStyle = { ...navActive(isOrg), position: 'relative' }; const chartsNavStyle = { ...navActive(isCharts), position: 'relative' }; @@ -12778,7 +8587,6 @@ // Nav "needs you" dot: the right-aligned rail dot is now an amber pip that lights // when a section needs a human (NOT a you-are-here marker — the active pill shows that). const needsDot = (on, color) => { const c=color||'#e0af68'; return { width: '6px', height: '6px', borderRadius: '50%', flex: 'none', background: on ? c : 'transparent', boxShadow: on ? '0 0 8px '+c : 'none' }; }; - const chatAttn = !!this.state.chatAttn; const healthAttn = !!this.state.healthAttn; const learningAttn = !!this.state.learningAttn; const pipelinesAttn = !!this.state.pipelinesAttn; @@ -12829,17 +8637,16 @@ // ---- top-bar breadcrumb: "section › entity", or "group › section" when no entity ---- // Graph keeps its repo › run-title (and the run-state dot); every other view shows - // its section + a cheaply-available selected entity (chat thread / pipeline / agent), + // its section + a cheaply-available selected entity (pipeline / agent), // falling back to its nav group + section name. - const NAV_GROUP = { overview: 'work', tasks: 'work', graph: 'work', jobs: 'work', pipelines: 'work', workflows: 'work', agents: 'fleet', org: 'fleet', chat: 'fleet', brain: 'insight', galaxy: 'insight', charts: 'insight', learning: 'insight', attention: 'system', health: 'system', config: 'system' }; - const SECT = { overview: 'overview', tasks: 'tasks', graph: 'graph', jobs: 'jobs', pipelines: 'pipelines', workflows: 'workflows', agents: 'agents', org: 'org', chat: 'chat', brain: 'brain', galaxy: 'galaxy', charts: 'charts', learning: 'learning', attention: 'attention', health: 'health', config: 'config' }; + const NAV_GROUP = { overview: 'work', tasks: 'work', graph: 'work', jobs: 'work', pipelines: 'work', workflows: 'work', agents: 'fleet', org: 'fleet', galaxy: 'insight', charts: 'insight', learning: 'insight', attention: 'system', health: 'system', config: 'system' }; + const SECT = { overview: 'overview', tasks: 'tasks', graph: 'graph', jobs: 'jobs', pipelines: 'pipelines', workflows: 'workflows', agents: 'agents', org: 'org', galaxy: 'galaxy', charts: 'charts', learning: 'learning', attention: 'attention', health: 'health', config: 'config' }; let crumbRoot, crumbLeaf, crumbShowDot = isOrg; if (isGraph) { crumbRoot = activeRun.repo || 'graph'; crumbLeaf = activeRun.title || 'run'; crumbShowDot = true; } else { let entity = ''; - if (isChat && this._chatSelected) { const th = this._chatByID && this._chatByID[this._chatSelected]; entity = (th && th.name) || this._chatSelected; } - else if (isPipelines && this._plDetailName) entity = this._plDetailName; + if (isPipelines && this._plDetailName) entity = this._plDetailName; else if (isAgents && this._agentsSelected) entity = this._agentsSelected; else if (isJobs && this._jobsFacetAgent) entity = this._jobsFacetAgent; else if (isWorkflows && this._workflowLabel) entity = this._workflowLabel; @@ -12856,12 +8663,12 @@ onDown: this.onDown, onMove: this.onMove, onUp: this.onUp, onWheel: this.onWheel, zoomIn: this.zoomIn, zoomOut: this.zoomOut, fit: this.fit, toggleRuns: this.toggleRuns, runsTabVisible, - showGraph: this.showGraph, showOverview: this.showOverview, showTasks: this.showTasks, showBrain: this.showBrain, showGalaxy: this.showGalaxy, + showGraph: this.showGraph, showOverview: this.showOverview, showTasks: this.showTasks, showGalaxy: this.showGalaxy, showJobs: this.showJobs, showAgents: this.showAgents, showOrg: this.showOrg, showCharts: this.showCharts, showHealth: this.showHealth, showConfig: this.showConfig, showLearning: this.showLearning, - showPipelines: this.showPipelines, showWorkflows: this.showWorkflows, showChat: this.showChat, showAttention: this.showAttention, - graphNavStyle, overviewNavStyle, tasksNavStyle, brainNavStyle, galaxyNavStyle, jobsNavStyle, pipelinesNavStyle, workflowsNavStyle, chatNavStyle, agentsNavStyle, orgNavStyle, chartsNavStyle, healthNavStyle, configNavStyle, attentionNavStyle, learningNavStyle, - graphNavDotStyle: needsDot(false), brainNavDotStyle: needsDot(false), galaxyNavDotStyle: needsDot(false), + showPipelines: this.showPipelines, showWorkflows: this.showWorkflows, showAttention: this.showAttention, + graphNavStyle, overviewNavStyle, tasksNavStyle, galaxyNavStyle, jobsNavStyle, pipelinesNavStyle, workflowsNavStyle, agentsNavStyle, orgNavStyle, chartsNavStyle, healthNavStyle, configNavStyle, attentionNavStyle, learningNavStyle, + graphNavDotStyle: needsDot(false), galaxyNavDotStyle: needsDot(false), jobsNavDotStyle: needsDot(false), agentsNavDotStyle: needsDot(false), orgNavDotStyle: needsDot(false), chartsNavDotStyle: needsDot(false), healthNavDotStyle: needsDot(healthAttn && !isHealth), configNavDotStyle: needsDot(false), @@ -12869,26 +8676,23 @@ tasksNavDotStyle: needsDot(tasksAttn && !isTasks), learningNavDotStyle: needsDot(false), pipelinesNavDotStyle: needsDot(pipelinesAttn && !isPipelines), workflowsNavDotStyle: needsDot(workflowsAttn && !isWorkflows), - chatNavDotStyle: needsDot(false), - chatTabAttnStyle: tabPip(chatAttn), tabPipesAttnStyle: tabPip(pipelinesAttn), tabHealthAttnStyle: tabPip(healthAttn), tabAttnAttnStyle: tabPip(attnAttn, '#f7768e'), tabTasksAttnStyle: tabPip(tasksAttn && !isTasks), tabWorkflowsAttnStyle: tabPip(workflowsAttn && !isWorkflows), tabMoreAttnStyle: tabPip(pipelinesAttn || healthAttn || attnAttn), moreSheetVisible, closeMoreSheet: this._navCloseMore, showMore: this._navOpenMore, - showOverviewFromMore: this._navMoreOverview, showTasksFromMore: this._navMoreTasks, showWorkflowsFromMore: this._navMoreWorkflows, showJobsFromMore: this._navMoreJobs, showBrainFromMore: this._navMoreBrain, + showOverviewFromMore: this._navMoreOverview, showTasksFromMore: this._navMoreTasks, showWorkflowsFromMore: this._navMoreWorkflows, showJobsFromMore: this._navMoreJobs, showGalaxyFromMore: this._navMoreGalaxy, showChartsFromMore: this._navMoreCharts, showLearningFromMore: this._navMoreLearning, - showConfigFromMore: this._navMoreConfig, showPipelinesFromMore: this._navMorePipelines, showChatFromMore: this._navMoreChat, + showConfigFromMore: this._navMoreConfig, showPipelinesFromMore: this._navMorePipelines, showAgentsFromMore: this._navMoreAgents, showOrgFromMore: this._navMoreOrg, showAttentionFromMore: this._navMoreAttention, showHealthFromMore: this._navMoreHealth, moreLearnDotStyle: needsDot(learningAttn), daemonText, daemonTextStyle, liveWord, liveBadgeStyle, liveDotStyle, buildSkewVisible, buildSkewServer, buildSkewDaemon, dismissBuildSkew: this._dismissBuildSkew, railStyle, tabBarStyle, tabLabelStyle, mobileMenuStyle, - tabGraphStyle: tabStyle(isGraph), tabOverviewStyle: tabStyle(isOverview), tabTasksStyle: { ...tabStyle(isTasks), position: 'relative' }, tabJobsStyle: tabStyle(isJobs), tabWorkflowsStyle: { ...tabStyle(isWorkflows), position: 'relative' }, tabAgentsStyle: tabStyle(isAgents), tabBrainStyle: tabStyle(isBrain), + tabGraphStyle: tabStyle(isGraph), tabOverviewStyle: tabStyle(isOverview), tabTasksStyle: { ...tabStyle(isTasks), position: 'relative' }, tabJobsStyle: tabStyle(isJobs), tabWorkflowsStyle: { ...tabStyle(isWorkflows), position: 'relative' }, tabAgentsStyle: tabStyle(isAgents), tabHealthStyle: { ...tabStyle(isHealth), position: 'relative' }, tabAttentionStyle: { ...tabStyle(isAttention), position: 'relative' }, tabPipelinesStyle: { ...tabStyle(isPipelines), position: 'relative' }, - tabChatStyle: { ...tabStyle(isChat), position: 'relative' }, - tabMoreStyle: { ...tabStyle(isGraph || isJobs || isGalaxy || isCharts || isLearning || isConfig || isPipelines || isChat || isAgents || isOrg || isAttention || isHealth), position: 'relative' }, + tabMoreStyle: { ...tabStyle(isGraph || isJobs || isGalaxy || isCharts || isLearning || isConfig || isPipelines || isAgents || isOrg || isAttention || isHealth), position: 'relative' }, crumbRepoStyle, crumbSepStyle, liveTextStyle, detailAsideStyle, zoomCtrlStyle, footerStyle, crumbRepo: crumbRoot, crumbTitle: crumbLeaf, crumbDotStyle: crumbShowDot ? { width: '8px', height: '8px', borderRadius: '50%', flex: 'none', background: isOrg ? '#bb9af7' : crumbCol.c, boxShadow: isOrg ? '0 0 8px rgba(187,154,247,.6)' : (activeRun.state === 'running' ? '0 0 8px ' + crumbCol.g : 'none'), animation: (!isOrg && activeRun.state === 'running') ? 'dotpulse 1.4s ease-in-out infinite' : 'none' } : { display: 'none' },