holohq 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +145 -0
  3. package/README.md +144 -2
  4. package/bin/holohq.js +12 -0
  5. package/dist/server/server/actions/clone.js +36 -0
  6. package/dist/server/server/actions/newProject.js +40 -0
  7. package/dist/server/server/actions/publish.js +22 -0
  8. package/dist/server/server/app.js +46 -0
  9. package/dist/server/server/autostart.js +127 -0
  10. package/dist/server/server/autostartRun.js +96 -0
  11. package/dist/server/server/browser.js +24 -0
  12. package/dist/server/server/cache.js +24 -0
  13. package/dist/server/server/claude/floor.js +408 -0
  14. package/dist/server/server/claude/history.js +268 -0
  15. package/dist/server/server/claude/prompt.js +8 -0
  16. package/dist/server/server/cli/autostart.js +21 -0
  17. package/dist/server/server/cli/config.js +45 -0
  18. package/dist/server/server/cli/convention.js +51 -0
  19. package/dist/server/server/cli/io.js +1 -0
  20. package/dist/server/server/cli/main.js +129 -0
  21. package/dist/server/server/config.js +311 -0
  22. package/dist/server/server/demo/config.js +19 -0
  23. package/dist/server/server/demo/data.js +317 -0
  24. package/dist/server/server/demo/deps.js +36 -0
  25. package/dist/server/server/demo/floor.js +45 -0
  26. package/dist/server/server/demo/run.js +315 -0
  27. package/dist/server/server/demo/scan.js +21 -0
  28. package/dist/server/server/domain/home.js +85 -0
  29. package/dist/server/server/domain/journal.js +33 -0
  30. package/dist/server/server/domain/sprint.js +9 -0
  31. package/dist/server/server/exec.js +12 -0
  32. package/dist/server/server/floor/attribute.js +74 -0
  33. package/dist/server/server/floor/evidence.js +39 -0
  34. package/dist/server/server/git/status.js +45 -0
  35. package/dist/server/server/github/gh.js +27 -0
  36. package/dist/server/server/github/labels.js +65 -0
  37. package/dist/server/server/github/project.js +58 -0
  38. package/dist/server/server/github/repos.js +17 -0
  39. package/dist/server/server/github/write.js +91 -0
  40. package/dist/server/server/guard.js +18 -0
  41. package/dist/server/server/index.js +9 -0
  42. package/dist/server/server/launch.js +168 -0
  43. package/dist/server/server/paths.js +26 -0
  44. package/dist/server/server/preload.js +30 -0
  45. package/dist/server/server/projects/remote.js +13 -0
  46. package/dist/server/server/projects/scan.js +79 -0
  47. package/dist/server/server/routes/actions.js +89 -0
  48. package/dist/server/server/routes/autostart.js +21 -0
  49. package/dist/server/server/routes/conversations.js +21 -0
  50. package/dist/server/server/routes/detail.js +24 -0
  51. package/dist/server/server/routes/floor.js +77 -0
  52. package/dist/server/server/routes/home.js +64 -0
  53. package/dist/server/server/routes/launch.js +79 -0
  54. package/dist/server/server/routes/projects.js +75 -0
  55. package/dist/server/server/routes/remotes.js +30 -0
  56. package/dist/server/server/routes/setup.js +114 -0
  57. package/dist/server/server/routes/write.js +129 -0
  58. package/dist/server/server/setup/tools.js +37 -0
  59. package/dist/server/server/skills.js +69 -0
  60. package/dist/server/server/start.js +166 -0
  61. package/dist/server/server/static.js +49 -0
  62. package/dist/server/shared/color.js +59 -0
  63. package/dist/server/shared/errors.js +88 -0
  64. package/dist/server/shared/ideas.js +36 -0
  65. package/dist/server/shared/labels.js +36 -0
  66. package/dist/server/shared/repoName.js +13 -0
  67. package/dist/server/shared/themes.js +120 -0
  68. package/dist/server/shared/tiers.js +15 -0
  69. package/dist/server/shared/types.js +1 -0
  70. package/dist/web/assets/Globe-ighOFp2V.js +4273 -0
  71. package/dist/web/assets/index-ByHbMQJl.js +11 -0
  72. package/dist/web/assets/index-DgR2KpYV.css +1 -0
  73. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  74. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  75. package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
  76. package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  77. package/dist/web/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  78. package/dist/web/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  79. package/dist/web/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  80. package/dist/web/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
  81. package/dist/web/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  82. package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  83. package/dist/web/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
  84. package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  85. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  86. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  87. package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  88. package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
  89. package/dist/web/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  90. package/dist/web/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
  91. package/dist/web/assets/rajdhani-devanagari-500-normal-BPH8g_s8.woff +0 -0
  92. package/dist/web/assets/rajdhani-devanagari-500-normal-B_DH_jja.woff2 +0 -0
  93. package/dist/web/assets/rajdhani-devanagari-600-normal-BtY48IV_.woff +0 -0
  94. package/dist/web/assets/rajdhani-devanagari-600-normal-DhS7ScYx.woff2 +0 -0
  95. package/dist/web/assets/rajdhani-devanagari-700-normal-BQQOj9BB.woff2 +0 -0
  96. package/dist/web/assets/rajdhani-devanagari-700-normal-DBRwWuxA.woff +0 -0
  97. package/dist/web/assets/rajdhani-latin-500-normal-ByNUCHrt.woff2 +0 -0
  98. package/dist/web/assets/rajdhani-latin-500-normal-DfvNI-Td.woff +0 -0
  99. package/dist/web/assets/rajdhani-latin-600-normal-CXCVEoA9.woff2 +0 -0
  100. package/dist/web/assets/rajdhani-latin-600-normal-Dx02qI2_.woff +0 -0
  101. package/dist/web/assets/rajdhani-latin-700-normal-BPDUZo87.woff2 +0 -0
  102. package/dist/web/assets/rajdhani-latin-700-normal-e0Uj8ZlN.woff +0 -0
  103. package/dist/web/assets/rajdhani-latin-ext-500-normal-CyRWJZ5B.woff +0 -0
  104. package/dist/web/assets/rajdhani-latin-ext-500-normal-DiyUS11w.woff2 +0 -0
  105. package/dist/web/assets/rajdhani-latin-ext-600-normal-BleIgkPp.woff +0 -0
  106. package/dist/web/assets/rajdhani-latin-ext-600-normal-C9ZjJQAt.woff2 +0 -0
  107. package/dist/web/assets/rajdhani-latin-ext-700-normal-BPaQ7tlD.woff +0 -0
  108. package/dist/web/assets/rajdhani-latin-ext-700-normal-S6aYESQK.woff2 +0 -0
  109. package/dist/web/index.html +13 -0
  110. package/package.json +74 -4
  111. package/scripts/autostart.ps1 +28 -0
  112. package/scripts/start-hidden.vbs +12 -0
  113. package/templates/en/CLAUDE.md +18 -0
  114. package/templates/en/README.md +3 -0
  115. package/templates/fr/CLAUDE.md +18 -0
  116. package/templates/fr/README.md +3 -0
@@ -0,0 +1,129 @@
1
+ import { errorBody } from '../../shared/errors.js';
2
+ import { clearCaches } from '../cache.js';
3
+ import { pickCurrentSprint } from '../domain/sprint.js';
4
+ import { GhError } from '../github/gh.js';
5
+ import { ensureLabels, repoLabelSet, standardLabels } from '../github/labels.js';
6
+ import { addToSprint, createIdea, createJournal, createSprint, findJournal, listOpenMilestones, setIdeaLabels } from '../github/write.js';
7
+ import { getProject } from './projects.js';
8
+ /** Requête mal formée (400) : le code et les variables servent à l'interface. */
9
+ class BadRequest extends Error {
10
+ code;
11
+ vars;
12
+ constructor(code, vars) {
13
+ super(code);
14
+ this.code = code;
15
+ this.vars = vars;
16
+ }
17
+ }
18
+ const EFFORTS = ['S', 'M', 'L'];
19
+ const IMPACTS = ['high', 'medium', 'low'];
20
+ async function body(c) {
21
+ try {
22
+ const b = await c.req.json();
23
+ return b && typeof b === 'object' ? b : {};
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ function text(v, field, required, label = false) {
30
+ if (v === undefined || v === null || v === '') {
31
+ if (required)
32
+ throw new BadRequest('fieldRequired', { field });
33
+ return undefined;
34
+ }
35
+ if (typeof v !== 'string')
36
+ throw new BadRequest('fieldInvalid', { field });
37
+ const t = v.trim();
38
+ if (!t && required)
39
+ throw new BadRequest('fieldRequired', { field });
40
+ if (t.length > 200 || (label ? /[\r\n,]/ : /[\r\n]/).test(t))
41
+ throw new BadRequest('fieldInvalid', { field });
42
+ return t || undefined;
43
+ }
44
+ function ideaLabels(b) {
45
+ const out = {};
46
+ const theme = text(b.theme, 'theme', false, true);
47
+ if (theme && theme.length > 44)
48
+ throw new BadRequest('themeTooLong');
49
+ if (theme)
50
+ out.theme = theme;
51
+ if (b.effort !== undefined && b.effort !== null && b.effort !== '') {
52
+ if (typeof b.effort !== 'string' || !EFFORTS.includes(b.effort))
53
+ throw new BadRequest('fieldInvalid', { field: 'effort' });
54
+ out.effort = b.effort;
55
+ }
56
+ if (b.impact !== undefined && b.impact !== null && b.impact !== '') {
57
+ if (typeof b.impact !== 'string' || !IMPACTS.includes(b.impact))
58
+ throw new BadRequest('fieldInvalid', { field: 'impact' });
59
+ out.impact = b.impact;
60
+ }
61
+ return out;
62
+ }
63
+ export function register(app, deps) {
64
+ const handle = (fn) => async (c) => {
65
+ const project = await getProject(c.req.param('id') ?? '', deps);
66
+ if (!project)
67
+ return c.json(errorBody('unknownProject'), 404);
68
+ if (!project.repo)
69
+ return c.json(errorBody('noRepo'), 400);
70
+ try {
71
+ const res = await fn(c, project.repo);
72
+ clearCaches();
73
+ return res;
74
+ }
75
+ catch (e) {
76
+ if (e instanceof BadRequest)
77
+ return c.json(errorBody(e.code, e.vars), 400);
78
+ if (e instanceof GhError)
79
+ return c.json((e.message ? errorBody('github', { detail: e.message }) : errorBody('githubUnreachable')), 502);
80
+ return c.json(errorBody('internal', { detail: e instanceof Error ? e.message : String(e) }), 500);
81
+ }
82
+ };
83
+ const issueNumber = (c) => {
84
+ const n = Number(c.req.param('n'));
85
+ if (!Number.isInteger(n) || n <= 0)
86
+ throw new BadRequest('invalidNumber');
87
+ return n;
88
+ };
89
+ app.post('/api/projects/:id/ideas', handle(async (c, repo) => {
90
+ const b = await body(c);
91
+ const title = text(b.title, 'title', true);
92
+ const labels = ideaLabels(b);
93
+ return c.json(await createIdea(deps.run, repo, await repoLabelSet(deps.run, repo, deps.config.labelSet), { title, ...labels }));
94
+ }));
95
+ app.post('/api/projects/:id/issues/:n/labels', handle(async (c, repo) => {
96
+ const n = issueNumber(c);
97
+ const labels = ideaLabels(await body(c));
98
+ await setIdeaLabels(deps.run, repo, await repoLabelSet(deps.run, repo, deps.config.labelSet), n, labels);
99
+ return c.json({ ok: true });
100
+ }));
101
+ app.post('/api/projects/:id/issues/:n/sprint', handle(async (c, repo) => {
102
+ const n = issueNumber(c);
103
+ const set = await repoLabelSet(deps.run, repo, deps.config.labelSet);
104
+ await ensureLabels(deps.run, repo, set, standardLabels(set).map((l) => l.name));
105
+ const sprint = pickCurrentSprint(await listOpenMilestones(deps.run, repo));
106
+ if (!sprint)
107
+ return c.json(errorBody('noSprint'), 409);
108
+ await addToSprint(deps.run, repo, n, sprint.title);
109
+ return c.json({ ok: true, sprint: sprint.title });
110
+ }));
111
+ app.post('/api/projects/:id/sprints', handle(async (c, repo) => {
112
+ const b = await body(c);
113
+ const title = text(b.title, 'title', true);
114
+ const dueOn = text(b.dueOn, 'dueOn', false);
115
+ const set = await repoLabelSet(deps.run, repo, deps.config.labelSet);
116
+ await ensureLabels(deps.run, repo, set, standardLabels(set).map((l) => l.name));
117
+ if (dueOn && (!/^\d{4}-\d{2}-\d{2}$/.test(dueOn) || Number.isNaN(Date.parse(dueOn))))
118
+ throw new BadRequest('invalidDate');
119
+ return c.json(await createSprint(deps.run, repo, { title, dueOn }));
120
+ }));
121
+ app.post('/api/projects/:id/journal', handle(async (c, repo) => {
122
+ const set = await repoLabelSet(deps.run, repo, deps.config.labelSet);
123
+ await ensureLabels(deps.run, repo, set, ['journal']);
124
+ const existing = await findJournal(deps.run, repo);
125
+ if (existing)
126
+ return c.json({ ...errorBody('journalExists'), ...existing }, 409);
127
+ return c.json(await createJournal(deps.run, repo, set));
128
+ }));
129
+ }
@@ -0,0 +1,37 @@
1
+ import { posix, win32 } from 'node:path';
2
+ /** Code 0 = vrai ; une exception (exécutable introuvable) compte comme faux. */
3
+ async function works(run, cmd, args) {
4
+ try {
5
+ return (await run(cmd, args)).code === 0;
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ }
11
+ export async function detectTools(run, platform = process.platform) {
12
+ // Sous Windows, npm installe claude.cmd : execFile ne le trouve pas, `where` oui.
13
+ const claudeCheck = platform === 'win32' ? works(run, 'where', ['claude']) : works(run, 'claude', ['--version']);
14
+ const [git, gh, ghAuth, claude] = await Promise.all([
15
+ works(run, 'git', ['--version']),
16
+ works(run, 'gh', ['--version']),
17
+ works(run, 'gh', ['auth', 'status']),
18
+ claudeCheck,
19
+ ]);
20
+ return { git, gh, ghAuth, claude };
21
+ }
22
+ /** Compte GitHub connecté à `gh`, ou null (lecture seule). */
23
+ export async function detectOwner(run) {
24
+ try {
25
+ const r = await run('gh', ['api', 'user', '-q', '.login']);
26
+ const login = r.stdout.trim();
27
+ return r.code === 0 && login ? login : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** Dossiers de projets usuels qui existent sur cette machine. */
34
+ export function suggestRoots(home, exists) {
35
+ const p = home.includes('\\') ? win32 : posix;
36
+ return ['Projects', 'projects', 'code', 'dev', 'src'].map((n) => p.join(home, n)).filter((d) => exists(d));
37
+ }
@@ -0,0 +1,69 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ /** Nom de skill : `reprise`, ou `plugin:skill` (un seul « : »). Source unique, partagée par la config et le lancement. */
4
+ export const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*(?::[A-Za-z0-9][A-Za-z0-9._-]*)?$/;
5
+ function unquote(v) {
6
+ const t = v.trim();
7
+ if (t.length >= 2 && ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))))
8
+ return t.slice(1, -1);
9
+ return t;
10
+ }
11
+ /** Lit `name` et `description` du frontmatter YAML ; null si absent ou incomplet. */
12
+ export function parseFrontmatter(text) {
13
+ const m = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
14
+ if (!m)
15
+ return null;
16
+ const fields = {};
17
+ for (const line of m[1].split(/\r?\n/)) {
18
+ const kv = /^(name|description):\s*(.*)$/.exec(line);
19
+ if (kv)
20
+ fields[kv[1]] = unquote(kv[2]);
21
+ }
22
+ if (!fields.name || !SKILL_NAME.test(fields.name))
23
+ return null;
24
+ return { name: fields.name, description: fields.description ?? '' };
25
+ }
26
+ async function readSkill(file, dirName, scope) {
27
+ try {
28
+ const fm = parseFrontmatter(await readFile(file, 'utf8'));
29
+ return fm && fm.name === dirName ? { ...fm, scope } : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ export async function listSkills(projectPath, cfg) {
36
+ const out = [];
37
+ const seen = new Set();
38
+ const dir = join(projectPath, '.claude', 'skills');
39
+ let names = [];
40
+ try {
41
+ names = (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
42
+ }
43
+ catch {
44
+ // pas de dossier de skills dans ce projet
45
+ }
46
+ for (const n of names) {
47
+ const s = await readSkill(join(dir, n, 'SKILL.md'), n, 'projet');
48
+ if (s && !seen.has(s.name)) {
49
+ seen.add(s.name);
50
+ out.push(s);
51
+ }
52
+ }
53
+ for (const n of Object.values(cfg.skills)) {
54
+ if (n.includes(':')) {
55
+ // Skill de plugin : pas de fichier à lire, on prend le nom configuré tel quel.
56
+ if (!seen.has(n)) {
57
+ seen.add(n);
58
+ out.push({ name: n, description: '', scope: 'plugin' });
59
+ }
60
+ continue;
61
+ }
62
+ const s = await readSkill(join(cfg.globalSkillsDir, n, 'SKILL.md'), n, 'global');
63
+ if (s && !seen.has(s.name)) {
64
+ seen.add(s.name);
65
+ out.push(s);
66
+ }
67
+ }
68
+ return out;
69
+ }
@@ -0,0 +1,166 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { appendFileSync, existsSync, mkdirSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { serve } from '@hono/node-server';
6
+ import { realAutostartDeps, runAutostart } from './autostartRun.js';
7
+ import { createApp } from './app.js';
8
+ import { openBrowser } from './browser.js';
9
+ import { createFloorReader } from './claude/floor.js';
10
+ import { claudeProjectsRoot, createHistoryReader } from './claude/history.js';
11
+ import { configPath, loadConfig, localeLang, portFromEnv } from './config.js';
12
+ import { DEMO_PORT } from './demo/config.js';
13
+ import { demoDeps } from './demo/deps.js';
14
+ import { run } from './exec.js';
15
+ import { dataDir, pkgPath } from './paths.js';
16
+ import { preloadAll } from './preload.js';
17
+ import { startToolsDetection } from './routes/setup.js';
18
+ import { detectOwner } from './setup/tools.js';
19
+ import { readStatic } from './static.js';
20
+ export { DEMO_PORT };
21
+ /** Sonde `/api/health` : seule une réponse `{ ok: true, app: 'holohq' }` est une instance HoloHQ ; `demo` donne son mode. */
22
+ export async function probeHoloHQ(port) {
23
+ try {
24
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
25
+ headers: { Host: `localhost:${port}` },
26
+ signal: AbortSignal.timeout(1000),
27
+ });
28
+ const body = (await res.json());
29
+ if (!res.ok || body?.ok !== true || body.app !== 'holohq')
30
+ return 'other';
31
+ return body.demo === true ? 'holohq-demo' : 'holohq';
32
+ }
33
+ catch (e) {
34
+ const code = e.cause?.code;
35
+ return code === 'ECONNREFUSED' ? 'free' : 'other';
36
+ }
37
+ }
38
+ const logDir = dataDir(process.env, process.platform, homedir());
39
+ const logFile = join(logDir, 'holohq.log');
40
+ /** En démo, rien n'est écrit sur le disque, pas même le log : la console seulement. */
41
+ let logToFile = true;
42
+ /** Log console + fichier holohq.log (sauf en démo) ; aussi utilisé par server/index.ts. */
43
+ export function log(msg) {
44
+ const line = `${new Date().toISOString()} ${msg}`;
45
+ console.log(line);
46
+ if (!logToFile)
47
+ return;
48
+ try {
49
+ mkdirSync(logDir, { recursive: true });
50
+ appendFileSync(logFile, line + '\n');
51
+ }
52
+ catch {
53
+ // le log fichier est best-effort
54
+ }
55
+ }
56
+ /** Dépendances réelles : config de l'utilisateur, vraies commandes, vrais lancements. */
57
+ function realDepsFor(opts, port) {
58
+ const file = configPath(process.env, process.platform, homedir());
59
+ const { config, firstRun, configError } = loadConfig(file, {
60
+ dev: opts.dev,
61
+ home: homedir(),
62
+ exists: existsSync,
63
+ port,
64
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
65
+ });
66
+ if (configError)
67
+ log(`Unreadable config, using defaults : ${configError}`);
68
+ const now = () => new Date();
69
+ return {
70
+ config,
71
+ setup: { file, firstRun, configError },
72
+ run,
73
+ now,
74
+ // Un seul lecteur par processus : il garde un cache par fichier.
75
+ conversations: createHistoryReader({ root: claudeProjectsRoot(process.env, homedir()), platform: process.platform, now }),
76
+ floor: createFloorReader({ root: claudeProjectsRoot(process.env, homedir()), now }),
77
+ spawnDetached: (cmd, args, cwd) => {
78
+ const child = spawn(cmd, args, { cwd, detached: true, stdio: 'ignore', windowsHide: false });
79
+ child.on('error', (e) => log(`Launch failed (${cmd}): ${e.message}`));
80
+ child.unref();
81
+ },
82
+ runAutostart: async (mode) => runAutostart(mode, await realAutostartDeps()),
83
+ };
84
+ }
85
+ /** À l'arrêt de la démo : le nombre de commandes restées sans réponse (aucune n'a été exécutée). */
86
+ function logMissesOnExit(run) {
87
+ process.once('exit', () => {
88
+ const distinct = [...new Set(run.misses)];
89
+ log(`Demo stopped: ${run.misses.length} unanswered command(s)${distinct.length ? ` : ${distinct.join(' | ')}` : ''}`);
90
+ });
91
+ // Sans ces gestionnaires, Ctrl+C tuerait le processus sans passer par 'exit'.
92
+ for (const sig of ['SIGINT', 'SIGTERM'])
93
+ process.once(sig, () => process.exit(0));
94
+ }
95
+ /** Démarre réellement le serveur sur `port` ; résout une fois à l'écoute. */
96
+ async function listen(opts, port) {
97
+ // Démo : config en mémoire (jamais le fichier de l'utilisateur), faux run, faux scanner, écritures bloquées.
98
+ const demo = opts.demo ? demoDeps({ lang: opts.lang ?? localeLang(Intl.DateTimeFormat().resolvedOptions().locale), port, dev: opts.dev }) : null;
99
+ const deps = demo ?? realDepsFor(opts, port);
100
+ const app = createApp(deps);
101
+ // Statique du paquet (indépendant du cwd et du lecteur), hors /api ; repli SPA sur index.html.
102
+ const webRoot = pkgPath('dist', 'web');
103
+ app.get('*', async (c, next) => {
104
+ if (c.req.path.startsWith('/api/'))
105
+ return next();
106
+ const hit = (await readStatic(webRoot, c.req.path)) ?? (await readStatic(webRoot, '/index.html'));
107
+ if (!hit)
108
+ return next();
109
+ return c.body(new Uint8Array(hit.body), 200, { 'content-type': hit.type });
110
+ });
111
+ // Compte GitHub détecté une fois au démarrage, gardé en mémoire (le fichier n'est écrit que par POST /api/config).
112
+ if (!deps.config.owner)
113
+ deps.config.owner = await detectOwner(deps.run);
114
+ await new Promise((resolve, reject) => {
115
+ const server = serve({ fetch: app.fetch, hostname: '127.0.0.1', port }, () => {
116
+ log(`HoloHQ${demo ? ' demo' : ''} listening on http://localhost:${port}`);
117
+ if (demo)
118
+ logMissesOnExit(demo.run);
119
+ void preloadAll(deps, log);
120
+ void startToolsDetection(deps);
121
+ resolve();
122
+ });
123
+ server.on('error', (err) => {
124
+ reject(err.code === 'EADDRINUSE'
125
+ ? new Error(`Port ${port} is already in use. Try: holohq --port <other port>`)
126
+ : new Error(`Server error: ${err.message}`));
127
+ });
128
+ });
129
+ }
130
+ const realDeps = { probe: probeHoloHQ, openUrl: (u) => openBrowser(u, log), listen, log };
131
+ export async function startServer(opts, deps = realDeps) {
132
+ if (opts.demo)
133
+ logToFile = false;
134
+ // Priorité : --port > démo (4243, jamais le port de dev/test de HOLOHQ_PORT) > HOLOHQ_PORT > port de la config.
135
+ let port = opts.port ?? (opts.demo ? DEMO_PORT : portFromEnv(process.env));
136
+ if (port === null) {
137
+ port =
138
+ loadConfig(configPath(process.env, process.platform, homedir()), {
139
+ dev: opts.dev,
140
+ home: homedir(),
141
+ exists: existsSync,
142
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
143
+ }).config.port;
144
+ }
145
+ const url = `http://localhost:${port}/`;
146
+ const state = await deps.probe(port);
147
+ if (state === 'other') {
148
+ throw new Error(`Port ${port} is in use by another program. Try: holohq --port <other port>`);
149
+ }
150
+ if (state === 'holohq' || state === 'holohq-demo') {
151
+ // Jamais réutiliser l'autre mode : on ouvrirait la démo en croyant voir ses vrais projets, ou l'inverse.
152
+ const runningDemo = state === 'holohq-demo';
153
+ if (runningDemo !== opts.demo) {
154
+ const what = runningDemo ? 'the HoloHQ demo' : 'HoloHQ (not in demo mode)';
155
+ throw new Error(`Port ${port} is used by ${what}. Try: holohq${opts.demo ? ' --demo' : ''} --port <other port>`);
156
+ }
157
+ deps.log(`HoloHQ${runningDemo ? ' demo' : ''} is already running on ${url}`);
158
+ if (opts.open)
159
+ deps.openUrl(url);
160
+ return { port, url, reused: true };
161
+ }
162
+ await deps.listen(opts, port);
163
+ if (opts.open)
164
+ deps.openUrl(url);
165
+ return { port, url, reused: false };
166
+ }
@@ -0,0 +1,49 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { extname, resolve, sep } from 'node:path';
3
+ const TYPES = {
4
+ '.html': 'text/html; charset=utf-8',
5
+ '.js': 'text/javascript; charset=utf-8',
6
+ '.mjs': 'text/javascript; charset=utf-8',
7
+ '.css': 'text/css; charset=utf-8',
8
+ '.json': 'application/json; charset=utf-8',
9
+ '.svg': 'image/svg+xml',
10
+ '.png': 'image/png',
11
+ '.jpg': 'image/jpeg',
12
+ '.ico': 'image/x-icon',
13
+ '.woff': 'font/woff',
14
+ '.woff2': 'font/woff2',
15
+ '.map': 'application/json; charset=utf-8',
16
+ '.txt': 'text/plain; charset=utf-8',
17
+ };
18
+ export function contentType(file) {
19
+ return TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
20
+ }
21
+ /** Chemin absolu du fichier demandé, ou null s'il sortirait de `root` (traversée, octets nuls, décodage invalide). */
22
+ export function resolveStaticPath(root, urlPath) {
23
+ let decoded;
24
+ try {
25
+ decoded = decodeURIComponent(urlPath);
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ if (decoded.includes('\0'))
31
+ return null;
32
+ const base = resolve(root);
33
+ const target = resolve(base, '.' + (decoded.startsWith('/') ? decoded : '/' + decoded));
34
+ if (target !== base && !target.startsWith(base + sep))
35
+ return null;
36
+ return target;
37
+ }
38
+ /** Lit un fichier statique sous `root` ; undefined s'il est absent ou interdit. */
39
+ export async function readStatic(root, urlPath) {
40
+ const file = resolveStaticPath(root, urlPath);
41
+ if (!file)
42
+ return undefined;
43
+ try {
44
+ return { body: await readFile(file), type: contentType(file) };
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
@@ -0,0 +1,59 @@
1
+ const HEX_RE = /^#([0-9a-fA-F]{6})$/;
2
+ /** `#rrggbb` uniquement (pas de forme courte, pas d'alpha, pas de nom) ; null sinon. */
3
+ export function parseHex(s) {
4
+ const m = HEX_RE.exec(s);
5
+ if (!m)
6
+ return null;
7
+ const n = parseInt(m[1], 16);
8
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
9
+ }
10
+ export function toHex(rgb) {
11
+ return '#' + rgb.map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('');
12
+ }
13
+ function rgbOf(s) {
14
+ const c = parseHex(s);
15
+ if (!c)
16
+ throw new Error(`invalid color: ${s}`);
17
+ return c;
18
+ }
19
+ /** Mélange linéaire de `a` vers `b` (t = 0 : a, t = 1 : b). */
20
+ export function mix(a, b, t) {
21
+ const x = rgbOf(a);
22
+ const y = rgbOf(b);
23
+ return toHex([0, 1, 2].map((i) => x[i] + (y[i] - x[i]) * t));
24
+ }
25
+ function luminance(s) {
26
+ const [r, g, b] = rgbOf(s).map((v) => {
27
+ const c = v / 255;
28
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
29
+ });
30
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
31
+ }
32
+ /** Ratio de contraste WCAG entre deux couleurs (1 à 21). */
33
+ export function contrast(a, b) {
34
+ const la = luminance(a);
35
+ const lb = luminance(b);
36
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
37
+ }
38
+ /**
39
+ * `fg` éclairci (fond sombre) ou assombri (fond clair) juste assez pour atteindre `min` contre `bg` ;
40
+ * inchangé s'il l'atteint déjà. Au pire, blanc ou noir.
41
+ * `alpha` < 1 : `fg` est affiché à cette opacité sur `bg`, et c'est la couleur vue qui doit atteindre `min`.
42
+ */
43
+ export function ensureContrast(fg, bg, min, alpha = 1) {
44
+ const passes = (c) => contrast(alpha < 1 ? mix(bg, c, alpha) : c, bg) >= min;
45
+ if (passes(fg))
46
+ return fg;
47
+ const target = contrast('#ffffff', bg) >= contrast('#000000', bg) ? '#ffffff' : '#000000';
48
+ // Recherche du plus petit mélange vers le blanc ou le noir qui passe le seuil (après arrondi en #rrggbb).
49
+ let lo = 0;
50
+ let hi = 1;
51
+ for (let i = 0; i < 20; i++) {
52
+ const mid = (lo + hi) / 2;
53
+ if (passes(mix(fg, target, mid)))
54
+ hi = mid;
55
+ else
56
+ lo = mid;
57
+ }
58
+ return mix(fg, target, hi);
59
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Erreurs de l'API : le serveur renvoie un code stable (+ variables), l'interface le traduit.
3
+ * `error` reste un texte anglais lisible (curl, logs, anciens clients).
4
+ */
5
+ export const ERROR_CODES = [
6
+ 'hostRefused', 'missingHeader', 'originRefused',
7
+ 'unknownProject', 'noRepo', 'noOwner',
8
+ 'invalidName', 'repoNameRequired',
9
+ 'skillMissing', 'skillUnknown', 'skillInvalid', 'sessionIdInvalid', 'promptInvalid', 'launchBodyInvalid', 'conversationUnknown',
10
+ 'editorNotFound', 'terminalNotFound', 'noTerminal',
11
+ 'pathRefused', 'pathControlChar', 'pathCmdMeta', 'pathSemicolon', 'pathBackslash',
12
+ 'noSprint', 'journalExists',
13
+ 'invalidJson', 'configInvalid', 'configWriteFailed', 'autostartFailed',
14
+ 'github', 'githubUnreachable', 'conflict', 'folderExists', 'repoExists', 'originExists',
15
+ 'badRequest', 'fieldRequired', 'fieldInvalid', 'themeTooLong', 'invalidNumber', 'invalidDate',
16
+ 'internal', 'serverUnreachable', 'demoMode',
17
+ ];
18
+ /** Raisons d'un réglage refusé (`vars.reason` de `configInvalid`). */
19
+ export const CONFIG_REASONS = ['absolutePath', 'leadingDash', 'controlChar', 'executable', 'language', 'skill', 'owner', 'projectsRootNotInRoots', 'appearance', 'excludeEntry'];
20
+ export const CONFIG_REASON_EN = {
21
+ absolutePath: 'absolute path expected',
22
+ leadingDash: 'must not start with "-"',
23
+ controlChar: 'must not contain a line break or control character',
24
+ executable: 'executable name or path without spaces or special characters expected',
25
+ language: '"en" or "fr" expected',
26
+ skill: 'invalid skill name or unknown key',
27
+ owner: 'invalid GitHub login',
28
+ projectsRootNotInRoots: 'must be one of the scanned folders',
29
+ appearance: 'unknown theme, invalid #rrggbb color or effects other than "full" / "subtle"',
30
+ excludeEntry: 'absolute path or folder name expected',
31
+ };
32
+ /** Texte anglais de chaque code ; `{name}` est remplacé par `vars.name`. */
33
+ export const ERROR_EN = {
34
+ hostRefused: 'Host refused',
35
+ missingHeader: 'Missing X-HoloHQ header',
36
+ originRefused: 'Origin refused',
37
+ unknownProject: 'Unknown project',
38
+ noRepo: 'No GitHub repository',
39
+ noOwner: 'GitHub owner unknown (gh not connected)',
40
+ invalidName: 'Invalid name (a-z, 0-9, hyphens)',
41
+ repoNameRequired: 'Repository name is required',
42
+ skillMissing: 'Skill missing',
43
+ skillUnknown: 'Unknown skill',
44
+ skillInvalid: 'Invalid skill name: launch refused',
45
+ sessionIdInvalid: 'Invalid conversation id: launch refused',
46
+ promptInvalid: 'Prompt contains a forbidden character: launch refused',
47
+ launchBodyInvalid: 'Invalid launch request: expected exactly one of skill, resume, continue, newSkill',
48
+ conversationUnknown: 'Unknown conversation for this project',
49
+ editorNotFound: 'Editor not found ({editor}): set it in Settings',
50
+ terminalNotFound: 'Terminal not found ({terminal}): set it in Settings',
51
+ noTerminal: 'No terminal found: set "terminal" in Settings',
52
+ pathRefused: 'Project path starts with "-": launch refused',
53
+ pathControlChar: 'Project path contains a line break or control character: launch refused',
54
+ pathCmdMeta: 'Project path contains a special character for cmd.exe (& | < > ^ % ! "): launch refused',
55
+ pathSemicolon: 'Project path contains ";": launch refused (Windows Terminal command separator)',
56
+ pathBackslash: 'Project path contains "\\": launch refused on macOS',
57
+ noSprint: 'No current sprint',
58
+ journalExists: 'Journal already exists',
59
+ invalidJson: 'Invalid JSON',
60
+ configInvalid: '{field}: {reason}',
61
+ configWriteFailed: 'Could not write the settings: {detail}',
62
+ autostartFailed: 'Could not change the autostart: {detail}',
63
+ github: 'GitHub error: {detail}',
64
+ githubUnreachable: 'GitHub unreachable',
65
+ conflict: 'Conflict',
66
+ folderExists: 'Folder {path} already exists',
67
+ repoExists: 'Repository {repo} already exists',
68
+ originExists: 'This project already has an origin remote',
69
+ badRequest: 'Bad request',
70
+ fieldRequired: '{field} is required',
71
+ fieldInvalid: '{field} is invalid',
72
+ themeTooLong: 'Theme is too long (44 characters max)',
73
+ invalidNumber: 'Invalid number',
74
+ invalidDate: 'Due date is invalid (YYYY-MM-DD)',
75
+ internal: 'Internal error: {detail}',
76
+ serverUnreachable: 'Server unreachable',
77
+ demoMode: 'Demo mode: this action is disabled.',
78
+ };
79
+ export function fillVars(text, vars) {
80
+ return text.replace(/\{(\w+)\}/g, (whole, name) => (vars && name in vars ? String(vars[name]) : whole));
81
+ }
82
+ /** Corps d'une réponse d'erreur : `error` en anglais (+ `detail` entre parenthèses), `code` et `vars` pour l'interface. */
83
+ export function errorBody(code, vars, detail) {
84
+ // `reason` d'un réglage : texte anglais de la raison.
85
+ const shown = vars && typeof vars.reason === 'string' && vars.reason in CONFIG_REASON_EN ? { ...vars, reason: CONFIG_REASON_EN[vars.reason] } : vars;
86
+ const error = fillVars(ERROR_EN[code], shown) + (detail ? ` (${detail})` : '');
87
+ return vars ? { error, code, vars } : { error, code };
88
+ }
@@ -0,0 +1,36 @@
1
+ import { parseImpact } from './labels.js';
2
+ /** Thème vide : « sans thème », distinct d'un thème nommé « Divers ». Le libellé affiché vient de ideas.noTheme. */
3
+ export const NO_THEME = '';
4
+ const labelValue = (labels, prefix) => {
5
+ const l = labels.find((x) => x.toLowerCase().startsWith(prefix));
6
+ return l ? l.slice(prefix.length).trim() : null;
7
+ };
8
+ export function classifyIdea(issue) {
9
+ const theme = labelValue(issue.labels, 'thème:') || labelValue(issue.labels, 'theme:') || NO_THEME;
10
+ const e = labelValue(issue.labels, 'effort:');
11
+ const impactLabel = issue.labels.find((x) => parseImpact(x));
12
+ const effort = e === 'S' || e === 'M' || e === 'L' ? e : null;
13
+ const impact = impactLabel ? parseImpact(impactLabel) : null;
14
+ let quadrant = 'a-classer';
15
+ if (impact && effort) {
16
+ // Impact high/medium = haut, low = bas ; effort S = gauche, M/L = droite.
17
+ const high = impact !== 'low';
18
+ const left = effort === 'S';
19
+ quadrant = high ? (left ? 'tout-de-suite' : 'gros-chantiers') : left ? 'bonus' : 'a-oublier';
20
+ }
21
+ return { ...issue, theme, effort, impact, quadrant };
22
+ }
23
+ export function groupMindMap(ideas) {
24
+ const map = new Map();
25
+ for (const idea of ideas)
26
+ map.set(idea.theme, [...(map.get(idea.theme) ?? []), idea]);
27
+ return [...map.entries()]
28
+ .map(([theme, list]) => ({ theme, ideas: list }))
29
+ .sort((a, b) => {
30
+ if (a.theme === NO_THEME)
31
+ return 1;
32
+ if (b.theme === NO_THEME)
33
+ return -1;
34
+ return b.ideas.length - a.ideas.length;
35
+ });
36
+ }