praxo-cli 0.0.0-stage → 0.1.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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +159 -2
  3. package/dist/app.js +75 -0
  4. package/dist/bin.js +21 -0
  5. package/dist/cli/commands/ai.command.js +189 -0
  6. package/dist/cli/commands/cmd.command.js +265 -0
  7. package/dist/cli/commands/completion.command.js +334 -0
  8. package/dist/cli/commands/config.command.js +27 -0
  9. package/dist/cli/commands/decision.command.js +287 -0
  10. package/dist/cli/commands/doctor.command.js +45 -0
  11. package/dist/cli/commands/project.command.js +24 -0
  12. package/dist/cli/commands/search.command.js +59 -0
  13. package/dist/cli/commands/sync.command.js +122 -0
  14. package/dist/cli/commands/transfer.command.js +148 -0
  15. package/dist/cli/index.js +156 -0
  16. package/dist/cli/output.js +133 -0
  17. package/dist/cli/prompts.js +68 -0
  18. package/dist/features/ai/client.js +238 -0
  19. package/dist/features/ai/output.js +7 -0
  20. package/dist/features/ai/providers.js +52 -0
  21. package/dist/features/ai/schemas.js +43 -0
  22. package/dist/features/ai/service.js +183 -0
  23. package/dist/features/commands/executor.js +54 -0
  24. package/dist/features/commands/repository.js +61 -0
  25. package/dist/features/commands/safety.js +154 -0
  26. package/dist/features/commands/service.js +254 -0
  27. package/dist/features/commands/template.js +153 -0
  28. package/dist/features/decisions/repository.js +53 -0
  29. package/dist/features/decisions/service.js +209 -0
  30. package/dist/features/decisions/stats.js +84 -0
  31. package/dist/features/decisions/status.js +7 -0
  32. package/dist/features/projects/repository.js +51 -0
  33. package/dist/features/projects/service.js +74 -0
  34. package/dist/features/sync/git.js +207 -0
  35. package/dist/features/sync/merge.js +194 -0
  36. package/dist/features/sync/repository.js +151 -0
  37. package/dist/features/sync/sanitizer.js +21 -0
  38. package/dist/features/sync/service.js +199 -0
  39. package/dist/features/sync/snapshot.js +230 -0
  40. package/dist/infrastructure/credentials/store.js +105 -0
  41. package/dist/infrastructure/database/client.js +41 -0
  42. package/dist/infrastructure/database/migrate.js +102 -0
  43. package/dist/infrastructure/database/schema.js +138 -0
  44. package/dist/infrastructure/git/detector.js +48 -0
  45. package/dist/shared/clipboard.js +19 -0
  46. package/dist/shared/config.js +163 -0
  47. package/dist/shared/doctor.js +47 -0
  48. package/dist/shared/errors.js +19 -0
  49. package/dist/shared/global-search.js +51 -0
  50. package/dist/shared/input.js +37 -0
  51. package/dist/shared/links.js +48 -0
  52. package/dist/shared/paths.js +14 -0
  53. package/dist/shared/query.js +10 -0
  54. package/dist/shared/redaction.js +54 -0
  55. package/dist/shared/search.js +39 -0
  56. package/dist/shared/sync-metadata.js +7 -0
  57. package/dist/shared/tags.js +91 -0
  58. package/dist/shared/transfer/archive.js +197 -0
  59. package/dist/shared/transfer/markdown.js +53 -0
  60. package/dist/shared/transfer/service.js +278 -0
  61. package/dist/tui/Workspace.js +121 -0
  62. package/dist/tui/components/AiPanel.js +200 -0
  63. package/dist/tui/components/Catalog.js +47 -0
  64. package/dist/tui/components/Confirm.js +28 -0
  65. package/dist/tui/components/Form.js +113 -0
  66. package/dist/tui/components/HelpModal.js +44 -0
  67. package/dist/tui/components/Inspection.js +28 -0
  68. package/dist/tui/components/KeyHints.js +7 -0
  69. package/dist/tui/components/SearchInput.js +31 -0
  70. package/dist/tui/components/SyncPanel.js +93 -0
  71. package/dist/tui/index.js +18 -0
  72. package/dist/tui/screens/Commands.js +383 -0
  73. package/dist/tui/screens/DecisionForms.js +117 -0
  74. package/dist/tui/screens/Decisions.js +260 -0
  75. package/dist/tui/screens/Lookup.js +96 -0
  76. package/dist/tui/theme.js +47 -0
  77. package/drizzle/0000_initial.sql +105 -0
  78. package/drizzle/0001_v11_sync.sql +117 -0
  79. package/drizzle/meta/0000_snapshot.json +735 -0
  80. package/drizzle/meta/0001_snapshot.json +867 -0
  81. package/drizzle/meta/_journal.json +20 -0
  82. package/package.json +77 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Praxo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # Praxo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Local-first Developer Workspace — A terminal workspace for actions and decisions.
4
+
5
+ Praxo 是一个本地优先的开发者终端工作台,由 **Command Vault(命令库)** 与 **Decision Log(决策库)** 两大核心模块组成。CLI 与 TUI 共用同一本地 SQLite 数据库,无需任何云端后端服务,开箱即用。
6
+
7
+ ## 安装
8
+
9
+ 环境要求:**Node.js 24**(`>=24.22.0 <25`)。
10
+
11
+ ```sh
12
+ npm install -g praxo-cli
13
+ # 或使用 pnpm
14
+ pnpm add -g praxo-cli
15
+ ```
16
+
17
+ 验证安装与本机环境:
18
+
19
+ ```sh
20
+ pxo --version
21
+ pxo doctor
22
+ ```
23
+
24
+ ## TUI 交互工作台
25
+
26
+ ```sh
27
+ pxo # 默认打开命令库(Command Vault)
28
+ pxo ui commands # 打开命令库
29
+ pxo ui decisions # 打开决策库(Decision Log)
30
+ ```
31
+
32
+ TUI 使用备用屏与增量渲染,退出时还原终端历史,宽终端自动双栏(`≥100` 列),窄终端自动单栏。顶部标签栏自动显示当前 Git 项目上下文、待复盘(Due)提醒、同步状态与 AI 状态。
33
+
34
+ | 分类 | 快捷键 | 说明 |
35
+ | ------ | --------------------------------------- | ------------------------------------------------ |
36
+ | 全局 | `1` / `2` / `Tab` | 切换 Commands / Decisions 模块 |
37
+ | 全局 | `Ctrl+K` / `Ctrl+P` | 跨模块全局实时搜索 |
38
+ | 全局 | `S` / `Ctrl+E` | 手动同步 / 打开 AI 助手配置 |
39
+ | 全局 | `?` / `q` / `Ctrl+C` | 快捷键帮助 / 退出 Praxo |
40
+ | 导航 | `↑` `↓` / `j` `k` / `g` `G` | 上下移动、跳至首项 / 末项 |
41
+ | 导航 | `→` / `←` / `Esc` | 窄屏详情 / 返回列表 / 清空筛选(`Esc` 永不误退) |
42
+ | 通用 | `/` / `f` | 展开内联实时搜索 / 条件筛选 |
43
+ | 通用 | `a`(`n`) / `e` / `d`(`Del`) / `t` / `l` | 新增 / 编辑 / 删除 / 标签 / 关联 |
44
+ | 命令库 | `Enter` / `y` | 渲染变量并安全复制到剪贴板 |
45
+ | 命令库 | `r` / `Ctrl+R` | 打开安全执行确认并在子进程执行 |
46
+ | 命令库 | `A` / `I` | AI 生成命令草稿 / AI 解释当前命令 |
47
+ | 决策库 | `r` / `h` / `s` | 对比复盘(当时 vs 现在)/ 复盘历史 / 统计看板 |
48
+ | 决策库 | `I` / `Ctrl+G` | AI 质疑或总结 / 复盘表单生成建议 |
49
+ | 表单 | `↑` `↓` / `Tab` / `Ctrl+S` | 切换字段 / 任意字段快捷保存 |
50
+
51
+ > **提示**:TUI 内执行子进程会在应用内实时展示输出(按 `Ctrl+C` 中止)。需要交互式键盘输入的命令请使用 `pxo command run`。
52
+
53
+ ## CLI 常用命令
54
+
55
+ 主命令使用完整名词(`command`、`decision`、`project`),同时提供常用短别名(`cmd`/`c`、`d`、`p`、`s`)。所有命令均支持全局 `--no-input`(同时尊重 `CI` 与 `PRAXO_NO_PROMPT`)以及 `--json` 输出;管道模式下空列表保持 0 行输出,方便脚本集成。
56
+
57
+ ### 命令库(Command Vault)
58
+
59
+ ```sh
60
+ pxo add 'lsof -i :{{port:3000}}' -n '查询端口占用' --type network --tier hot --sos --tag debug
61
+ pxo command list --tier hot # 短别名:pxo cmd ls / pxo c ls
62
+ pxo command search '端口' --json
63
+ pxo command render <id> --var port=8080
64
+ pxo command copy '端口' --var port=8080
65
+ pxo command run '端口' --var port=8080 --dry-run --json
66
+ pxo command run '端口' --var port=8080 -y
67
+ pxo command link add <cmd-id> <decision-id>
68
+ pxo command link list <cmd-id>
69
+ ```
70
+
71
+ - **模板变量**:`{{name}}`(必填)、`{{name:default}}`(默认值),通过可重复的 `--var name=value` 传入。
72
+ - **安全边界**:变量作为独立参数传递,避免注入;需要修改父 Shell 状态(如 `cd`、`export`)的命令会自动提示并降级为复制;高危命令无法通过 `-y`/`--yes` 跳过,必须在交互终端输入 `RUN` 确认。
73
+
74
+ ### 决策库(Decision Log)
75
+
76
+ ```sh
77
+ pxo decide '存储使用 SQLite' --reason '单文件便于备份' --confidence 85 --in 90d
78
+ pxo decision due --json # 短别名:pxo d due
79
+ pxo decision search 'SQLite' --scope global
80
+ pxo decision review add <id> --result '恢复验证通过' --rating accurate --lesson '迁移与恢复一起验证'
81
+ pxo decision review list <id>
82
+ pxo stats
83
+ pxo search SQLite
84
+ ```
85
+
86
+ - 默认复盘日为本地日期 90 天后,`Due` 状态按本地日期实时计算;复盘记录追加保存并保留当时的决策快照。
87
+
88
+ ### 导出、导入与 Shell 自动补全
89
+
90
+ ```sh
91
+ pxo project current
92
+ pxo project list
93
+ pxo export -o praxo.json
94
+ pxo export -f md --only decisions -o decisions.md
95
+ pxo export -o - | pxo import - --dry-run --json
96
+ pxo import praxo.json --merge
97
+ eval "$(pxo completion zsh)" # 支持 bash / zsh / fish / powershell
98
+ ```
99
+
100
+ - 交互终端(TTY)下自动按中英文列宽对齐表格;管道与 `--json` 输出保持纯净无色(尊重 `NO_COLOR`、`FORCE_COLOR`、`TERM=dumb`)。
101
+ - 全量覆盖导入(`import --replace`)仅允许交互终端二次确认,覆盖前会自动备份现有 SQLite 数据库。
102
+
103
+ ## 跨设备同步(Git SSH)
104
+
105
+ 先在 GitHub(或自建 Git 服务)创建一个**私有仓库**,确保本机已有可用的 SSH 访问(如 `ssh -T git@github.com` 正常),无需额外配置 Token 或登录 `gh`:
106
+
107
+ ```sh
108
+ pxo sync init owner/praxo-vault # 等价 git@github.com:owner/praxo-vault.git
109
+ # 也支持自定义 ~/.ssh/config 别名或完整 SSH URL:
110
+ # pxo sync init git@github-work:owner/praxo-vault.git
111
+
112
+ pxo sync --dry-run
113
+ pxo sync
114
+ pxo sync pull
115
+ pxo sync push
116
+ pxo sync status
117
+ pxo sync history
118
+ ```
119
+
120
+ - 每台设备链接同一私有仓库与分支(默认 `praxo-sync`),复用本机 `git` 与 SSH(支持 `ssh-agent` 与多账号别名),TUI 内按 `S` 手动同步。
121
+ - 发生冲突时可通过 `pxo sync conflicts` 查看并用 `pxo sync resolve <id> --keep local|remote` 处理,或在 TUI 冲突面板按 `L` / `R` 直接选择。
122
+ - 本机项目绝对路径、命令使用历史与凭据不会上传;推送前自动拦截疑似明文密钥(命令中的敏感值请使用 `{{name}}` 模板变量)。
123
+
124
+ ## AI 助手(BYOK)
125
+
126
+ 支持自带 API Key 接入 **DeepSeek** 与 **Gemini**,模型、端点与能力均已内置默认值:
127
+
128
+ ```sh
129
+ # 方式一:通过环境变量配置(默认模型:deepseek-chat / gemini-2.5-flash)
130
+ export PRAXO_DEEPSEEK_API_KEY="sk-..." # 或 PRAXO_GEMINI_API_KEY="AIza..."
131
+ pxo ai config deepseek # 或 pxo ai config gemini(可选 --model 覆盖默认模型)
132
+
133
+ # 方式二:写入系统凭据库(无需长期保留环境变量)
134
+ printf '%s' 'sk-...' | pxo ai config deepseek --key-stdin
135
+
136
+ pxo ai test
137
+ pxo ai generate '列出当前目录的文件' # 短别名:pxo ai gen
138
+ pxo ai explain 'git status --short' --no-stream
139
+ pxo ai challenge <决策ID>
140
+ pxo ai summarize --period 180d -p current # 短别名:pxo ai summary
141
+ ```
142
+
143
+ - TUI 内按 `Ctrl+E` 可随时打开或修改 AI 配置;所有 AI 生成的命令草稿均须本地风险校验与人工确认后才会保存,不会自动执行。
144
+ - 发送给 AI 前会自动检测并脱敏疑似密钥或凭据。
145
+
146
+ ## 本地数据路径
147
+
148
+ | 系统 | 默认数据库路径 |
149
+ | ------- | -------------------------------------------------------------------------- |
150
+ | Windows | `%LOCALAPPDATA%\praxo\praxo.sqlite` |
151
+ | macOS | `~/Library/Application Support/praxo/praxo.sqlite` |
152
+ | Linux | `$XDG_DATA_HOME/praxo/praxo.sqlite` 或 `~/.local/share/praxo/praxo.sqlite` |
153
+
154
+ - 运行 `pxo config path` 可查看当前本机的数据库、配置与缓存目录。
155
+ - 设置环境变量 `PRAXO_DATA_DIR` 可指定独立数据目录用于隔离试用或测试。
156
+ - 升级版本触发数据库迁移时,会在数据库同级 `backups` 目录自动保留迁移前备份。
157
+
158
+ ## License
159
+
160
+ [MIT](https://github.com/xingchen-m/Praxo/blob/main/LICENSE)
package/dist/app.js ADDED
@@ -0,0 +1,75 @@
1
+ import { openStore } from './infrastructure/database/client.js';
2
+ import { projectRepository } from './features/projects/repository.js';
3
+ import { projectService } from './features/projects/service.js';
4
+ import { aiService } from './features/ai/service.js';
5
+ import { syncRepository } from './features/sync/repository.js';
6
+ import { syncService } from './features/sync/service.js';
7
+ import { configService, instancePaths } from './shared/config.js';
8
+ import { credentials } from './infrastructure/credentials/store.js';
9
+ import { databasePath } from './shared/paths.js';
10
+ import { commandRepository } from './features/commands/repository.js';
11
+ import { commandService } from './features/commands/service.js';
12
+ import { execute } from './features/commands/executor.js';
13
+ import { copyToClipboard } from './shared/clipboard.js';
14
+ import { tagService } from './shared/tags.js';
15
+ import { decisionRepository } from './features/decisions/repository.js';
16
+ import { decisionService } from './features/decisions/service.js';
17
+ import { statistics } from './features/decisions/stats.js';
18
+ import { globalSearch } from './shared/global-search.js';
19
+ import { linkService } from './shared/links.js';
20
+ import { transferService } from './shared/transfer/service.js';
21
+ export function createApp(options = {}) {
22
+ const cwd = options.cwd ?? process.cwd();
23
+ const now = options.now ?? (() => new Date());
24
+ const path = options.path ?? databasePath();
25
+ const store = openStore(path, options.mode);
26
+ const credentialStore = credentials();
27
+ const write = (action) => store.native.transaction(action).immediate();
28
+ const config = configService(instancePaths(path, Boolean(options.path || process.env.PRAXO_DATA_DIR)), write);
29
+ const projects = projectService(projectRepository(store.db), write, cwd, options.mode === 'preview', now);
30
+ const tags = tagService(store.db, now);
31
+ const commands = commandService({
32
+ repository: commandRepository(store.db),
33
+ projects,
34
+ tags,
35
+ write,
36
+ now,
37
+ cwd,
38
+ copy: options.copy ?? copyToClipboard,
39
+ execute: options.execute ?? execute,
40
+ });
41
+ const decisions = decisionService({
42
+ repository: decisionRepository(store.db),
43
+ projects,
44
+ tags,
45
+ write,
46
+ now,
47
+ });
48
+ const stats = statistics(store.db, decisions, projects, now);
49
+ const ai = aiService({
50
+ config,
51
+ credentials: credentialStore,
52
+ commands,
53
+ decisions,
54
+ stats,
55
+ copy: options.copy ?? copyToClipboard,
56
+ fetcher: options.aiFetch,
57
+ });
58
+ return {
59
+ path,
60
+ cwd,
61
+ config,
62
+ credentials: credentialStore,
63
+ sync: syncService(syncRepository(store), config, now, projects.invalidate, options.syncTransport),
64
+ projects,
65
+ commands,
66
+ decisions,
67
+ stats,
68
+ ai,
69
+ tags: { list: tags.list },
70
+ search: globalSearch(commands, decisions),
71
+ links: linkService(store.db, commands, decisions, write, now),
72
+ transfer: transferService(store, path, now),
73
+ close: store.close,
74
+ };
75
+ }
package/dist/bin.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import { cli } from './cli/index.js';
3
+ import { useColor } from './cli/output.js';
4
+ import { exitCodeOf, messageOf } from './shared/errors.js';
5
+ try {
6
+ process.exitCode = await cli(process.argv.slice(2));
7
+ }
8
+ catch (error) {
9
+ const prefix = useColor(process.stderr) ? '\x1b[31mpxo:\x1b[0m' : 'pxo:';
10
+ process.stderr.write(`${prefix} ${messageOf(error)}\n`);
11
+ process.exitCode = exitCodeOf(error);
12
+ }
13
+ // Windows 的控制台读取在 TUI 或 readline 释放后仍可能挂起。
14
+ // 业务与数据库清理已结束,等输出写完再按原退出码结束进程。
15
+ if (process.platform === 'win32' && process.stdin.isTTY) {
16
+ const flush = (stream) => stream.writableLength === 0
17
+ ? Promise.resolve()
18
+ : new Promise((resolve) => stream.write('', () => resolve()));
19
+ await Promise.all([flush(process.stdout), flush(process.stderr)]);
20
+ process.exit(process.exitCode);
21
+ }
@@ -0,0 +1,189 @@
1
+ import { Argument, Option } from 'commander';
2
+ import { AI_PROVIDERS, providerPreset } from '../../features/ai/providers.js';
3
+ import { AppError } from '../../shared/errors.js';
4
+ import { canPrompt, output, positiveInt } from '../output.js';
5
+ import { field, pipedInput, prompt, requirePrompt } from '../prompts.js';
6
+ const PROVIDERS = AI_PROVIDERS;
7
+ const yes = (answer) => /^y(?:es)?$/iu.test(answer.trim());
8
+ /** 按当前调用时的终端状态动态构造脱敏确认回调,避免模块加载期缓存过期 TTY 状态。 */
9
+ function redactionApprover(json) {
10
+ if (json || !canPrompt())
11
+ return undefined;
12
+ return (locations) => prompt(async (ask) => yes(await ask('Redacted sensitive values from ' +
13
+ locations.join(', ') +
14
+ '. Send the redacted request? [y/N] ')));
15
+ }
16
+ async function cancellable(operation) {
17
+ const abort = new AbortController();
18
+ const interrupt = () => abort.abort();
19
+ process.on('SIGINT', interrupt);
20
+ try {
21
+ return await operation(abort.signal);
22
+ }
23
+ finally {
24
+ process.off('SIGINT', interrupt);
25
+ }
26
+ }
27
+ /** 注册 `pxo ai` 辅助能力命令组。 */
28
+ export function registerAi(program, withApp) {
29
+ const ai = program.command('ai').description('Use a configured AI provider');
30
+ const providerOverrides = (command) => command
31
+ .addOption(new Option('--provider <name>', 'Override AI provider').choices([...PROVIDERS]))
32
+ .option('--model <name>', 'Override AI model name');
33
+ ai.command('config')
34
+ .description('Configure AI provider (deepseek or gemini) and API key')
35
+ .addArgument(new Argument('[provider]', 'AI provider').choices([...PROVIDERS]))
36
+ .addOption(new Option('--provider <name>', 'AI provider').choices([...PROVIDERS]))
37
+ .option('--model <name>', 'Model identifier (defaults to provider preset)')
38
+ .option('--timeout-ms <ms>', 'Request timeout in milliseconds (100-300000)', (raw) => positiveInt(raw, '--timeout-ms'))
39
+ .option('--key-stdin', 'Store an API key piped on standard input')
40
+ .option('--json', 'Output JSON')
41
+ .action((positional, options) => withApp(async (app) => {
42
+ if (positional && options.provider && positional !== options.provider) {
43
+ throw new AppError(2, 'Specify the provider once, either as an argument or with --provider.');
44
+ }
45
+ const current = app.ai.settings();
46
+ let provider = positional ?? options.provider;
47
+ let model = options.model;
48
+ const hasInput = Boolean(provider || model || options.timeoutMs !== undefined || options.keyStdin);
49
+ if (!hasInput && !current) {
50
+ requirePrompt('Pass deepseek or gemini to configure AI in a script.');
51
+ [provider, model] = await prompt(async (ask) => {
52
+ const chosen = (await ask('Provider [deepseek | gemini, default deepseek]: ')).trim() ||
53
+ 'deepseek';
54
+ const presetModel = PROVIDERS.includes(chosen)
55
+ ? providerPreset(chosen).defaultModel
56
+ : 'deepseek-chat';
57
+ const chosenModel = (await ask(`Model [${presetModel}]: `)).trim();
58
+ return [chosen, chosenModel || undefined];
59
+ });
60
+ }
61
+ const settings = await app.ai.configure({
62
+ provider,
63
+ model,
64
+ timeoutMs: options.timeoutMs,
65
+ }, options.keyStdin ? await pipedInput('the API key') : undefined);
66
+ output(settings, options.json, () => 'AI configured for ' +
67
+ settings.provider +
68
+ ' / ' +
69
+ settings.model +
70
+ '. Run pxo ai test.');
71
+ }));
72
+ ai.command('test')
73
+ .description('Verify connectivity to the configured AI provider')
74
+ .option('--json', 'Output JSON')
75
+ .action((options) => withApp(async (app) => {
76
+ const result = await cancellable((signal) => app.ai.test({ signal }));
77
+ output(result, options.json, () => 'AI connection verified (' +
78
+ result.provider +
79
+ ' / ' +
80
+ result.model +
81
+ ', ' +
82
+ result.format +
83
+ ').');
84
+ }, 'preview'));
85
+ providerOverrides(ai
86
+ .command('generate <prompt>')
87
+ .alias('gen')
88
+ .description('Generate a command draft from natural language'))
89
+ .option('--json', 'Output JSON')
90
+ .action((description, options) => withApp(async (app) => {
91
+ const approve = redactionApprover(options.json);
92
+ const result = await cancellable((signal) => app.ai.generate(description, {
93
+ ...options,
94
+ signal,
95
+ approve,
96
+ }));
97
+ output(result, options.json, () => [
98
+ result.draft.name,
99
+ result.draft.template,
100
+ result.draft.note,
101
+ result.draft.platform + ' · ' + result.risk,
102
+ ]
103
+ .filter(Boolean)
104
+ .join('\n'));
105
+ if (options.json || !canPrompt())
106
+ return;
107
+ await prompt(async (ask) => {
108
+ if (!yes(await ask('Keep this draft for saving? [y/N] ')))
109
+ return;
110
+ let draft = result.draft;
111
+ if (yes(await ask('Edit the draft first? [y/N] '))) {
112
+ draft = {
113
+ ...draft,
114
+ name: (await field(ask, 'Name', draft.name)) ?? draft.name,
115
+ template: (await field(ask, 'Command', draft.template)) ?? draft.template,
116
+ note: (await field(ask, 'Note', draft.note)) ?? draft.note,
117
+ type: (await field(ask, 'Type', draft.type)) ?? draft.type,
118
+ tags: (await field(ask, 'Tags (comma-separated)', draft.tags.join(',')))
119
+ ?.split(',')
120
+ .map((tag) => tag.trim())
121
+ .filter(Boolean) ?? draft.tags,
122
+ };
123
+ }
124
+ const final = app.ai.assessDraft(draft);
125
+ if (!yes(await ask('Save ' + final.draft.name + '? [y/N] ')))
126
+ return;
127
+ const danger = !final.danger ||
128
+ (await ask(final.risk + ' Type SAVE to confirm this draft: ')) === 'SAVE';
129
+ const saved = app.ai.saveDraft(draft, true, danger);
130
+ process.stdout.write('Saved ' + saved.id + '.\n');
131
+ });
132
+ }, options.json || !canPrompt() ? 'preview' : 'write'));
133
+ providerOverrides(ai.command('explain <command>').description('Explain a shell command without executing it'))
134
+ .option('--no-stream', 'Disable streaming and print the complete explanation at once')
135
+ .option('--json', 'Output JSON')
136
+ .action((command, options) => withApp(async (app) => {
137
+ const approve = redactionApprover(options.json);
138
+ const stream = options.stream && !options.json;
139
+ const result = await cancellable((signal) => app.ai.explain(command, { ...options, signal, approve }, stream ? (chunk) => process.stdout.write(chunk) : undefined));
140
+ if (stream) {
141
+ process.stdout.write('\n');
142
+ }
143
+ else {
144
+ output({ command, explanation: result }, options.json, () => result);
145
+ }
146
+ }, 'preview'));
147
+ ai.command('challenge <id>')
148
+ .description("Generate a devil's advocate critique for a decision")
149
+ .option('--json', 'Output JSON')
150
+ .action((id, options) => withApp(async (app) => {
151
+ const approve = redactionApprover(options.json);
152
+ const result = await cancellable((signal) => app.ai.challenge(id, { signal, approve }));
153
+ output({ id, challenge: result }, options.json, () => result);
154
+ if (!options.json &&
155
+ canPrompt() &&
156
+ (await prompt(async (ask) => yes(await ask('Save as an AI note? [y/N] '))))) {
157
+ app.ai.saveChallenge(id, result, true);
158
+ }
159
+ }, !options.json && canPrompt() ? 'write' : 'preview'));
160
+ ai.command('review <id>')
161
+ .description('Suggest a review rating and lesson for a decision')
162
+ .option('--result-stdin', 'Read the observed actual result from standard input')
163
+ .option('--json', 'Output JSON')
164
+ .action((id, options) => withApp(async (app) => {
165
+ const approve = redactionApprover(options.json);
166
+ const actual = options.resultStdin
167
+ ? await pipedInput('the actual result')
168
+ : await (async () => {
169
+ requirePrompt('Use --result-stdin to provide the actual result in a script.');
170
+ return prompt((ask) => ask('Actual result: '));
171
+ })();
172
+ const result = await cancellable((signal) => app.ai.review(id, actual, { signal, approve }));
173
+ output(result, options.json, () => result.rating + '\n' + result.lesson);
174
+ }, 'preview'));
175
+ ai.command('summarize')
176
+ .alias('summary')
177
+ .description('Summarize aggregate decision statistics')
178
+ .addOption(new Option('--period <period>', 'Statistics window')
179
+ .choices(['30d', '90d', '180d', 'all'])
180
+ .default('180d'))
181
+ .option('-p, --project <id>', 'Filter by project ID or "current"')
182
+ .option('--json', 'Output JSON')
183
+ .action((options) => withApp(async (app) => {
184
+ const approve = redactionApprover(options.json);
185
+ const result = await cancellable((signal) => app.ai.summary(options.period, options.project, { signal, approve }));
186
+ output({ period: options.period, project: options.project ?? null, summary: result }, options.json, () => result);
187
+ }, 'preview'));
188
+ return ai;
189
+ }