@sanqianx/project-knowledge 5.3.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "project-knowledge",
12
- "version": "5.3.0",
12
+ "version": "5.3.1",
13
13
  "source": "./plugins/project-knowledge",
14
14
  "description": "Search durable project decisions and implementation history through MCP."
15
15
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [5.3.1] - 2026-11-25
4
+
5
+ - AI 团队新增单仓库维护页。成员可调用本机登记的工具,按目标分支提交、每日北京时间或手动触发检查、格式整理和文档更新。
6
+ - 同仓任务排队复用独立 Git worktree。开发占用、工作区有改动或运行中断时保留现场。页面记录检查、修复、复查和候选提交,支持经授权的普通快进推送。
7
+ - 固定 Workflow `0.2.3`,嵌入页面跟随知识库的主题和窄屏布局。
8
+
3
9
  ## [5.2.1] - 2026-11-22
4
10
 
5
11
  - 工作流模块升级至 `0.2.1`。AI 团队页按新交互设计重构:任务工作台(列表搜索、团队计划的依赖工作项与真实成员、最新意见在前代码审查、验收依据含工具版本/命令摘要/退出码/快照与收据时效)、团队设置(真实配置编辑带版本冲突保护)与只读接入诊断;全部数据来自服务端,无示例内容。程序收据新增脱敏命令摘要;能力声明如实标记审查编排可用。
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const path = require('node:path');
5
+ const { createAiTeamUiFixture, cliOptions } = require('./helpers/ai-team-ui-fixture');
6
+ const { launchCdpBrowser, waitFor } = require('./helpers/cdp-browser');
7
+ const { findChrome } = require('./helpers/find-chrome');
8
+
9
+ async function main() {
10
+ const options = cliOptions({ test: true, defaultMaintenance: true });
11
+ // Keep Windows known-folder discovery intact for Chrome. The browser's
12
+ // explicit user-data-dir still belongs to this fixture.
13
+ const browserEnv = { ...process.env };
14
+ const fixture = await createAiTeamUiFixture(options);
15
+ let browser;
16
+ try {
17
+ const disallowed = await fetch(fixture.address + '/api/integrations/status');
18
+ assert.equal(disallowed.status, 403, 'the preview never inspects daily client integrations');
19
+ browser = await launchCdpBrowser({
20
+ chrome: findChrome(), profileDir: fixture.browserProfile, url: fixture.address,
21
+ launchAttempts: 1, width: 1440, height: 940, env: browserEnv,
22
+ });
23
+ const page = expression => browser.evaluate(expression);
24
+ const workflow = expression => page(
25
+ '(() => { const doc = document.querySelector("#workflowFrame")?.contentDocument; if (!doc) return null; return (' + expression + '); })()'
26
+ );
27
+ const click = selector => workflow('doc.querySelector(' + JSON.stringify(selector) + ').click()');
28
+ const has = (selector, text) => workflow('doc.querySelector(' + JSON.stringify(selector) + ')?.textContent.includes(' + JSON.stringify(text) + ')');
29
+ const field = (form, name, value) => workflow(
30
+ '(() => { const field = doc.getElementById(' + JSON.stringify(form) + ').elements.namedItem(' + JSON.stringify(name) + '); field.value = ' + JSON.stringify(value) + '; return field.value; })()'
31
+ );
32
+ const shot = filename => browser.screenshot(path.join(options.dataDir, filename));
33
+
34
+ await browser.setViewport(1440, 940);
35
+ await page('document.querySelector(\'nav [data-view="team"]\').click()');
36
+ if (options.emptyTeam) {
37
+ assert.equal((await fixture.call('team')).status, 'empty');
38
+ await waitFor(() => has('#heading', '任务工作台'), 'AI team frame in a newly installed knowledge base');
39
+ await click('#navSettings');
40
+ await waitFor(() => has('#teamForm', '创建团队'), 'first-team creation form');
41
+ await shot('create-team.png');
42
+ await field('teamForm', 'name', '首次建队验收');
43
+ await click('#teamForm button[type="submit"]');
44
+ await waitFor(() => has('#teamName', '首次建队验收'), 'team saved through Workflow');
45
+ assert.equal((await fixture.call('team')).team.name, '首次建队验收');
46
+ assert.equal(await workflow('Boolean(doc.getElementById("teamForm"))'), false);
47
+ const duplicate = await fetch(fixture.address + '/api/workflow/team', {
48
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
49
+ body: JSON.stringify({ requestId: 'duplicate-team-check', name: '第二团队' }),
50
+ });
51
+ assert.equal(duplicate.status, 409, 'the current Workflow contract rejects a second default team');
52
+ assert.deepEqual(browser.exceptions, []);
53
+ console.log('ai-team-ui-integration-test PASS (empty team UI, real creation, existing team view, duplicate rejected)');
54
+ return;
55
+ }
56
+ await waitFor(() => has('#taskList', fixture.task.title), 'render a task through the real Workflow proxy');
57
+ assert.equal(await workflow('doc.body.dataset.embed'), '1');
58
+ assert.equal(await has('#teamName', '维护团队'), true);
59
+ await click('#taskList [data-task]');
60
+ await waitFor(() => workflow('doc.querySelectorAll("#detail .subnav [data-tab]").length === 3'), 'task detail and Review tabs');
61
+ await shot('tasks.png');
62
+
63
+ await click('#start');
64
+ assert.equal(await workflow('doc.getElementById("promptDialog").open'), true);
65
+ await click('#closeDialog');
66
+ await click('#navSettings');
67
+ await waitFor(() => workflow('Boolean(doc.getElementById("projectForm"))'), 'project editor over core project directory');
68
+ assert.equal(await workflow('doc.querySelector("#projectPicker option").textContent'), '示例代码仓库');
69
+ assert.equal(await workflow('doc.getElementById("projectForm").elements.autoDispatch.checked'), true);
70
+ await shot('settings.png');
71
+
72
+ await click('#addMember');
73
+ await waitFor(() => has('#memberForm', '代码规范'), 'memory directory in member editor');
74
+ await field('memberForm', 'name', '验证维护成员');
75
+ await field('memberForm', 'instructions', '先检查文档,再记录结果。');
76
+ await workflow('doc.querySelector(\'#memberForm input[value="group-docs"]\').checked = true');
77
+ await shot('member.png');
78
+ await click('#memberForm button[type="submit"]');
79
+ await waitFor(() => has('#memberList', '验证维护成员'), 'new member persisted');
80
+ const member = (await fixture.call('members')).members.find(item => item.name === '验证维护成员');
81
+ assert.deepEqual(member.memoryGroupIds, ['group-docs']);
82
+ assert.equal(member.instructions, '先检查文档,再记录结果。');
83
+ await click('[data-edit-member="' + member.memberId + '"]');
84
+ await field('memberForm', 'instructions', '按项目工具配置更新文档。');
85
+ await click('#memberForm button[type="submit"]');
86
+ await waitFor(() => has('#memberList', '按项目工具配置更新文档。'), 'edited member persisted');
87
+ assert.equal((await fixture.call('members/' + member.memberId)).member.instructions, '按项目工具配置更新文档。');
88
+
89
+ const project1 = fixture.projects[0].id;
90
+ const project2 = fixture.projects[1].id;
91
+ await workflow('(() => {const select = doc.getElementById("projectPicker");select.value = ' + JSON.stringify(project2) + ';select.dispatchEvent(new Event("change"));return select.value;})()');
92
+ await waitFor(() => has('#projectForm', '未启用'), 'newly picked project shows persisted settings');
93
+ await workflow('doc.getElementById("projectForm").elements.enabled.checked = true');
94
+ await field('projectForm', 'leaderMemberId', member.memberId);
95
+ await workflow('doc.querySelector(' + JSON.stringify('[name="developerMemberIds"][value="' + member.memberId + '"]') + ').checked = true');
96
+ await click('#projectForm button[type="submit"]');
97
+ await waitFor(() => has('#projectForm', '已启用'), 'project setting saved');
98
+ const settings = (await fixture.call('projects/' + project2 + '/settings')).settings;
99
+ assert.equal(settings.leaderMemberId, member.memberId);
100
+ assert.deepEqual(settings.developerMemberIds, [member.memberId]);
101
+ assert.equal((await fixture.call('projects/' + project1 + '/settings')).settings.substantiveCodeReview, false);
102
+
103
+ await fixture.call('projects/' + project2 + '/settings', {
104
+ method: 'PUT', body: { requestId: 'external-settings-edit', expectedRevision: settings.revision, reminders: false },
105
+ });
106
+ await click('#projectForm button[type="submit"]');
107
+ await waitFor(() => has('#projectError', '配置已更新'), 'stale editor does not overwrite newer version');
108
+ await click('#projectError button');
109
+ await waitFor(() => workflow('doc.querySelector("#projectForm button[type=submit]")?.disabled === false'), 'reload updated config');
110
+ assert.equal((await fixture.call('projects/' + project2 + '/settings')).settings.reminders, false);
111
+
112
+ await click('#navMaintenance');
113
+ if (fixture.maintenance) {
114
+ await waitFor(() => has('#maintenanceRepoTitle', '示例代码仓库'), 'actual registered repository in the knowledge-base frame');
115
+ await click('[data-maintenance-new]');
116
+ await waitFor(() => has('#maintenanceDialogTitle', '新建维护任务'), 'maintenance creation dialog');
117
+ await field('maintenanceForm', 'title', '每日格式整理');
118
+ await field('maintenanceForm', 'memberId', member.memberId);
119
+ await field('maintenanceForm', 'toolId', 'format');
120
+ await field('maintenanceForm', 'trigger', 'daily');
121
+ await workflow('doc.getElementById("maintenanceForm").elements.trigger.dispatchEvent(new Event("change"))');
122
+ assert.equal(await workflow('doc.getElementById("maintenanceTimeField").hidden'), false);
123
+ await field('maintenanceForm', 'at', '09:00');
124
+ await workflow('doc.getElementById("maintenanceForm").elements.enabled.checked = true');
125
+ await shot('maintenance-task-form.png');
126
+ await click('#maintenanceForm button[type="submit"]');
127
+ await waitFor(() => has('.maintenance-job', '验证维护成员'), 'saved member is visible on the scheduled task');
128
+ assert.equal(await has('.maintenance-job', '每天 09:00'), true);
129
+ const job = (await fixture.call('maintenance')).jobs[0];
130
+ assert.equal(job.memberId, member.memberId);
131
+ assert.deepEqual(job.trigger, { kind: 'daily', at: '09:00' });
132
+ assert.equal(job.delivery, 'candidate');
133
+
134
+ await click('[data-maintenance-busy]');
135
+ await waitFor(() => has('[data-maintenance-busy]', '释放开发占用'), 'developer occupancy is persisted');
136
+ await click('[data-maintenance-run]');
137
+ await waitFor(() => has('.maintenance-run', '已排队'), 'manual run is queued during development');
138
+ await shot('maintenance-queued.png');
139
+ await click('[data-maintenance-busy]');
140
+ await waitFor(() => has('.maintenance-run', '已保留候选提交'), 'registered tool really commits in the isolated worktree');
141
+ await shot('maintenance-light.png');
142
+ await click('[data-maintenance-detail]');
143
+ await waitFor(() => has('#maintenanceRunDetail', '候选提交'), 'record displays real candidate SHA');
144
+ await click('.maintenance-receipt summary');
145
+ assert.equal(await has('.maintenance-receipt pre', 'format completed'), true);
146
+ await shot('maintenance-run-detail.png');
147
+ await click('#maintenanceRunDetail [data-close]');
148
+ } else {
149
+ await waitFor(() => has('#maintenance', '登记维护仓库'), 'unconfigured maintenance shows actual registration state');
150
+ assert.equal(await workflow('doc.querySelector("[data-maintenance-new]") === null'), true);
151
+ }
152
+ await browser.setViewport(390, 840);
153
+ await waitFor(() => workflow('doc.documentElement.scrollWidth <= doc.defaultView.innerWidth'), 'narrow maintenance layout');
154
+ assert.equal(await workflow('doc.querySelector("#navMaintenance").getBoundingClientRect().width > 0'), true);
155
+ await browser.setViewport(1440, 940);
156
+ await click('#navSettings');
157
+ await waitFor(() => has('#memberList', '验证维护成员'), 'team settings return from maintenance');
158
+
159
+ await page(`(() => {
160
+ const input = document.querySelector('input[data-token="accent"]');
161
+ input.value = '#3a775a';
162
+ input.dispatchEvent(new Event('input', { bubbles: true }));
163
+ })()`);
164
+ await waitFor(() => workflow('doc.documentElement.style.getPropertyValue("--accent") === "#3a775a"'), 'parent live skin applies inside Workflow');
165
+ await page('document.getElementById("themeToggle").click()');
166
+ await waitFor(() => workflow('doc.documentElement.dataset.theme === "dark"'), 'parent dark mode applies inside Workflow');
167
+ await shot('settings-dark.png');
168
+
169
+ await browser.setViewport(390, 840);
170
+ assert.ok(await workflow('doc.defaultView.innerWidth >= 360'), 'the knowledge-base sidebar must leave a usable width for the embedded page');
171
+ assert.equal(await workflow('doc.documentElement.scrollWidth <= doc.defaultView.innerWidth'), true);
172
+ await shot('mobile.png');
173
+ if (fixture.maintenance) {
174
+ await click('#navMaintenance');
175
+ await waitFor(() => has('.maintenance-run', '已保留候选提交'), 'actual runs render in dark mobile mode');
176
+ assert.equal(await workflow('doc.documentElement.scrollWidth <= doc.defaultView.innerWidth'), true);
177
+ await shot('maintenance-dark-mobile.png');
178
+ }
179
+ await click('#navTasks');
180
+ assert.equal(await has('#taskList', fixture.task.title), true);
181
+
182
+ if (options.designFile) {
183
+ await browser.send('Page.navigate', { url: fixture.address + '/?maintenance-preview=1' });
184
+ await waitFor(() => page('document.readyState === "complete" && Boolean(document.querySelector(\'nav [data-view="team"]\'))'), 'open design fixture');
185
+ await page('document.querySelector(\'nav [data-view="team"]\').click()');
186
+ await waitFor(() => has('#tk-page', '任务调度'), 'maintenance design mounts through the team frame');
187
+ await browser.setViewport(1440, 940);
188
+ await click('[data-action="simulate"]');
189
+ await click('#tk-form button[type="submit"]');
190
+ await waitFor(() => has('.tk-metrics', '1 排队'), 'busy repo queued while other repositories finish', 15000);
191
+ await click('[data-nav="projects"]');
192
+ await click('[data-action="toggle-development"][data-id="project-1"]');
193
+ await waitFor(() => has('.tk-table tbody tr:first-child', '累计使用 6 次'), 'reuses the existing worktree');
194
+ await click('[data-nav="runs"]');
195
+ await waitFor(() => has('.tk-run-detail', '提交并推送完成'), 'resumed simulation finishes');
196
+ await shot('maintenance-design.png');
197
+ await click('[data-action="simulate"]');
198
+ await field('tk-form', 'task', 'review-task');
199
+ await workflow('doc.getElementById("tk-form").elements.task.dispatchEvent(new Event("change"))');
200
+ await click('#tk-form button[type="submit"]');
201
+ await waitFor(() => has('.tk-run-detail', '修复提交已生成'), 'commit Review and repair simulation');
202
+ assert.ok(await has('.tk-run-detail', '复查通过'));
203
+ await click('[data-action="simulate"]');
204
+ await field('tk-form', 'task', 'docs-task');
205
+ await workflow('doc.getElementById("tk-form").elements.task.dispatchEvent(new Event("change"))');
206
+ await click('#tk-form button[type="submit"]');
207
+ await waitFor(() => has('.tk-run-detail', '提交并推送完成'), 'documentation simulation');
208
+ assert.ok(await has('.tk-run-detail', 'update_documents'));
209
+ }
210
+ assert.deepEqual(browser.exceptions, []);
211
+ const maintenanceResult = fixture.maintenance ? 'real maintenance task, run and receipt' : 'unconfigured maintenance';
212
+ console.log('ai-team-ui-integration-test PASS (shell proxy, team, members, project CAS, theme, mobile, ' + maintenanceResult + ')');
213
+ } finally {
214
+ if (browser) await browser.close();
215
+ await fixture.close();
216
+ }
217
+ }
218
+
219
+ main().catch(error => { console.error(error.stack); process.exitCode = 1; });
@@ -0,0 +1,235 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const http = require('node:http');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { Module } = require('node:module');
8
+ const { prepareMaintenanceFixture } = require('./single-repo-maintenance-fixture');
9
+
10
+ const root = path.resolve(__dirname, '..', '..', '..');
11
+ const host = '127.0.0.1';
12
+ const offline = 'http://127.0.0.1:0';
13
+ const projects = [
14
+ { id: 'project-ai-team-ui-1', name: '示例代码仓库' },
15
+ { id: 'project-ai-team-ui-2', name: '示例文档仓库' },
16
+ ];
17
+
18
+ function json(res, response, status = 200) {
19
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
20
+ res.end(JSON.stringify(response));
21
+ }
22
+
23
+ async function listen(server) {
24
+ await new Promise((resolve, reject) => {
25
+ server.once('error', reject);
26
+ server.listen(0, host, resolve);
27
+ });
28
+ return 'http://' + host + ':' + server.address().port;
29
+ }
30
+
31
+ function stop(server) {
32
+ server.closeAllConnections?.();
33
+ return new Promise(resolve => server.close(resolve));
34
+ }
35
+
36
+ function copyInstall(from, to, files) {
37
+ fs.mkdirSync(to, { recursive: true });
38
+ for (const file of files) fs.cpSync(path.join(from, file), path.join(to, file), { recursive: true });
39
+ }
40
+
41
+ function prepareIsolatedEnvironment(sandbox, moduleUrls) {
42
+ const paths = {
43
+ KB_DATA_DIR: path.join(sandbox, 'kb-data'),
44
+ KB_KNOWLEDGE_DATA_DIR: path.join(sandbox, 'knowledge'),
45
+ KB_CLAUDE_RULES_DIR: path.join(sandbox, 'config'),
46
+ AI_CODING_EVENT_BRIDGE_HOME: path.join(sandbox, 'bridge-home'),
47
+ HOME: path.join(sandbox, 'git-home'),
48
+ };
49
+ if (process.platform === 'win32') paths.USERPROFILE = path.join(sandbox, 'home');
50
+ for (const directory of Object.values(paths)) fs.mkdirSync(directory);
51
+ Object.assign(process.env, paths, {
52
+ KB_TERMINAL_URL: offline,
53
+ KB_VECTORHUB_URL: offline,
54
+ KB_EVENTBRIDGE_URL: offline,
55
+ KB_EVENT_BRIDGE_URL: offline,
56
+ KB_KNOWLEDGE_ENGINE_URL: moduleUrls.engine,
57
+ KB_WORKFLOW_URL: moduleUrls.workflow,
58
+ KB_MODULES_AUTOSTART: '0',
59
+ KB_MODULES_REGISTER: '0',
60
+ NODE_PATH: path.join(root, 'node_modules'),
61
+ });
62
+ Module._initPaths();
63
+ }
64
+
65
+ async function fetchJson(url, options = {}) {
66
+ const response = await fetch(url, {
67
+ ...options, headers: { 'Content-Type': 'application/json' },
68
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
69
+ });
70
+ const payload = await response.json();
71
+ if (!response.ok) throw new Error(`${response.status} ${url} ${payload.message || ''}`);
72
+ return payload;
73
+ }
74
+
75
+ async function seedSyntheticState(runtime, sandbox, call, emptyTeam) {
76
+ for (const project of projects) {
77
+ const repoPath = path.join(sandbox, 'repos', project.id);
78
+ const knowledgePath = path.join(sandbox, 'knowledge', project.id);
79
+ fs.mkdirSync(repoPath, { recursive: true });
80
+ fs.mkdirSync(knowledgePath, { recursive: true });
81
+ await runtime.projectStore.create(project.id, { displayName: project.name, repoPath, knowledgePath });
82
+ await runtime.registryStore.add(project.id, { displayName: project.name });
83
+ }
84
+ if (emptyTeam) return { members: [], task: null };
85
+ const { members } = await call('team', {
86
+ method: 'POST', body: {
87
+ requestId: 'seed-team', name: '维护团队',
88
+ members: [
89
+ { name: '维护 Agent', role: 'developer', instructions: '检查和维护示例仓库。', memoryGroupIds: ['group-code'] },
90
+ { name: '独立 Reviewer', role: 'reviewer', instructions: '审阅改动说明。' },
91
+ ],
92
+ },
93
+ });
94
+ await call('projects/' + projects[0].id + '/settings', {
95
+ method: 'PUT', body: {
96
+ requestId: 'seed-settings', enabled: true, autoDispatch: true, substantiveCodeReview: false,
97
+ leaderMemberId: members[0].memberId, developerMemberIds: [members[0].memberId], reviewerMemberId: members[1].memberId,
98
+ },
99
+ });
100
+ const { task } = await call('workflow-tasks', {
101
+ method: 'POST', body: {
102
+ requestId: 'seed-task', projectId: projects[0].id, title: '维护示例仓库的接口文档',
103
+ goal: '核对接口文档的用法与实现。',
104
+ ownerMemberId: members[0].memberId,
105
+ acceptance: [{ kind: 'manual', title: '示例文档与接口一致' }],
106
+ },
107
+ });
108
+ return { members, task };
109
+ }
110
+
111
+ function attachDesignPreview(install, designFile) {
112
+ const asset = path.join(install, 'core', 'ui', 'product.js');
113
+ const source = fs.readFileSync(asset, 'utf8');
114
+ const route = '/workflow-ui/?embed=1&apiBase=/api/workflow';
115
+ if (!source.includes(route)) throw new Error('Workflow iframe route has changed.');
116
+ fs.writeFileSync(asset, source.replace("'" + route + "'", `(new URLSearchParams(location.search).has('maintenance-preview') ? '/workflow-ui/maintenance-preview.html?embed=1' : '${route}')`));
117
+ return fs.readFileSync(designFile);
118
+ }
119
+
120
+ function fixtureRequestAllowed(method, pathname, maintenance) {
121
+ if (pathname.startsWith('/api/integrations')) return false;
122
+ if (method === 'GET' || method === 'HEAD') return true;
123
+ if (method === 'POST') {
124
+ if (maintenance && /^\/api\/workflow\/maintenance\/(jobs|runs|control)$/.test(pathname)) return true;
125
+ return ['/api/workflow/team', '/api/workflow/members', '/api/workflow/workflow-tasks'].includes(pathname);
126
+ }
127
+ if (method === 'PATCH') return /^\/api\/workflow\/members\/[^/]+$/.test(pathname);
128
+ if (method === 'PUT') return projects.some(project => pathname === `/api/workflow/projects/${project.id}/settings`);
129
+ return false;
130
+ }
131
+
132
+ async function createAiTeamUiFixture({ dataDir, workflowRoot, designFile, emptyTeam = false, maintenance = false, maintenanceTiming }) {
133
+ // A fresh, explicitly named directory cannot alias an existing installation.
134
+ const sandbox = path.resolve(dataDir);
135
+ fs.mkdirSync(sandbox);
136
+ const install = path.join(sandbox, 'install');
137
+ const workflowInstall = path.join(install, 'workflow');
138
+ const coreInstall = path.join(install, 'core');
139
+ copyInstall(workflowRoot, workflowInstall, ['src', 'ui', 'package.json']);
140
+ copyInstall(root, coreInstall, ['_site', 'ui', 'package.json', 'module-runtime-manifest.json']);
141
+ const design = designFile ? attachDesignPreview(install, designFile) : null;
142
+ const workflowData = path.join(sandbox, 'workflow-data');
143
+ fs.mkdirSync(workflowData);
144
+ prepareIsolatedEnvironment(sandbox, { engine: offline, workflow: offline });
145
+ const maintenanceFixture = maintenance && prepareMaintenanceFixture({ sandbox, coreInstall, workflowData, projectId: projects[0].id });
146
+ if (maintenanceFixture) maintenanceFixture.journalId = await maintenanceFixture.registerProject();
147
+ const bridgeUrl = maintenanceFixture ? await listen(maintenanceFixture.server) : offline;
148
+ const { createWorkflowServer } = require(path.join(workflowInstall, 'src', 'server'));
149
+ const workflowOptions = {
150
+ dataDir: workflowData, bridgeUrl, maintenanceTiming,
151
+ projectRoots: maintenanceFixture ? { [projects[0].id]: maintenanceFixture.repo } : undefined,
152
+ };
153
+ let workflow = createWorkflowServer(workflowOptions);
154
+ const memoryDirectory = http.createServer((req, res) => {
155
+ if (req.method === 'GET' && req.url.startsWith('/api/memory-groups?')) {
156
+ json(res, { ok: true, groups: [{ id: 'group-code', name: '代码规范' }, { id: 'group-docs', name: '文档约定' }], total: 2 });
157
+ } else json(res, { ok: false, error: 'FIXTURE_ROUTE' }, 404);
158
+ });
159
+ const shell = http.createServer();
160
+ const close = () => Promise.allSettled([
161
+ stop(shell), stop(memoryDirectory), workflow.close(), ...(maintenanceFixture ? [stop(maintenanceFixture.server)] : []),
162
+ ]);
163
+ try {
164
+ const [wf, engine] = await Promise.all([workflow.listen(0, host), listen(memoryDirectory)]);
165
+ const workflowUrl = 'http://' + host + ':' + wf.port;
166
+ Object.assign(process.env, {
167
+ KB_KNOWLEDGE_ENGINE_URL: engine, KB_WORKFLOW_URL: workflowUrl,
168
+ KB_EVENTBRIDGE_URL: bridgeUrl, KB_EVENT_BRIDGE_URL: bridgeUrl,
169
+ });
170
+ const { createRuntime, initializeRuntime, createRequestHandler } = require(path.join(coreInstall, '_site', 'lib', 'server-app'));
171
+ const runtime = createRuntime({ rootDir: coreInstall, dataDir: process.env.KB_DATA_DIR, analysisOwner: 'legacy' });
172
+ await initializeRuntime(runtime);
173
+ const address = await listen(shell);
174
+ const handler = createRequestHandler(runtime, { host, port: shell.address().port });
175
+ shell.on('request', (req, res) => {
176
+ const pathname = new URL(req.url, address).pathname;
177
+ if (!fixtureRequestAllowed(req.method, pathname, maintenance)) {
178
+ json(res, { ok: false, error: 'FIXTURE_READ_ONLY', message: '此操作超出隔离 AI 团队预览范围。' }, 403);
179
+ return;
180
+ }
181
+ if (design && req.method === 'GET' && req.url.startsWith('/workflow-ui/maintenance-preview.html?')) {
182
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
183
+ res.end(design);
184
+ return;
185
+ }
186
+ handler(req, res);
187
+ });
188
+ const call = (route, options) => fetchJson(address + '/api/workflow/' + route, options);
189
+ const seeded = await seedSyntheticState(runtime, sandbox, call, emptyTeam);
190
+ if (maintenanceFixture) {
191
+ maintenanceFixture.installHook(process.env.KB_DATA_DIR, shell.address().port);
192
+ await workflow.consumer.drain({ notifyUrl: workflowUrl + '/api/internal/bridge-notify' });
193
+ }
194
+ async function restartWorkflow() {
195
+ await workflow.close();
196
+ workflow = createWorkflowServer(workflowOptions);
197
+ await workflow.listen(wf.port, host);
198
+ if (maintenanceFixture) await workflow.consumer.drain({ notifyUrl: workflowUrl + '/api/internal/bridge-notify' });
199
+ }
200
+ return {
201
+ address, call, projects, browserProfile: path.join(sandbox, 'browser-profile'), ...seeded,
202
+ maintenance: maintenanceFixture, workflowUrl, restartWorkflow, close,
203
+ };
204
+ } catch (error) {
205
+ await close();
206
+ throw error;
207
+ }
208
+ }
209
+
210
+ function argument(name) {
211
+ const index = process.argv.indexOf('--' + name);
212
+ return index < 0 ? '' : process.argv[index + 1] || '';
213
+ }
214
+
215
+ function cliOptions({ test = false, defaultMaintenance = false } = {}) {
216
+ const dataDir = argument('data') || (test ? path.join(fs.mkdtempSync(path.join(process.env.PK_TEST_TEMP_ROOT || os.tmpdir(), 'pk-ai-team-')), 'data') : '');
217
+ const workflowRoot = argument('workflow-root') || (test ? path.dirname(require.resolve('@sanqianx/ai-coding-workflow/package.json')) : '');
218
+ if (!dataDir || !workflowRoot) throw new Error('Supply --data <new test directory> and --workflow-root <Workflow checkout>.');
219
+ return {
220
+ dataDir, workflowRoot, designFile: argument('design') || undefined,
221
+ emptyTeam: process.argv.includes('--empty-team'),
222
+ maintenance: process.argv.includes('--maintenance') || (defaultMaintenance && !process.argv.includes('--without-maintenance')),
223
+ };
224
+ }
225
+
226
+ if (require.main === module) {
227
+ createAiTeamUiFixture(cliOptions()).then(fixture => {
228
+ const close = () => fixture.close().then(() => { process.exitCode = 0; });
229
+ process.once('SIGINT', close);
230
+ process.once('SIGTERM', close);
231
+ console.log(JSON.stringify({ address: fixture.address, pid: process.pid, data: path.resolve(argument('data')) }));
232
+ }).catch(error => { console.error(error.stack); process.exitCode = 1; });
233
+ }
234
+
235
+ module.exports = { createAiTeamUiFixture, cliOptions };
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const http = require('node:http');
5
+ const path = require('node:path');
6
+ const { execFileSync, execFile } = require('node:child_process');
7
+ const { promisify } = require('node:util');
8
+
9
+ const command = promisify(execFile);
10
+ const host = '127.0.0.1';
11
+ const BRIDGE_PACKAGE = '@sanqianx/ai-coding-event-bridge-console';
12
+
13
+ function git(repo, ...args) {
14
+ return execFileSync('git', args, { cwd: repo, encoding: 'utf8', windowsHide: true, timeout: 30_000 }).trim();
15
+ }
16
+
17
+ async function gitAsync(repo, ...args) {
18
+ const { stdout } = await command('git', args, { cwd: repo, encoding: 'utf8', windowsHide: true, timeout: 30_000 });
19
+ return stdout.trim();
20
+ }
21
+
22
+ function prepareMaintenanceFixture({ sandbox, coreInstall, workflowData, projectId }) {
23
+ const repo = path.join(sandbox, 'repos', projectId);
24
+ const remote = path.join(sandbox, 'isolated upstream.git');
25
+ const emptyHooks = path.join(sandbox, 'empty-hooks');
26
+ for (const directory of [repo, remote, emptyHooks]) fs.mkdirSync(directory, { recursive: true });
27
+ git(remote, 'init', '-q', '--bare', '-b', 'main');
28
+ git(repo, 'init', '-q', '-b', 'main');
29
+ git(repo, 'config', '--local', 'core.hooksPath', emptyHooks);
30
+ git(repo, 'config', '--local', 'user.name', 'Synthetic Maintenance QA');
31
+ git(repo, 'config', '--local', 'user.email', 'maintenance-qa@example.invalid');
32
+ git(repo, 'config', '--local', 'core.autocrlf', 'false');
33
+ fs.writeFileSync(path.join(repo, 'policy.txt'), 'PASS\n');
34
+ fs.writeFileSync(path.join(repo, 'README.md'), '# Isolated maintenance fixture\n');
35
+ git(repo, 'add', '.');
36
+ git(repo, 'commit', '-qm', 'fixture baseline');
37
+ const baseline = git(repo, 'rev-parse', 'HEAD');
38
+ git(repo, 'remote', 'add', 'origin', remote);
39
+ git(repo, 'push', '-u', 'origin', 'main');
40
+ git(repo, 'config', '--local', 'core.hooksPath', '.git/hooks');
41
+
42
+ const tool = path.join(sandbox, 'install', 'tool.js');
43
+ fs.copyFileSync(path.join(__dirname, 'single-repo-maintenance-tool.js'), tool);
44
+ const cli = mode => [process.execPath, tool, mode];
45
+ const configPath = path.join(workflowData, 'workflow', 'maintenance.json');
46
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
47
+ fs.writeFileSync(configPath, JSON.stringify({
48
+ version: 1, projectId, repoPath: repo, branch: 'main', remote: 'origin', allowPush: true,
49
+ tools: [
50
+ { id: 'review', name: '示例代码规则', kind: 'review', check: cli('check'), repair: cli('repair') },
51
+ { id: 'format', name: '示例格式整理器', kind: 'apply', apply: cli('format') },
52
+ { id: 'docs', name: '示例文档工具', kind: 'apply', apply: cli('docs') },
53
+ { id: 'reject', name: '示例未通过规则', kind: 'review', check: cli('reject'), repair: cli('stubborn'), maxRepairs: 1 },
54
+ { id: 'timeout', name: '示例超时命令', kind: 'apply', apply: cli('timeout'), timeoutSeconds: 1 },
55
+ { id: 'probe', name: '示例推送授权检查', kind: 'apply', apply: cli('record') },
56
+ ],
57
+ }, null, 2));
58
+
59
+ const bridgeInstall = path.join(sandbox, 'install', 'bridge');
60
+ const bridgeSource = path.dirname(require.resolve(BRIDGE_PACKAGE + '/package.json'));
61
+ fs.mkdirSync(bridgeInstall);
62
+ for (const item of ['package.json', 'src']) fs.cpSync(path.join(bridgeSource, item), path.join(bridgeInstall, item), { recursive: true });
63
+ const bridgeHome = process.env.AI_CODING_EVENT_BRIDGE_HOME;
64
+ const bridgeModule = path.join(bridgeInstall, 'src', 'bridge', 'index.js');
65
+ const { createBridge, resolveRepoContext, projectRegistry, projectJournalDir, Journal } = require(bridgeModule);
66
+ const { createConsoleServer } = require(path.join(bridgeInstall, 'src', 'server'));
67
+ const bridge = createBridge({ homeDir: bridgeHome });
68
+ const server = http.createServer(createConsoleServer({ home: bridgeHome }));
69
+
70
+ function installHook(dataDir, port) {
71
+ const { installHook } = require(path.join(coreInstall, '_site', 'lib', 'hook-manager'));
72
+ const { writeEndpoint } = require(path.join(coreInstall, '_site', 'lib', 'runtime-endpoint'));
73
+ writeEndpoint(dataDir, { host, port, pid: process.pid });
74
+ return installHook({
75
+ projectId, repoPath: repo, dataDir, bridgeHomeDir: bridgeHome, bridgeModulePath: bridgeModule,
76
+ triggerScriptPath: path.join(coreInstall, '_site', 'scripts', 'hook-trigger.js'),
77
+ });
78
+ }
79
+ async function appendBoundary(overrides = {}) {
80
+ const { repoIdentity } = await resolveRepoContext(repo);
81
+ return bridge.appendCommitBoundary({
82
+ projectId, repoIdentity, commitSha: git(repo, 'rev-parse', 'HEAD'), branch: 'main', ...overrides,
83
+ });
84
+ }
85
+ async function registerProject() {
86
+ const project = await projectRegistry.addProject({ home: bridgeHome, path: repo, store: path.join(sandbox, 'bridge project store') });
87
+ const old = await appendBoundary();
88
+ await new Journal(projectJournalDir(project)).trimThrough(old.sequence);
89
+ return project.id;
90
+ }
91
+ return { repo, remote, baseline, configPath, projectId, server, bridge, installHook, appendBoundary, registerProject, git, gitAsync };
92
+ }
93
+
94
+ module.exports = { prepareMaintenanceFixture };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const input = JSON.parse(fs.readFileSync(0, 'utf8'));
8
+ assert.equal(input.schema, 'ai-team-maintenance/v1');
9
+ assert.equal(fs.realpathSync(input.workspace), fs.realpathSync(process.cwd()));
10
+ assert.equal(typeof input.member.instructions, 'string');
11
+ assert.equal(process.env.KB_WORKFLOW_RUNTIME_TOKEN, undefined);
12
+ assert.equal(process.env.GIT_DIR, undefined);
13
+ const mode = process.argv[2];
14
+
15
+ switch (mode) {
16
+ case 'check':
17
+ assert.equal(input.phase, 'check');
18
+ assert.deepEqual(input.member.memoryGroupIds, ['group-code']);
19
+ if (fs.readFileSync('policy.txt', 'utf8').trim() !== 'PASS') {
20
+ console.log(JSON.stringify({ path: 'policy.txt', expected: 'PASS' }));
21
+ process.exitCode = 1;
22
+ }
23
+ break;
24
+ case 'repair':
25
+ assert.equal(input.phase, 'repair');
26
+ assert.equal(JSON.parse(input.findings.stdout.text).path, 'policy.txt');
27
+ fs.writeFileSync('policy.txt', 'PASS\n');
28
+ break;
29
+ case 'format':
30
+ assert.equal(input.phase, 'apply');
31
+ fs.writeFileSync('formatted.txt', 'one line\n');
32
+ console.log('format completed');
33
+ break;
34
+ case 'docs':
35
+ assert.equal(input.phase, 'apply');
36
+ assert.ok(fs.existsSync('formatted.txt'), 'docs reads the updated remote baseline');
37
+ fs.mkdirSync('docs', { recursive: true });
38
+ fs.writeFileSync(path.join('docs', 'usage.md'), '# Formatted repository\n');
39
+ break;
40
+ case 'reject':
41
+ console.log('Additional fixes required');
42
+ process.exitCode = 1;
43
+ break;
44
+ case 'stubborn':
45
+ fs.writeFileSync('unresolved.txt', 'Keep this after failed review\n');
46
+ break;
47
+ case 'timeout':
48
+ fs.writeFileSync('timed-out.txt', 'Keep this after timeout\n');
49
+ setTimeout(() => {}, 10_000);
50
+ break;
51
+ case 'record':
52
+ fs.writeFileSync('push-permission.txt', 'This candidate should stay local\n');
53
+ break;
54
+ default:
55
+ throw new Error('Unknown fixture tool action.');
56
+ }
@@ -121,7 +121,16 @@ async function main() {
121
121
  // Add the memory through the real UI with the project-bound combination: the new-memory
122
122
  // dialog (#appDialog > #memoryForm) with title + multiline body, scope
123
123
  // global, submitted by the primary (type=submit) action button.
124
- await harness.nativeClick('#memoryContent [data-action="new-memory"]');
124
+ // Initial live refreshes can redraw the toolbar between the coordinate
125
+ // probe and the CDP click. Find, hit-test and activate the same node.
126
+ await harness.waitFor(() => harness.run(`(() => {
127
+ const button = document.querySelector('#memoryContent [data-action="new-memory"]');
128
+ if (!button || button.disabled || !button.getClientRects().length) return false;
129
+ const rect = button.getBoundingClientRect();
130
+ if (!button.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2))) return false;
131
+ button.click();
132
+ return true;
133
+ })()`), 'the add memory control is actionable', 10000);
125
134
  await harness.waitFor(
126
135
  () => harness.run("document.getElementById('appDialog').open === true && document.getElementById('memoryForm') !== null"),
127
136
  'the add dialog with the memory form is open',
@@ -23,32 +23,28 @@ async function createTeamViaSettings(harness, projectId, group) {
23
23
  node.click();
24
24
  return true;
25
25
  }, selector), `control clickable: ${selector}`);
26
- const change = (selector, value, eventType) => inFrame((doc, target, next, type) => {
27
- const node = doc.querySelector(target);
28
- node.value = next;
29
- node.dispatchEvent(new Event(type, { bubbles: true }));
30
- }, selector, value, eventType);
31
-
32
26
  await harness.nativeClick('nav [data-view="projects"]');
33
27
  const createTeam = `[data-project-team="${projectId}"] [data-go="team"]`;
34
28
  // Atomic wait-and-click: the project list re-renders after async loads, so
35
29
  // a separate waitFor+click races a redraw that swaps the node out.
36
30
  await harness.waitFor(() => harness.run(`(selector => { const node = document.querySelector(selector); if (!node || node.disabled || !node.getClientRects().length) return false; node.click(); return true; })(${JSON.stringify(createTeam)})`), 'create-team entry clickable');
37
31
  // P4a workbench: the workbench opens on the tasks view; the empty-team
38
- // init card lives on the settings view. Wait for the app's startup probe to
32
+ // creation form lives on the settings view. Wait for the app's startup probe to
39
33
  // settle FIRST — clicking inside a frame that is about to be reloaded lands
40
34
  // in the dying document and the fresh one boots back to the tasks view.
41
35
  await harness.waitFor(() => inFrame(doc => doc && doc.querySelector('#serviceText') && !doc.querySelector('#serviceText').textContent.includes('正在连接')), 'workbench settled');
42
36
  await click('#navSettings');
43
- try {
44
- await harness.waitFor(() => inFrame(doc => Boolean(doc?.querySelector('#createTeam'))), 'empty team init card');
45
- } catch (error) {
46
- const dump = await inFrame(doc => doc ? doc.body.innerHTML.slice(0, 400) : 'NO IFRAME DOC');
47
- console.error('DIAG settings body:', dump);
48
- throw error;
49
- }
50
- await click('#createTeam');
37
+ await harness.waitFor(() => inFrame((doc, name) => {
38
+ const form = doc?.querySelector('#teamForm');
39
+ const submit = form?.querySelector('button[type="submit"]');
40
+ if (!submit || submit.disabled || !submit.getClientRects().length) return false;
41
+ form.elements.name.value = name;
42
+ submit.click();
43
+ return true;
44
+ }, teamName), 'submit the first-team form');
51
45
  await harness.waitFor(() => inFrame(doc => Boolean(doc?.querySelector('#addMember'))), 'member management after team creation');
46
+ const team = await harness.productApi('GET', workflowApi + '/team');
47
+ assert.equal(team.body.team.name, teamName, 'the form creates the named team');
52
48
 
53
49
  // Default roster: the module seeds developer + reviewer.
54
50
  let members = (await harness.productApi('GET', workflowApi + '/members')).body.members;
@@ -0,0 +1,200 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { setTimeout: delay } = require('node:timers/promises');
7
+ const { createAiTeamUiFixture, cliOptions } = require('./helpers/ai-team-ui-fixture');
8
+
9
+ async function until(read, predicate, label) {
10
+ const deadline = Date.now() + 30_000;
11
+ let value;
12
+ while (Date.now() < deadline) {
13
+ value = await read();
14
+ if (predicate(value)) return value;
15
+ await delay(125);
16
+ }
17
+ throw new Error('Timed out waiting for ' + label + '\n' + JSON.stringify(value));
18
+ }
19
+
20
+ async function main() {
21
+ const options = cliOptions({ test: true });
22
+ let fakeTime;
23
+ const fixture = await createAiTeamUiFixture({
24
+ ...options, maintenance: true, emptyTeam: false,
25
+ maintenanceTiming: { pollMs: 150, bridgePollMs: 250, clock: () => fakeTime || new Date() },
26
+ });
27
+ try {
28
+ const { repo, remote, baseline, configPath, projectId, journalId, bridge, git, gitAsync, appendBoundary } = fixture.maintenance;
29
+ const status = () => fixture.call('maintenance');
30
+ const post = (route, body) => fixture.call('maintenance/' + route, { method: 'POST', body });
31
+ const detail = runId => fixture.call('maintenance/runs/' + runId).then(value => value.run);
32
+ const upstream = () => git(remote, 'rev-parse', 'refs/heads/main');
33
+ const terminal = run => !['queued', 'running'].includes(run.status);
34
+ const waitRun = id => until(() => detail(id), terminal, 'run ' + id);
35
+ const getRuns = async (job, kind) => (await status()).runs.filter(run => run.jobId === job.jobId && run.trigger.kind === kind);
36
+ let requestIndex = 0;
37
+ const save = fields => post('jobs', {
38
+ requestId: 'job-' + (++requestIndex), memberId: fixture.members[0].memberId,
39
+ enabled: true, delivery: 'candidate', ...fields,
40
+ }).then(value => value.job);
41
+ const control = (busy, fields = {}) => post('control', { requestId: 'control-' + (++requestIndex), busy, ...fields });
42
+ const runNow = (job, id) => post('runs', { requestId: id || 'run-' + (++requestIndex), jobId: job.jobId }).then(value => value.run);
43
+
44
+ const available = await status();
45
+ assert.equal(available.projectId, projectId);
46
+ assert.equal(available.workspace, null);
47
+ assert.equal(available.timeZone, 'Asia/Shanghai');
48
+ assert.ok(available.tools.every(tool => !tool.phases && !tool.command));
49
+ const consumers = await bridge.listConsumers();
50
+ assert.deepEqual(consumers.find(item => item.name === 'workflow:default').meta.journals, ['global', journalId]);
51
+ const direct = fixture.workflowUrl + '/api/workflow/v1/maintenance';
52
+ assert.equal((await fetch(direct, { headers: { Origin: 'https://foreign.example' } })).status, 403);
53
+ assert.equal((await fetch(direct + '/runs', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{}' })).status, 400);
54
+ assert.equal((await fetch(fixture.address + '/api/workflow/maintenance/control', {
55
+ method: 'POST', headers: { Origin: 'https://foreign.example', 'Content-Type': 'application/json' },
56
+ body: JSON.stringify({ requestId: 'cross-origin', busy: true }),
57
+ })).status, 403);
58
+ await assert.rejects(save({ title: 'Invalid member', toolId: 'review', memberId: 'other', trigger: { kind: 'commit' } }), /400/);
59
+ await assert.rejects(save({ title: 'Unknown executable', toolId: 'arbitrary', trigger: { kind: 'commit' } }), /400/);
60
+
61
+ const historical = await appendBoundary(); // Already captured before maintenance is enabled.
62
+ assert.ok(historical.sequence > 1, 'the project journal starts with a real compacted prefix');
63
+ let review = await save({ title: '处理提交检查', toolId: 'review', trigger: { kind: 'commit' } });
64
+ assert.deepEqual(await getRuns(review, 'commit'), []);
65
+ await control(true);
66
+ fs.writeFileSync(path.join(repo, 'policy.txt'), 'FAIL\n');
67
+ await gitAsync(repo, 'add', 'policy.txt');
68
+ await gitAsync(repo, 'commit', '-qm', 'source commit from development');
69
+ const source = git(repo, 'rev-parse', 'HEAD');
70
+ const queued = await until(() => getRuns(review, 'commit'), runs => runs.length === 1, 'real managed Git hook');
71
+ assert.equal(queued[0].trigger.commitSha, source);
72
+ assert.equal(queued[0].status, 'queued');
73
+ assert.equal((await status()).workspace, null);
74
+ const events = await bridge.readEvents({ journalId, fromSequence: 1 });
75
+ assert.ok(events.some(event => event.schema === 'git-commit-boundary/v1' && event.commitSha === source));
76
+ await appendBoundary();
77
+ await appendBoundary({ projectId: 'project-another-repo', commitSha: baseline });
78
+ await appendBoundary({ branch: 'different-branch', commitSha: baseline });
79
+ const lastBoundary = await bridge.getHighWatermark({ journalId });
80
+ await until(() => fixture.call('consumer'), result => result.cursors[journalId] === lastBoundary, 'all journal events processed');
81
+ const workflowState = JSON.parse(fs.readFileSync(path.join(options.dataDir, 'workflow-data', 'workflow', 'state.json'), 'utf8'));
82
+ assert.ok(workflowState.consumer.gaps.some(gap => gap.journalId === journalId && gap.reason === 'retained-prefix'));
83
+ assert.equal((await getRuns(review, 'commit')).length, 1);
84
+
85
+ const devFile = path.join(repo, 'work-in-progress.txt');
86
+ fs.writeFileSync(devFile, 'Development workspace only\n');
87
+ await control(false);
88
+ await until(status, data => data.waitReason === 'original-busy', 'uncommitted original work held');
89
+ assert.equal(fs.readFileSync(devFile, 'utf8'), 'Development workspace only\n');
90
+ assert.equal((await status()).workspace, null);
91
+ fs.unlinkSync(devFile);
92
+
93
+ const first = await waitRun(queued[0].runId);
94
+ assert.equal(first.status, 'succeeded', JSON.stringify(first));
95
+ assert.equal(first.delivery, 'candidate');
96
+ assert.equal(first.baseSha, source);
97
+ assert.deepEqual(first.receipts.map(receipt => [receipt.phase, receipt.exitCode]), [['check', 1], ['repair', 0], ['check', 0]]);
98
+ assert.equal(git(repo, 'rev-parse', first.candidateRef), first.commitSha);
99
+ assert.equal(git(repo, 'rev-parse', first.commitSha + '^'), source);
100
+ assert.equal(git(repo, 'show', first.commitSha + ':policy.txt'), 'PASS');
101
+ assert.equal(git(repo, 'rev-parse', 'HEAD'), source);
102
+ assert.equal(fs.readFileSync(path.join(repo, 'policy.txt'), 'utf8'), 'FAIL\n');
103
+ assert.equal(upstream(), baseline);
104
+ const workspace = (await status()).workspace;
105
+ assert.ok(workspace && workspace !== repo);
106
+ assert.equal(git(repo, 'worktree', 'list', '--porcelain').split(/\r?\n/).filter(line => line.startsWith('worktree ')).length, 2);
107
+
108
+ await fixture.restartWorkflow();
109
+ assert.equal((await status()).workspace, workspace);
110
+ await appendBoundary();
111
+ assert.equal((await getRuns(review, 'commit')).length, 1, 'dedupe persists across service restart');
112
+ review = await save({ ...review, expectedRevision: review.revision, delivery: 'push' });
113
+ await assert.rejects(save({ ...review, expectedRevision: review.revision - 1 }), /409/);
114
+ fs.writeFileSync(path.join(repo, 'second-source.txt'), 'This local commit must stay local\n');
115
+ await gitAsync(repo, 'add', 'second-source.txt');
116
+ await gitAsync(repo, 'commit', '-qm', 'second unpublished source commit');
117
+ const next = await until(() => getRuns(review, 'commit'), runs => runs.length === 2, 'second Git boundary');
118
+ const unpushed = await waitRun(next[0].runId);
119
+ assert.equal(unpushed.delivery, 'remote-changed', JSON.stringify(unpushed));
120
+ assert.equal(upstream(), baseline);
121
+ assert.equal((await status()).workspace, workspace);
122
+
123
+ fakeTime = new Date('2031-01-20T00:58:00.000Z');
124
+ await control(true);
125
+ const schedule = { kind: 'daily', at: '09:00' };
126
+ const formatter = await save({ title: '日常格式整理', toolId: 'format', trigger: schedule, delivery: 'push' });
127
+ const docs = await save({ title: '更新项目文档', toolId: 'docs', trigger: schedule, delivery: 'push' });
128
+ assert.equal((await status()).queueLength, 0);
129
+ fakeTime = new Date('2031-01-20T01:00:00.000Z');
130
+ const dailyQueue = await until(status, data => data.queueLength === 2, '09:00 China time schedule');
131
+ const formatQueued = dailyQueue.runs.find(run => run.jobId === formatter.jobId);
132
+ const docsQueued = dailyQueue.runs.find(run => run.jobId === docs.jobId);
133
+ assert.deepEqual(formatQueued.trigger, { kind: 'daily', date: '2031-01-20', at: '09:00', timeZone: 'Asia/Shanghai' });
134
+ await control(false);
135
+ const formatted = await waitRun(formatQueued.runId);
136
+ const documented = await waitRun(docsQueued.runId);
137
+ assert.equal(formatted.delivery, 'pushed', JSON.stringify(formatted));
138
+ assert.equal(formatted.baseSha, baseline);
139
+ assert.equal(documented.delivery, 'pushed', JSON.stringify(documented));
140
+ assert.equal(documented.baseSha, formatted.commitSha, 'second write fetches the completed first write');
141
+ assert.equal(upstream(), documented.commitSha);
142
+ assert.equal(git(remote, 'show', 'main:docs/usage.md'), '# Formatted repository');
143
+ assert.equal(git(repo, 'status', '--porcelain'), '');
144
+ assert.equal((await status()).workspace, workspace);
145
+ fakeTime = new Date('2031-01-20T01:10:00.000Z');
146
+ await fixture.restartWorkflow();
147
+ const noOp = await runNow(formatter, 'manual-idempotent');
148
+ assert.equal((await runNow(formatter, 'manual-idempotent')).runId, noOp.runId);
149
+ assert.equal((await waitRun(noOp.runId)).delivery, 'no-changes');
150
+ assert.equal((await getRuns(formatter, 'daily')).length, 1);
151
+ assert.equal((await getRuns(docs, 'daily')).length, 1);
152
+
153
+ const reject = await save({ title: '无法修复的规则', toolId: 'reject', trigger: { kind: 'manual' } });
154
+ const failed = await waitRun((await runNow(reject)).runId);
155
+ assert.equal(failed.status, 'failed');
156
+ assert.equal(failed.reason, 'review-findings');
157
+ assert.deepEqual(failed.receipts.map(item => item.exitCode), [1, 0, 1]);
158
+ assert.equal(failed.commitSha, undefined);
159
+ const heldRun = await runNow(formatter);
160
+ await until(status, data => data.waitReason === 'workspace-dirty', 'dirty maintenance worktree held');
161
+ const unresolved = path.join(workspace, 'unresolved.txt');
162
+ assert.match(fs.readFileSync(unresolved, 'utf8'), /Keep this/);
163
+ fs.renameSync(unresolved, path.join(options.dataDir, 'preserved-failed-review.txt'));
164
+ assert.equal((await waitRun(heldRun.runId)).delivery, 'no-changes');
165
+
166
+ const timeout = await save({ title: '超时后保护', toolId: 'timeout', trigger: { kind: 'manual' } });
167
+ const interrupted = await waitRun((await runNow(timeout)).runId);
168
+ assert.equal(interrupted.status, 'interrupted');
169
+ assert.equal(interrupted.receipts[0].error, 'command-timeout');
170
+ assert.equal((await status()).hold.runId, interrupted.runId);
171
+ const queuedAfterTimeout = await runNow(formatter);
172
+ assert.equal((await detail(queuedAfterTimeout.runId)).status, 'queued');
173
+ await assert.rejects(control(false, { clearHold: true, holdRunId: 'stale' }), /409/);
174
+ const leftovers = path.join(workspace, 'timed-out.txt');
175
+ fs.renameSync(leftovers, path.join(options.dataDir, 'preserved-timeout.txt'));
176
+ await control(false, { clearHold: true, holdRunId: interrupted.runId });
177
+ assert.equal((await waitRun(queuedAfterTimeout.runId)).delivery, 'no-changes');
178
+ const pushProbe = await save({ title: '本机授权变更', toolId: 'probe', trigger: { kind: 'manual' }, delivery: 'push' });
179
+ const registry = JSON.parse(fs.readFileSync(configPath, 'utf8'));
180
+ fs.writeFileSync(configPath, JSON.stringify({ ...registry, allowPush: false }));
181
+ await fixture.restartWorkflow();
182
+ const candidate = await waitRun((await runNow(pushProbe)).runId);
183
+ assert.equal(candidate.delivery, 'candidate');
184
+ assert.equal(git(repo, 'show', candidate.commitSha + ':push-permission.txt'), 'This candidate should stay local');
185
+ assert.equal(upstream(), documented.commitSha);
186
+ assert.equal(git(repo, 'status', '--porcelain'), '');
187
+ assert.equal(git(repo, 'worktree', 'list', '--porcelain').split(/\r?\n/).filter(line => line.startsWith('worktree ')).length, 2);
188
+ console.log(JSON.stringify({
189
+ passed: ['real managed Git hook and Bridge', 'commit repair and bounded retry', 'busy and dirty guards',
190
+ 'persistent trigger dedupe', 'worktree reuse', 'schedule and serial remote baselines', 'true fast-forward push',
191
+ 'unpushed source stays local', 'push permission revocation', 'timeout hold and resume', 'JSON, origin and job permissions'],
192
+ workspace, reviewCommit: first.commitSha, remoteTip: documented.commitSha,
193
+ }));
194
+ } finally {
195
+ const closed = await fixture.close();
196
+ assert.ok(closed.every(item => item.status === 'fulfilled'), JSON.stringify(closed));
197
+ }
198
+ }
199
+
200
+ main().catch(error => { console.error(error.stack); process.exitCode = 1; });
@@ -4,11 +4,13 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const vm = require('node:vm');
6
6
  const source = fs.readFileSync(path.join(__dirname, '../../ui/product.js'), 'utf8');
7
- const code = source.slice(source.indexOf(' function frameContext('), source.indexOf(' function setView('));
8
- const messages = [], frame = { ready: false }, state = { epoch: 1, scope: 'project' };
7
+ const code = source.slice(source.indexOf(' function postTheme('), source.indexOf(' function setView('));
8
+ const messages = [], frame = { ready: false }, workflow = { ready: true };
9
+ const state = { epoch: 1, scope: 'project' };
9
10
  const project = { projectId: 'a', workspacePath: '/workspace', modules: { terminal: { projectId: 'context-a' } } };
10
- const ctx = vm.createContext({ state, frames: { terminal: frame }, activeProject: () => project,
11
- document: { documentElement: { dataset: { theme: 'light' } } }, frameVisible: () => true,
11
+ const ctx = vm.createContext({ state, frames: { terminal: frame, workflow }, activeProject: () => project,
12
+ document: { documentElement: { dataset: { theme: 'light' } } },
13
+ getComputedStyle: () => ({ getPropertyValue: name => name === '--accent' ? ' #3a775a ' : '' }),
12
14
  post: (_key, message) => messages.push(message) });
13
15
  vm.runInContext(code, ctx);
14
16
  vm.runInContext('frameContext("terminal")', ctx);
@@ -19,4 +21,7 @@ assert.equal(messages.filter(m => m.type === 'kb:select-project').length, 1, 'id
19
21
  state.epoch++;
20
22
  vm.runInContext('frameContext("terminal")', ctx);
21
23
  assert.equal(messages.filter(m => m.type === 'kb:select-project').length, 2, 'a real selection still reaches the iframe');
24
+ assert.ok(messages.filter(m => m.type === 'kb:theme').every(message => !message.palette), 'terminal theme message preserves its fields');
25
+ vm.runInContext('frameContext("workflow"); frameContext("workflow")', ctx);
26
+ assert.equal(messages.filter(m => m.palette?.accent === '#3a775a').length, 1, 'Workflow receives the palette with its context once');
22
27
  console.log('workbench-context-receipts-test PASS');
@@ -3,17 +3,17 @@
3
3
  "productFiles": {
4
4
  "ui/index.html": "55cbc1c20b5f88c7c21b50bc1b68d52ce3c94280f001567513e304d33c6933e1",
5
5
  "ui/knowledge-panel.html": "dfd85f15759472252d797853263e9da0054b251c56bb9ccdc8a75e6301334ca8",
6
- "ui/product.js": "427bc732f0b1f3a10719d7aa9ef6571098360c794cb81beb3585951164342c96",
6
+ "ui/product.js": "053791a9188ebc8229e362ce2d7cc0ea42abac9c4a312491d8854a203529ebcc",
7
7
  "ui/live-client.js": "0d81fa894c629bb839e1931fc3c5ebad4d831aae8232d6ce8c0f542e9e3559e8",
8
- "ui/product.css": "d1503958137a30368de24d7d03d662ccd0a15e15a45966cde4cd1bc19f991b06",
8
+ "ui/product.css": "904b367da6efa96a668d400735d08923a07a2df427f82176214ccfbc602ca361",
9
9
  "ui/favicon.svg": "c48be946b224112ebb0238b44263f7a61bda31e531afa895c2e9801c0ff24f32",
10
10
  "plugins/project-knowledge/hooks/claude.json": "d61510327e3e1facbb4c645228e9f50cad05a88b33d80c4c22e5ba9f8b9f5359",
11
11
  "plugins/project-knowledge/hooks/codex.json": "216e03c07295606ef6ebb2c4f669ad0d790b5e7c4f3f34600488033db75e4239",
12
12
  "plugins/project-knowledge/scripts/context-hook.cjs": "90d3fd7dcf965a17fdb1f6a88b80da25b943b06bd5030a8eb2fbc2ea39b174fa",
13
13
  "plugins/project-knowledge/scripts/mcp-launcher.cjs": "c9235eaf722ad011ce42d7a8416a77bef8e2a65e174f27b3d183f4b8f811f293",
14
- "plugins/project-knowledge/.claude-plugin/plugin.json": "f966f82e4c7d6a2f18c3b2527eeb5891e23477f55db744f0f2a69164108c06d4",
15
- "plugins/project-knowledge/.codex-plugin/plugin.json": "9bb74d0a87e7ebacb6996746ecac4ce487220fc4f07a95fcfab24f990d3f5a7e",
16
- "plugins/project-knowledge/.mcp.json": "e2da3aa3cf27027e02936ed391b21862fbdfd1f24f8d0f0bb8c3c9a4009cbca9",
14
+ "plugins/project-knowledge/.claude-plugin/plugin.json": "4df2c9c6002f25eef02c35870a77d1935f75807ce0e461d140c735101f15196e",
15
+ "plugins/project-knowledge/.codex-plugin/plugin.json": "39d4945045f8d5ba6360656b3dfeaff95ce20beaa11d30e7edee8af1269a24ec",
16
+ "plugins/project-knowledge/.mcp.json": "cacdfc3e4b357e367e30ae067a85f40fc8cd4268477910d3bffedf60f8c1103a",
17
17
  "ui/version-info.js": "01a82217b031de54b80d6c7974da9c70888c4c90a046bd4248a808f7989ddce7",
18
18
  "ui/version-info.css": "209fad8e42b661f72d2aba3280e1ca47768b5cefb776fe5459538d34fbad120f"
19
19
  },
@@ -288,6 +288,7 @@
288
288
  "src/memories.js": "4c170b0079ab7bba24e15c7aa50f77788b324f75a591ff3930c35dfa639ca9e7",
289
289
  "src/memory-eligibility.js": "0cc68807e0d113d52c2a2455f8f629c1e04e922b24813d02eaff9e7509208f2f",
290
290
  "src/memory-groups.js": "6dda17be0469b731c4d45c4aade7fc0c37fb6065cd924e7c7b03bd8e7e230c61",
291
+ "src/memory-migration.js": "89ca4e9ec0ecfe4839ff5e37b7e9a0fd6df51238b8b555051fed4b88db9bc4b8",
291
292
  "src/retrieval-policy.json": "4c2ce26e6c99330eb58c375da8f480ca9bc5f603b13e02712d66a267cd546e61",
292
293
  "src/retrieval-ranking.js": "43f61504bca5e5fd9fdaf7234e775b25dd97d2777ef4615394e8069c7371e75e",
293
294
  "src/retrieval.js": "6b6b057f58cd3d91088f3f402806c68c77cbc6079290d51307e8301f79069255",
@@ -314,33 +315,36 @@
314
315
  "src/store.js": "da3c36fea9a03d723836f2994adbdd64aaf840f519ee253e9900e253c805789b",
315
316
  "ui/app.css": "7ad370c269e60a7b5ec907d81a607b2d16bd07b2d7c22a81f102dab51eeb2889",
316
317
  "ui/app.js": "e9ecb0125d5f2a8bb30a58c4d278fe0737ee2540ecfb065f97f453495cfc792d",
317
- "ui/index.html": "ce3565cfefd4838b11d37a91a906ef26ca5a1834844fe3f7c897b56851a3c418",
318
- "src/memory-migration.js": "89ca4e9ec0ecfe4839ff5e37b7e9a0fd6df51238b8b555051fed4b88db9bc4b8"
318
+ "ui/index.html": "ce3565cfefd4838b11d37a91a906ef26ca5a1834844fe3f7c897b56851a3c418"
319
319
  }
320
320
  },
321
321
  "workflow": {
322
322
  "name": "@sanqianx/ai-coding-workflow",
323
323
  "installName": "@sanqianx/ai-coding-workflow",
324
- "version": "0.2.2",
324
+ "version": "0.2.3",
325
325
  "files": {
326
326
  "LICENSE": "c1b9df1275e769f3dbab000d1e457a2d4b0f28eb5da6c77e48dc37eeba202ed7",
327
327
  "README.md": "0ee483525831969a3855d942cbb2388d0c6a72e160bfa3c4fd33ee1bc729d1c7",
328
- "docs/contract.md": "ee869693eea33a3c3e763fc2008951bc5c888f2bcdb5a36c28c611064ca3f320",
329
- "package.json": "e767e75f8a8f091d25e0bd12f68c70085afa62cbe866068e243cc0c23b1146e2",
328
+ "docs/contract.md": "2b750eae9998f2ee19953769c56fb046e31cfa105ad2eee351ec63764bb3572f",
329
+ "package.json": "a2a86aabd55bc62c62d6c0953fd30cbedcac7ba9f33854298e843c47f29225c7",
330
330
  "src/bin.js": "1feb264c5f2df3302846d604a3a58c51d991d3736ee46c31d658e50978946618",
331
331
  "src/checks.js": "adffca98f9717a23bc6a611ecc387b15626b187a2e37a65cb658ac917cf3b1bb",
332
- "src/consumer.js": "2033895f7b536de8505bac00a3f88f717768adfdc9ae25b53c5e4bf75243f250",
332
+ "src/consumer.js": "0f25dcda53d25f82a8c83e637cb3de64e9e5b5014a74531383c8244c094d5500",
333
333
  "src/digests.js": "dd90e639d21c3b59a604e3280f214d0b4ed178e3c659c18b90d31b5479913332",
334
334
  "src/domain.js": "2edd3170002a592fc17f09456074b3c3c7d48dcd608efb64e9e76b314cd9a361",
335
335
  "src/errors.js": "1868330aa021b3dba5e92061dbb41e15a94f4cb0746f870c49aac4bf6119d708",
336
- "src/identity.js": "01d119c5f04c80860444224e2b74f732ca0ea4ccdaac9e8aa40cdc7f0ad6e84e",
337
- "src/server.js": "0cc18b28fd449d22aeed159cc7fae0e63d4acb31bba79ab5ef987eb8f8c05e4d",
336
+ "src/identity.js": "89a3023b84c82f37aa2647033632463940da48ae9b60cf329e3c29259cc6367c",
337
+ "src/maintenance-config.js": "4edb8f033894344b27cb7a57e5444259a90781e90009b54e34b939a4be7aa0b9",
338
+ "src/maintenance-runner.js": "2e8a38b597a6396abdea8c2ff015f80fe2f3587f6ef7b6a92fbed6feb4154c69",
339
+ "src/maintenance.js": "10e536c8bc534adbbe055e1fc94232d8b3c796891cc5c801c77f10909d118a2b",
340
+ "src/review-native.js": "47ca1ba2c424116bcdce66526d1bafb90f560b945f8b4fd58a6732e252aa7a7f",
341
+ "src/server.js": "e5db984d61025a22fbd729d3dc1ebcf6bfcdfedc499c33e1bcb89637e039ac38",
338
342
  "src/snapshots.js": "e4d3dca2d9193a536f9c24fb9f572aff58eb1031f2caac71ba8531d4b47db7b0",
339
343
  "src/store.js": "5c7d5e1415c326fec192bc2e6824b93abda1236e23b1304afe11f52754d96500",
340
344
  "src/tasks.js": "95a043d7c9a25cb266a9ec7f21b8502dc96e13b441b0e4c884c4f91996f558ed",
341
- "ui/app.css": "4d0fe1ce87abc26763ad312104312d2cd4a0363872ac7ba19a1f3c7adebbbb1f",
342
- "ui/app.js": "09494b513c66770e29d2c27287cd5cd1be3d539578708e6c38dfb1fd694df2e5",
343
- "ui/index.html": "3226838b7415beaeb559413195dcd3d53ec779b1cd987dcfc33e89c0405e6a17"
345
+ "ui/app.css": "c64fc049febb5a461bd902b08de491e030b53ffc0d2c6c8a5366ec0b88b27843",
346
+ "ui/app.js": "de7601e903486498719e8be749cc0d457a281a6f73867a999d63eb7171c579b2",
347
+ "ui/index.html": "23177779fefb0e0cc194c102df3a29a86559101944610c6f09587ef472ec5ae0"
344
348
  }
345
349
  }
346
350
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanqianx/project-knowledge",
3
- "version": "5.3.0",
3
+ "version": "5.3.1",
4
4
  "description": "Knowledge base manager with Git integration, AI-driven analysis, and bilingual (zh-CN/en-US) knowledge output",
5
5
  "main": "_site/server.js",
6
6
  "scripts": {
@@ -88,7 +88,7 @@
88
88
  "@modelcontextprotocol/sdk": "1.29.0",
89
89
  "@sanqianx/ai-coding-event-bridge-console": "0.7.5-rc.1",
90
90
  "@sanqianx/ai-coding-knowledge-engine": "0.4.1",
91
- "@sanqianx/ai-coding-workflow": "0.2.2",
91
+ "@sanqianx/ai-coding-workflow": "0.2.3",
92
92
  "@sanqianx/vector-hub": "1.0.8-rc.9",
93
93
  "buffer": "^6.0.3",
94
94
  "cheerio": "^1.2.0",
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "project-knowledge",
4
4
  "hooks": "./hooks/claude.json",
5
- "version": "5.3.0",
5
+ "version": "5.3.1",
6
6
  "description": "Read durable project decisions and implementation history from Project Knowledge.",
7
7
  "author": {
8
8
  "name": "SanQianX",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-knowledge",
3
- "version": "5.3.0",
3
+ "version": "5.3.1",
4
4
  "description": "Read durable project decisions and implementation history from Project Knowledge.",
5
5
  "author": {
6
6
  "name": "SanQianX",
@@ -8,7 +8,7 @@
8
8
  "const fs=require('fs'),path=require('path'),os=require('os');const PKG='@sanqianx/project-knowledge',SC='project-knowledge/integration-runtime/v1';let f='';const root=process.env.CLAUDE_PLUGIN_ROOT||process.env.PLUGIN_ROOT;if(root){f=path.join(root,'scripts','mcp-launcher.cjs');if(!fs.existsSync(f))f=''}if(!f){const dd=process.env.KB_DATA_DIR||path.join(os.homedir(),'.project-knowledge');try{const bp=path.join(dd,'integration-runtime.json');const st=fs.statSync(bp);if(st.isFile()&&st.size<=32768){const b=JSON.parse(fs.readFileSync(bp,'utf8'));if(b&&b.schema===SC&&b.packageName===PKG&&typeof b.packageRoot==='string'&&path.isAbsolute(b.packageRoot)){const c=path.join(b.packageRoot,'plugins','project-knowledge','scripts','mcp-launcher.cjs');const rr=fs.realpathSync(b.packageRoot),cr=fs.realpathSync(c);const rel=path.relative(rr,cr);if(rel&&rel!=='..'&&!rel.startsWith('..'+path.sep)&&!path.isAbsolute(rel)&&fs.statSync(cr).isFile())f=cr}}}catch(e){}}if(!f){console.error('[project-knowledge-mcp] 未能通过受信任插件根或已验证的安装绑定定位启动器,已停止;不访问网络,也不加载工作目录源码。');process.exit(127)}require(f);"
9
9
  ],
10
10
  "env": {
11
- "KB_PLUGIN_VERSION": "5.3.0"
11
+ "KB_PLUGIN_VERSION": "5.3.1"
12
12
  }
13
13
  }
14
14
  }
package/ui/product.css CHANGED
@@ -58,3 +58,23 @@ html[data-skin=steel][data-theme=dark]{--page:#171a1f;--surface:#20252d;--surfac
58
58
  .status-group{background:var(--accent-soft)}
59
59
  @media(max-width:900px){.memory-layout{grid-template-columns:170px minmax(0,1fr)}.grid2{grid-template-columns:1fr}.result-row{grid-template-columns:1fr}.result-row>small{text-align:left;max-width:none}}
60
60
  @media(max-width:640px){.memory-layout{display:block}.memory-folders{margin-bottom:16px}.memory-folders hr{display:none}.project-name{min-width:130px}.dragbar{display:none}}
61
+
62
+ @media (max-width: 800px) {
63
+ .app:has(#view-team.active) { grid-template-columns:minmax(0,1fr); grid-template-rows:auto minmax(0,1fr); }
64
+ .app:has(#view-team.active) > .sidebar { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; border-right:0; border-bottom:1px solid var(--line); }
65
+ .app:has(#view-team.active) .sidebar .brand { min-width:0; padding:9px 12px; }
66
+ .app:has(#view-team.active) .sidebar .brain-label { display:none; }
67
+ .app:has(#view-team.active) .sidebar nav { grid-column:1/-1; display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:3px; padding:0 8px 7px; }
68
+ .app:has(#view-team.active) .sidebar nav button { min-width:0; justify-content:center; gap:4px; padding:6px; white-space:nowrap; }
69
+ .app:has(#view-team.active) .sidebar .system-button { grid-column:2; grid-row:1; margin:0 9px 0 0; padding:6px 8px; }
70
+ .app:has(#view-team.active) .system-button small { display:none; }
71
+ .app:has(#view-team.active) .topbar { height:57px; gap:8px; padding:0 12px; }
72
+ .app:has(#view-team.active) .topbar > div:first-child { flex:1; min-width:0; }
73
+ .app:has(#view-team.active) #breadcrumb { display:block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
74
+ .app:has(#view-team.active) .topbar .spacer { display:none; }
75
+ .app:has(#view-team.active) .topbar select { width:min(48%,220px); }
76
+ }
77
+ @media (max-width: 560px) {
78
+ .app:has(#view-team.active) .sidebar nav { grid-template-columns:repeat(3,minmax(0,1fr)); }
79
+ .app:has(#view-team.active) .sidebar .system-button b { max-width:12ch; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
80
+ }
package/ui/product.js CHANGED
@@ -85,6 +85,17 @@
85
85
  }
86
86
  function on(id, event, callback) { $(id).addEventListener(event, e => Promise.resolve(callback(e)).catch(error => toast(error.message))); }
87
87
  function post(key, message) { const frame = frames[key]; if (frame.ready) $(frame.id).contentWindow.postMessage(message, location.origin); }
88
+ function postTheme(key) {
89
+ if (!frames[key].ready) return;
90
+ const root = document.documentElement;
91
+ const message = { type: 'kb:theme', theme: root.dataset.theme };
92
+ if (key === 'workflow') {
93
+ const style = getComputedStyle(root);
94
+ const tokens = ['page', 'surface', 'surface2', 'line', 'text', 'muted', 'accent', 'accent-soft', 'good', 'bad', 'bad-soft'];
95
+ message.palette = Object.fromEntries(tokens.map(token => [token, style.getPropertyValue('--' + token).trim()]));
96
+ }
97
+ post(key, message);
98
+ }
88
99
  function initializeFrame(key) { const frame = frames[key]; if (!frame.initialized) { $(frame.id).src = frame.url; frame.initialized = true; } }
89
100
  function frameVisible(key) { return key === 'engine' ? $('engineDialog').open : key === 'eventBridge' && state.view === 'activity' && state.activityTab === 'sessions'; }
90
101
  function frameContext(key) {
@@ -96,7 +107,7 @@
96
107
  const signature = JSON.stringify([state.epoch, ref || '', document.documentElement.dataset.theme, frameVisible(key)]);
97
108
  if (frame.contextSignature === signature) return;
98
109
  frame.contextSignature = signature;
99
- post(key, { type: 'kb:theme', theme: document.documentElement.dataset.theme });
110
+ postTheme(key);
100
111
  post(key, { type: 'kb:select-project', project: ref || '', projectId: project?.projectId || '', requestId: frame.requestId });
101
112
  post(key, { type: 'kb:visibility', visible: frameVisible(key) });
102
113
  }
@@ -1742,7 +1753,7 @@
1742
1753
  }
1743
1754
  });
1744
1755
  on('projectSelect', 'change', e => selectProject(e.target.value));
1745
- on('themeToggle', 'click', () => { document.documentElement.dataset.theme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark'; localStorage.setItem('kb.theme', document.documentElement.dataset.theme); applyAppearance(); Object.keys(frames).forEach(key => post(key, { type: 'kb:theme', theme: document.documentElement.dataset.theme })); void pushKnowledgeToPanel(); });
1756
+ on('themeToggle', 'click', () => { document.documentElement.dataset.theme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark'; localStorage.setItem('kb.theme', document.documentElement.dataset.theme); applyAppearance(); Object.keys(frames).filter(key => key !== 'workflow').forEach(postTheme); void pushKnowledgeToPanel(); });
1746
1757
  const appearanceTokens = ['page','surface','surface2','surface3','line','text','muted','faint','nav','accent','accent-soft','good','bad','bad-soft'];
1747
1758
  const appearanceDefaults = {
1748
1759
  pure: {
@@ -1775,6 +1786,7 @@
1775
1786
  const theme = root.dataset.theme === 'dark' ? 'dark' : 'light';
1776
1787
  for (const token of appearanceTokens) root.style.removeProperty(`--${token}`);
1777
1788
  for (const [token, value] of Object.entries(appearance.overrides[theme] || {})) if (appearanceTokens.includes(token)) root.style.setProperty(`--${token}`, value);
1789
+ postTheme('workflow');
1778
1790
  }
1779
1791
  function syncAppearanceControls() {
1780
1792
  if (!$('skinPreset')) return;