@bnviking/dsh-bnv-workspace 0.0.0-stage → 1.0.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.
@@ -0,0 +1,5 @@
1
+ # Bundle patch: one Host row for the permanent-delete command; the browser half
2
+ # is declared by package.json `dsh.client`.
3
+ - insert:
4
+ - id: bnv-workspace
5
+ name: '@bnviking/dsh-bnv-workspace'
package/docs/DETAIL.md ADDED
@@ -0,0 +1,179 @@
1
+ # BNV WorkSpace — technical details
2
+
3
+ English · [Русский ниже](#русский)
4
+
5
+ ## Shape
6
+
7
+ BNV WorkSpace is one DSH bundle with two halves:
8
+
9
+ | Half | Entry | Responsibilities |
10
+ |---|---|---|
11
+ | Host | `index.js` (ESM) | registers the `/bnv-delete` command; reads `sessionPersistence`, `sessions`, `workspaceRegistry`; erases session log directories; emits `api-session/removed` |
12
+ | Client | `client.js` (browser artifact) | registers slots, renders UI, keeps settings in `localStorage`, calls the Host through `remote.commands` |
13
+ | Shared | `safety.js` (pure) | validates log paths and finds subagent descendants |
14
+
15
+ There is no build step: `client.js` is loaded as-is through `window.__ModuleLoader__`, and its module id must equal the package name.
16
+
17
+ ## Client slots
18
+
19
+ | Slot | Id | Role |
20
+ |---|---|---|
21
+ | `shell.overlay` | `bnv-overlay` | `<style>`, dialogs, toast |
22
+ | `settings.section` + `settings.section.icon` | `bnv-workspace-appearance` | settings page and its nav glyph |
23
+ | `sidebar.session.row.leading` | `bnv-chat-icon` | per-chat icon |
24
+ | `sidebar.session.action` (HOC) | `bnv-compact-topbar` | hides the shipped New session row in compact mode |
25
+ | `sidebar.workspaces.session.menu.item` | `bnv-appearance-session`, `bnv-delete-forever` | chat row menu items |
26
+ | `contextMenus` for `workspace`, `contextMenu.icon` | `bnv-workspace.row-actions`, `bnv-workspace.appearance`, `bnv-workspace.trash` | project header menu items and icons |
27
+ | `sidebar.brand.name` (dynamic) | no id, `priority: -1` | compact button row: New session, panel icons, Settings |
28
+ | `settings.launcher` (dynamic) | no id, `priority: -1` | captures `openSettings`; hides the shipped account launcher in compact mode |
29
+
30
+ The two dynamic registrations exist only while the compact top bar is selected; on “Default” they are disposed and the shipped wordmark/account row return.
31
+
32
+ ## State
33
+
34
+ One module-level store drives the UI:
35
+
36
+ ```js
37
+ { styles, icons, itemColors, topbar, dialog, notice }
38
+ ```
39
+
40
+ `useSnapshot()` subscribes components to `listeners`; every mutation goes through `update(patch)`. Persistence keys:
41
+
42
+ | Key | Schema |
43
+ |---|---|
44
+ | `dsh.bnv-workspace.styles.v2` | `{ chat: Style, project: Style }`; `Style = { case, font, weight, color, colorCustom, size, tracking }` |
45
+ | `dsh.bnv-workspace.icons.v1` | `{ sessions: { id: 'builtin:star' \| 'data:…' }, projects: { … } }` |
46
+ | `dsh.bnv-workspace.item-colors.v1` | `{ sessions: { id: '#rrggbb' }, projects: { … } }` |
47
+ | `dsh.bnv-workspace.general.v2` | `{ topbar: 'compact' \| 'default' }` |
48
+
49
+ `font` is `none`, `mono`, `serif`, or `family:<installed family>`. Compact is the default when the key is absent.
50
+
51
+ ## CSS pipeline
52
+
53
+ One `<style>` element contains the base CSS followed by generated rules:
54
+
55
+ ```text
56
+ CSS + nameCss(styles) + projectIconCss(icons) + itemColorCss(itemColors)
57
+ ```
58
+
59
+ Selectors target the stable row attributes:
60
+
61
+ - chat title: `[data-row-key="session:<id>"] > span:nth-child(2)`;
62
+ - project title: `[data-row-key="workspace:<id>"] > span:nth-child(3)`;
63
+ - per-row color rules are appended last, so they win over the shared color;
64
+ - project icons replace the folder cell through `mask` (built-in glyphs) or `background` (uploaded images).
65
+
66
+ ## Deletion
67
+
68
+ `/bnv-delete session <id> [ru|en]`
69
+ `/bnv-delete project <id> [ru|en]`
70
+
71
+ Chat flow: list snapshots → collect the chat and every descendant by `header.parentSession` → refuse if any of them is live → unpin/unarchive/detach from projects → `rm` each log directory → emit `api-session/removed` per id.
72
+
73
+ Project flow: read the workspace → collect `sessionIds` plus descendants → refuse if any is live → unpin/unarchive → detach from every workspace → `rm` log directories → delete the workspace record → emit `api-session/removed` per id.
74
+
75
+ Path safety: `safeSessionArtifact` accepts only `<root>/<project>/session-…/session[.vN].jsonl[.zstd]`, normalizes with `path.resolve`, and rejects anything else.
76
+
77
+ What remains after deletion: the project folder on disk, attachments, other plugins’ usage data, and search-index rows until DSH reconciles them.
78
+
79
+ ## Compact top bar
80
+
81
+ - The HOC returns a marker span; CSS hides the now-empty shipped New session row.
82
+ - Buttons are rendered inside `sidebar.brand.name`, which lives inside the brand button.
83
+ - Panel icons are read from live `sidebar.panellist` registrations (labels are thunks), rendered through the `sidebar.panel.icon` factory, and highlighted with `usePanelInfo`.
84
+ - Right alignment is measured at runtime: a `useLayoutEffect` shifts the button group with `translateX` to the brand button’s right edge (the shipped `brandIdentity` has a `transform`, which breaks absolute positioning).
85
+ - The shipped vertical panel list is hidden by a CSS rule scoped to `html[data-bnv-topbar="compact"]`; the collapsed rail keeps its icons.
86
+
87
+ ## Lifecycle
88
+
89
+ All registrations, intervals, and subscriptions return disposers. The workspace title rename (“Workspaces” → “Projects”) is a 300 ms poll that replaces the matching localized text inside `[data-sidebar-workspace-header]` and restores it on dispose. Locale dictionaries are registered under the `bnv-workspace` namespace; if DSH is not Russian, the chain falls back to English. Host code changes require a DSH restart; client changes require a page reload.
90
+
91
+ ---
92
+
93
+ ## Русский
94
+
95
+ ## Форма
96
+
97
+ BNV WorkSpace — один DSH-bundle из двух половин:
98
+
99
+ | Половина | Точка входа | Ответственность |
100
+ |---|---|---|
101
+ | Host | `index.js` (ESM) | команда `/bnv-delete`; читает `sessionPersistence`, `sessions`, `workspaceRegistry`; стирает каталоги журналов; emits `api-session/removed` |
102
+ | Client | `client.js` (браузерный артефакт) | регистрирует слоты, рисует UI, хранит настройки в `localStorage`, вызывает Host через `remote.commands` |
103
+ | Общий | `safety.js` (чистые функции) | проверка путей журналов и поиск подсессий |
104
+
105
+ Шага сборки нет: `client.js` грузится как есть через `window.__ModuleLoader__`, а id модуля обязан совпадать с именем пакета.
106
+
107
+ ## Слоты клиента
108
+
109
+ | Слот | id | Роль |
110
+ |---|---|---|
111
+ | `shell.overlay` | `bnv-overlay` | `<style>`, диалоги, тост |
112
+ | `settings.section` + `settings.section.icon` | `bnv-workspace-appearance` | страница настроек и её глиф в навигации |
113
+ | `sidebar.session.row.leading` | `bnv-chat-icon` | иконка чата |
114
+ | `sidebar.session.action` (HOC) | `bnv-compact-topbar` | в компакте скрывает штатную строку новой сессии |
115
+ | `sidebar.workspaces.session.menu.item` | `bnv-appearance-session`, `bnv-delete-forever` | пункты меню чата |
116
+ | `contextMenus` для `workspace`, `contextMenu.icon` | `bnv-workspace.row-actions`, `bnv-workspace.appearance`, `bnv-workspace.trash` | пункты меню проекта и их иконки |
117
+ | `sidebar.brand.name` (динамически) | без id, `priority: -1` | компактный ряд: новая сессия, иконки разделов, «Настройки» |
118
+ | `settings.launcher` (динамически) | без id, `priority: -1` | перехватывает `openSettings`; в компакте скрывает штатный аккаунт |
119
+
120
+ Обе динамические регистрации живут только при выбранной компактной шапке; при «Обычном» снимаются, и возвращаются вордмарк и аккаунт.
121
+
122
+ ## Состояние
123
+
124
+ UI питается одним модульным store:
125
+
126
+ ```js
127
+ { styles, icons, itemColors, topbar, dialog, notice }
128
+ ```
129
+
130
+ `useSnapshot()` подписывает компоненты на `listeners`; любое изменение идёт через `update(patch)`. Ключи хранения:
131
+
132
+ | Ключ | Схема |
133
+ |---|---|
134
+ | `dsh.bnv-workspace.styles.v2` | `{ chat: Style, project: Style }`; `Style = { case, font, weight, color, colorCustom, size, tracking }` |
135
+ | `dsh.bnv-workspace.icons.v1` | `{ sessions: { id: 'builtin:star' \| 'data:…' }, projects: { … } }` |
136
+ | `dsh.bnv-workspace.item-colors.v1` | `{ sessions: { id: '#rrggbb' }, projects: { … } }` |
137
+ | `dsh.bnv-workspace.general.v2` | `{ topbar: 'compact' \| 'default' }` |
138
+
139
+ `font` — `none`, `mono`, `serif` или `family:<установленное семейство>`. Если ключа нет, компакт включён по умолчанию.
140
+
141
+ ## CSS-конвейер
142
+
143
+ Один `<style>` содержит базовый CSS и сгенерированные правила:
144
+
145
+ ```text
146
+ CSS + nameCss(styles) + projectIconCss(icons) + itemColorCss(itemColors)
147
+ ```
148
+
149
+ Селекторы опираются на стабильные атрибуты строк:
150
+
151
+ - подпись чата: `[data-row-key="session:<id>"] > span:nth-child(2)`;
152
+ - подпись проекта: `[data-row-key="workspace:<id>"] > span:nth-child(3)`;
153
+ - персональные цвета идут последними и перекрывают общий цвет;
154
+ - иконки проекта заменяют ячейку папки через `mask` (встроенные глифы) или `background` (загруженные картинки).
155
+
156
+ ## Удаление
157
+
158
+ `/bnv-delete session <id> [ru|en]`
159
+ `/bnv-delete project <id> [ru|en]`
160
+
161
+ Чат: снимки списка → сам чат и все потомки по `header.parentSession` → отказ, если кто-то живой → снять закрепление/архив/привязку → `rm` каталогов → `api-session/removed` по каждому id.
162
+
163
+ Проект: запись workspace → `sessionIds` плюс потомки → отказ, если кто-то живой → снять закрепления/архивы → отвязать от всех проектов → `rm` каталогов → удалить запись проекта → `api-session/removed` по каждому id.
164
+
165
+ Безопасность пути: `safeSessionArtifact` принимает только `<root>/<project>/session-…/session[.vN].jsonl[.zstd]`, нормализует через `path.resolve` и всё остальное отвергает.
166
+
167
+ Что остаётся после удаления: папка проекта на диске, вложения, usage-данные других плагинов и строки поискового индекса до сверки DSH.
168
+
169
+ ## Компактная шапка
170
+
171
+ - HOC возвращает маркер; CSS скрывает опустевшую штатную строку новой сессии.
172
+ - Кнопки рендерятся в `sidebar.brand.name`, внутри кнопки бренда.
173
+ - Иконки разделов читаются из живых регистраций `sidebar.panellist` (ярлыки — thunk), рисуются через фабрику `sidebar.panel.icon` и подсвечиваются `usePanelInfo`.
174
+ - Правое выравнивание измеряется на месте: `useLayoutEffect` сдвигает группу `translateX` к правому краю кнопки бренда (у штатного `brandIdentity` есть `transform`, из-за которого абсолютное позиционирование не работает).
175
+ - Штатный вертикальный список скрыт правилом под `html[data-bnv-topbar="compact"]`; в свёрнутом рельсе иконки остаются.
176
+
177
+ ## Жизненный цикл
178
+
179
+ Все регистрации, интервалы и подписки возвращают disposer. Переименование «Рабочие пространства» → «Проекты» — опрос раз в 300 мс: подменяет совпадающий локализованный текст внутри `[data-sidebar-workspace-header]` и возвращает его при выгрузке. Словари локали регистрируются в неймспейсе `bnv-workspace`; если DSH не на русском, цепочка уходит в английский. Правки Host требуют перезапуска DSH, правки клиента — перезагрузки страницы.
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Sidebar names and permanent delete">
2
+ <rect width="64" height="64" rx="14" fill="#247bbf"/>
3
+ <text x="13" y="41" font-family="Segoe UI, Arial, sans-serif" font-size="27" font-weight="600" fill="#ffffff">A</text>
4
+ <path d="M35 25h15M39.5 25v-3.2h5V25M37 25l1.3 19h9.4L49 25M41.8 30v9.5M45.7 30v9.5"
5
+ fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Host half: one human command that erases a chat, or a project and every chat
3
+ * inside it, from disk. No DSH seam deletes stored session files, so this
4
+ * plugin removes the session-owned directory and then forgets every durable
5
+ * reference to the erased ids (workspace account, pin, archive).
6
+ *
7
+ * The Client passes its active language as the last argument, because Host
8
+ * command results are plain text and the Client shows them verbatim.
9
+ */
10
+ import { rm } from 'node:fs/promises'
11
+ import { descendantsOf, safeSessionArtifact } from './safety.js'
12
+
13
+ export const name = 'bnv-workspace'
14
+ export const inject = ['commands', 'sessions', 'sessionPersistence', 'workspaceRegistry']
15
+
16
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/
17
+ const PLAIN_ID = /^[A-Za-z0-9_-]{1,160}$/
18
+
19
+ const TEXT = {
20
+ en: {
21
+ usage: 'Usage: /bnv-delete session <id> | project <id>',
22
+ projectMissing: 'Project not found.',
23
+ openOne: 'This chat is open right now. Switch to another chat and try again.',
24
+ openMany: count => `An open chat is part of this deletion (${count}). Switch to another chat and try again.`,
25
+ chatDone: erased => `Chat deleted permanently: ${erased} log${erased === 1 ? '' : 's'} erased.`,
26
+ projectDone: (title, chats, erased) => `Project “${title}” deleted permanently: ${chats} chat${chats === 1 ? '' : 's'} erased, ${erased} log${erased === 1 ? '' : 's'}. The project folder on disk was left untouched.`,
27
+ },
28
+ ru: {
29
+ usage: 'Использование: /bnv-delete session <id> | project <id>',
30
+ projectMissing: 'Проект не найден.',
31
+ openOne: 'Этот чат сейчас открыт. Переключитесь на другой чат и повторите удаление.',
32
+ openMany: count => `Среди удаляемых есть открытый чат (${count}). Переключитесь на другой чат и повторите.`,
33
+ chatDone: erased => `Чат удалён навсегда: стёрто журналов — ${erased}.`,
34
+ projectDone: (title, chats, erased) => `Проект «${title}» удалён навсегда: стёрто чатов — ${chats}, журналов — ${erased}. Папка проекта на диске не тронута.`,
35
+ },
36
+ }
37
+
38
+ /** @param {import('@deepseek-ai/cordis').Context} ctx */
39
+ export function apply(ctx) {
40
+ ctx.effect(() => ctx.commands.register({
41
+ name: 'bnv-delete',
42
+ description: 'Permanently delete a chat or a project with every chat inside',
43
+ recordInput: false,
44
+ input: { hint: 'session <id> | project <id>' },
45
+ handler: invocation => run(ctx, invocation.rawInput),
46
+ }), 'bnv-workspace: permanent delete command')
47
+ }
48
+
49
+ /** @param {string} rawInput */
50
+ async function run(ctx, rawInput) {
51
+ const [verb, id, language] = String(rawInput ?? '').trim().split(/\s+/)
52
+ const text = language === 'ru' ? TEXT.ru : TEXT.en
53
+ if (verb === undefined || id === undefined || !SAFE_ID.test(id)) return fail(text.usage)
54
+ if (verb === 'session') return eraseChat(ctx, id, text)
55
+ if (verb === 'project') return eraseProject(ctx, id, text)
56
+ return fail(text.usage)
57
+ }
58
+
59
+ async function eraseChat(ctx, id, text) {
60
+ try {
61
+ const snapshots = await storedSessions(ctx)
62
+ const ids = [id, ...descendantsOf(snapshots, id)]
63
+ const open = ids.filter(candidate => ctx.sessions.get(candidate) !== undefined)
64
+ if (open.length > 0) return fail(openMessage(text, open.length))
65
+ // Detach before the log disappears: workspace membership is derived from
66
+ // the stored header, so a deleted session could keep a dangling id.
67
+ await forgetReferences(ctx, ids)
68
+ const erased = await eraseAll(ctx, ids)
69
+ for (const candidate of ids) ctx.emit('api-session/removed', candidate)
70
+ return ok(text.chatDone(erased))
71
+ } catch (error) {
72
+ return fail(messageOf(error))
73
+ }
74
+ }
75
+
76
+ async function eraseProject(ctx, id, text) {
77
+ try {
78
+ const registry = ctx.workspaceRegistry
79
+ const workspace = registry.get(id)
80
+ if (workspace === undefined) return fail(text.projectMissing)
81
+ const snapshots = await storedSessions(ctx)
82
+ const ids = new Set()
83
+ for (const root of workspace.sessionIds) {
84
+ ids.add(root)
85
+ for (const descendant of descendantsOf(snapshots, root)) ids.add(descendant)
86
+ }
87
+ const targets = [...ids]
88
+ const open = targets.filter(candidate => ctx.sessions.get(candidate) !== undefined)
89
+ if (open.length > 0) return fail(openMessage(text, open.length))
90
+ for (const candidate of targets) {
91
+ await registry.unpinSession(candidate)
92
+ await registry.unarchiveSession(candidate)
93
+ }
94
+ for (const workspaceRow of registry.list()) {
95
+ const members = new Set(workspaceRow.sessionIds)
96
+ for (const candidate of targets) {
97
+ if (members.has(candidate)) await workspaceRow.detachSession(candidate)
98
+ }
99
+ }
100
+ const erased = await eraseAll(ctx, targets)
101
+ await registry.delete(id)
102
+ for (const candidate of targets) ctx.emit('api-session/removed', candidate)
103
+ return ok(text.projectDone(workspace.title, targets.length, erased))
104
+ } catch (error) {
105
+ return fail(messageOf(error))
106
+ }
107
+ }
108
+
109
+ async function storedSessions(ctx) {
110
+ const snapshots = await ctx.sessionPersistence.list()
111
+ return new Map(snapshots.map(snapshot => [snapshot.header.id, snapshot]))
112
+ }
113
+
114
+ async function eraseAll(ctx, ids) {
115
+ let erased = 0
116
+ for (const id of ids) {
117
+ if (!PLAIN_ID.test(id)) continue
118
+ const snapshot = await ctx.sessionPersistence.stat(id)
119
+ const dir = safeSessionArtifact(snapshot?.location?.path)
120
+ if (dir === null) continue
121
+ await rm(dir, { recursive: true, force: true })
122
+ erased += 1
123
+ }
124
+ return erased
125
+ }
126
+
127
+ async function forgetReferences(ctx, ids) {
128
+ const registry = ctx.workspaceRegistry
129
+ for (const id of ids) {
130
+ await registry.unpinSession(id)
131
+ await registry.unarchiveSession(id)
132
+ }
133
+ for (const workspace of registry.list()) {
134
+ const members = new Set(workspace.sessionIds)
135
+ for (const id of ids) {
136
+ if (members.has(id)) await workspace.detachSession(id)
137
+ }
138
+ }
139
+ }
140
+
141
+ function openMessage(text, count) {
142
+ return count === 1 ? text.openOne : text.openMany(count)
143
+ }
144
+
145
+ function ok(text) {
146
+ return { kind: 'success', text }
147
+ }
148
+
149
+ function fail(text) {
150
+ return { kind: 'error', text }
151
+ }
152
+
153
+ function messageOf(error) {
154
+ return error instanceof Error ? error.message : String(error)
155
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Sidebar names and permanent delete",
4
+ "description": "Restyle chat and project names in the workspace sidebar, and permanently erase chats or projects together with every chat inside them."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Имена в сайдбаре и удаление навсегда",
4
+ "description": "Настраивает шрифт, цвет, толщину и регистр названий чатов и проектов в боковой панели и безвозвратно удаляет чаты или проекты вместе со всеми чатами внутри."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@bnviking/dsh-bnv-workspace",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Turns the DeepSeek Harness sidebar into a tidy workspace with styled names, per-row icons and colors, a compact top bar, and truly permanent chat and project deletion.",
5
+ "license": "MIT",
6
+ "author": "BNViking",
7
+ "private": false,
8
+ "keywords": ["dsh-plugin", "deepseek-harness", "sidebar", "workspace", "chat-management", "customization", "icons", "productivity"],
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/BNViking/dsh-bnv-workspace.git"
12
+ },
13
+ "homepage": "https://www.npmjs.com/package/@bnviking/dsh-bnv-workspace",
14
+ "bugs": {
15
+ "url": "https://github.com/BNViking/dsh-bnv-workspace/issues"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./index.js",
26
+ "./client": "./client.js",
27
+ "./locale/*.json": "./locale/*.json",
28
+ "./icon": "./icon.svg"
29
+ },
30
+ "files": [
31
+ "index.js",
32
+ "client.js",
33
+ "safety.js",
34
+ "cordis.patch.yml",
35
+ "locale/*.json",
36
+ "docs/",
37
+ "assets/",
38
+ "NOTICE",
39
+ "LICENSE",
40
+ "README.md",
41
+ "icon.svg"
42
+ ],
43
+ "dsh": {
44
+ "bundle": { "patch": "./cordis.patch.yml" },
45
+ "client": {
46
+ "platform": "web",
47
+ "immediately": true,
48
+ "inject": [
49
+ "@deepseek-ai/dsh-client-ui-workspace",
50
+ "@deepseek-ai/dsh-client-ui-context-menu"
51
+ ]
52
+ }
53
+ }
54
+ }
package/safety.js ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Pure helpers for permanent deletion: which stored file may be erased, and
3
+ * which persisted sessions hang below one session. Kept separate from the
4
+ * command so they can be checked without a Harness process.
5
+ */
6
+ import { basename, dirname, resolve } from 'node:path'
7
+
8
+ const SESSION_FILE = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/
9
+ const SESSION_DIR = /^session-[A-Za-z0-9._-]{1,180}$/
10
+
11
+ /**
12
+ * The session-owned directory to erase, or null when the path is not exactly
13
+ * one file inside a session directory (`<root>/<project>/<session>/session*.jsonl*`).
14
+ * @param {string} file - absolute stored log path.
15
+ * @returns {string | null} the directory to remove.
16
+ */
17
+ export function safeSessionArtifact(file) {
18
+ if (typeof file !== 'string' || file.length === 0) return null
19
+ if (!SESSION_FILE.test(basename(file))) return null
20
+ const dir = resolve(dirname(file))
21
+ if (!SESSION_DIR.test(basename(dir))) return null
22
+ return dir
23
+ }
24
+
25
+ /**
26
+ * Every stored session below one root, breadth-first, excluding the root.
27
+ * @param {Map<string, { header: { id: string, parentSession?: string } }>} byId - every stored snapshot by id.
28
+ * @param {string} rootId - the session whose descendants to collect.
29
+ * @returns {string[]} descendant ids.
30
+ */
31
+ export function descendantsOf(byId, rootId) {
32
+ const children = new Map()
33
+ for (const snapshot of byId.values()) {
34
+ const parent = snapshot.header.parentSession
35
+ if (parent === undefined) continue
36
+ const list = children.get(parent)
37
+ if (list === undefined) children.set(parent, [snapshot.header.id])
38
+ else list.push(snapshot.header.id)
39
+ }
40
+ const out = []
41
+ const stack = [...(children.get(rootId) ?? [])]
42
+ while (stack.length > 0) {
43
+ const id = stack.pop()
44
+ out.push(id)
45
+ stack.push(...(children.get(id) ?? []))
46
+ }
47
+ return out
48
+ }