@aiti-ai/aiti-git-ops 0.1.9

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 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="6" x2="6" y1="3" y2="15"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/></svg>
package/index.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * aiti-git-ops · Git 操作共享引擎扩展(方案 docs/aiti-git-ops-shared-plan.md M1)
3
+ *
4
+ * 零 UI、零 npm 运行时依赖的纯服务端引擎:
5
+ * - REST:POST /api/extensions/aiti-git-ops/git/*(§1.2 全表,cwd 走 JSON body 不落 URL)
6
+ * - services:ctx.services.provide("aiti-git-ops.api", {...}) 与 REST 同面(§1.6)
7
+ * - 事件:aiti-git-ops:changed:<hash(repoRoot)> 经 aiti-event-bus publish-local 发布
8
+ * (alive 保活门控——订阅方 POST /alive {types} 刷新,45s 无保活停推,§1.5 契约)
9
+ *
10
+ * 消费方:aiti-folder(提交面板/SyncBar)、session-manager(分支 chip 面板,M2)。
11
+ * 引擎缺席时消费方各自降级(optionalDependsOn 软依赖),本扩展不感知。
12
+ */
13
+ import { join } from "node:path";
14
+ import { mkdir } from "node:fs/promises";
15
+ import * as engine from "./git-engine.ts";
16
+
17
+ export default {
18
+ id: "aiti-git-ops",
19
+ name: "Git Ops(共享 Git 操作引擎)",
20
+ version: "0.1.0",
21
+ icon: "icons/git-branch.svg",
22
+ // 零 client bundle(同 aiti-echo-agent 等 10 个纯服务端扩展先例)
23
+ provides: ["aiti-git-ops.api"],
24
+
25
+ server: {
26
+ startup: async (ctx: any) => {
27
+ servicesCtx = ctx?.services ?? null;
28
+ // 数据分层(AGENTS §data-layering):审计→state(不可再生);隔离区→cache(可整体 rm -rf)
29
+ const configDir = (ctx?.configDir as string) || "";
30
+ const stateDir = (ctx?.stateDir as string) || (configDir ? join(configDir, "state") : "");
31
+ const cacheDir = (ctx?.cacheDir as string) || (configDir ? join(configDir, "cache") : "");
32
+ if (stateDir) await mkdir(join(stateDir, "aiti-git-ops"), { recursive: true }).catch(() => {});
33
+ if (cacheDir) await mkdir(join(cacheDir, "aiti-git-ops", "discarded"), { recursive: true }).catch(() => {});
34
+
35
+ engine.initGitEngine({
36
+ stateDir,
37
+ cacheDir,
38
+ source: "aiti-git-ops",
39
+ onChanged: (repo, kind, summary) => publish(engine.repoTopic(repo), { kind, summary, repo }),
40
+ });
41
+
42
+ // services 出口(§1.6):与 REST 同面,供服务端消费方与测试进程内直调
43
+ try {
44
+ ctx.services?.provide?.("aiti-git-ops.api", {
45
+ refs: (cwd: string) => engine.gitRefs(cwd),
46
+ log: (cwd: string, cursor: number) => engine.gitLog(cwd, cursor),
47
+ checkout: (cwd: string, ref: string, mode?: string) => engine.gitCheckout(cwd, ref, mode),
48
+ branchCreate: (cwd: string, name: string, from?: string, checkout?: boolean) => engine.gitBranchCreate(cwd, name, from, checkout),
49
+ branchDelete: (cwd: string, name: string) => engine.gitBranchDelete(cwd, name),
50
+ tags: (cwd: string) => engine.gitTags(cwd),
51
+ tagCreate: (cwd: string, name: string, ref?: string, opts?: { annotate?: boolean; message?: string }) => engine.gitTagCreate(cwd, name, ref, opts),
52
+ commitShow: (cwd: string, sha: string) => engine.gitCommitShow(cwd, sha),
53
+ commitDiff: (cwd: string, sha: string, paths: string[]) => engine.gitCommitDiff(cwd, sha, paths),
54
+ cherryPick: (cwd: string, sha: string, opts?: { abort?: boolean }) => engine.gitCherryPick(cwd, sha, opts),
55
+ stage: (cwd: string, paths: string[]) => engine.gitStage(cwd, paths),
56
+ unstage: (cwd: string, paths: string[]) => engine.gitUnstage(cwd, paths),
57
+ discard: (cwd: string, paths: string[]) => engine.gitDiscard(cwd, paths),
58
+ commit: (cwd: string, message?: string, amend?: boolean) => engine.gitCommit(cwd, message, amend),
59
+ planExecute: (cwd: string, groups: engine.PlanGroup[]) => engine.gitPlanExecute(cwd, groups),
60
+ planRollback: (cwd: string, baseHEAD: string) => engine.gitPlanRollback(cwd, baseHEAD),
61
+ stashList: (cwd: string) => engine.stashList(cwd),
62
+ stashFiles: (cwd: string, index: number) => engine.stashFiles(cwd, index),
63
+ stashPush: (cwd: string, opts: { message?: string; includeUntracked?: boolean; paths?: string[] }) => engine.stashPush(cwd, opts),
64
+ stashApply: (cwd: string, index: number, opts: { pop?: boolean; paths?: string[] }) => engine.stashApply(cwd, index, opts),
65
+ stashDrop: (cwd: string, index: number) => engine.stashDrop(cwd, index),
66
+ stashBranch: (cwd: string, index: number, name: string) => engine.stashBranch(cwd, index, name),
67
+ push: (cwd: string, opts: { remote?: string; branch?: string; setUpstream?: boolean }) => engine.gitPush(cwd, opts),
68
+ pull: (cwd: string, opts: { mode?: "ff-only" | "rebase" | "merge" }) => engine.gitPull(cwd, opts),
69
+ fetch: (cwd: string, remote?: string) => engine.gitFetch(cwd, remote),
70
+ });
71
+ } catch { /* services 不可用时 REST 仍可用 */ }
72
+ },
73
+
74
+ shutdown: async () => {},
75
+
76
+ api: async (req: Request, ctx: any) => {
77
+ const p: string[] = ctx?.path || [];
78
+ if (req.method === "OPTIONS") return new Response(null, { status: 204 });
79
+ if (req.method !== "POST") return json({ ok: false, error: "仅支持 POST" }, 405);
80
+
81
+ // alive 保活(§1.5):订阅方周期刷新关注的 topic,发布侧超时停推
82
+ if (p[0] === "alive") {
83
+ const body = await readBody(req);
84
+ for (const t of Array.isArray(body?.types) ? body.types : []) {
85
+ if (typeof t === "string" && t.startsWith("aiti-git-ops:changed:")) aliveMap.set(t, Date.now());
86
+ }
87
+ return json({ ok: true });
88
+ }
89
+
90
+ if (p[0] !== "git") return json({ ok: false, error: "not found: " + p.join("/") }, 404);
91
+ const body = await readBody(req);
92
+ const cwd = body?.cwd;
93
+ try {
94
+ switch (p[1]) {
95
+ case "refs": return json({ ok: true, ...(await engine.gitRefs(cwd)) });
96
+ case "log": return json({ ok: true, ...(await engine.gitLog(cwd, body?.cursor ?? 0)) });
97
+ case "checkout": return json(await engine.gitCheckout(cwd, body?.ref, body?.mode));
98
+ case "branch-create": return json(await engine.gitBranchCreate(cwd, body?.name, body?.from, body?.checkout !== false));
99
+ case "branch-delete": return json(await engine.gitBranchDelete(cwd, body?.name));
100
+ case "tags": return json({ ok: true, ...(await engine.gitTags(cwd)) });
101
+ case "tag-create": return json(await engine.gitTagCreate(cwd, body?.name, body?.ref, body));
102
+ case "commit-show": return json({ ok: true, ...(await engine.gitCommitShow(cwd, body?.sha)) });
103
+ case "commit-diff": return json({ ok: true, ...(await engine.gitCommitDiff(cwd, body?.sha, body?.paths)) });
104
+ case "cherry-pick": return json(await engine.gitCherryPick(cwd, body?.sha, body || {}));
105
+ case "stage": return json(await engine.gitStage(cwd, body?.paths));
106
+ case "unstage": return json(await engine.gitUnstage(cwd, body?.paths));
107
+ case "discard": return json(await engine.gitDiscard(cwd, body?.paths));
108
+ case "commit": return json(await engine.gitCommit(cwd, body?.message, !!body?.amend));
109
+ case "plan":
110
+ if (p[2] === "execute") return json(await engine.gitPlanExecute(cwd, body?.groups));
111
+ if (p[2] === "rollback") return json(await engine.gitPlanRollback(cwd, body?.baseHEAD));
112
+ break;
113
+ case "stash":
114
+ if (p[2] === "list") return json({ ok: true, ...(await engine.stashList(cwd)) });
115
+ if (p[2] === "files") return json({ ok: true, ...(await engine.stashFiles(cwd, body?.index)) });
116
+ if (p[2] === "push") return json(await engine.stashPush(cwd, body || {}));
117
+ if (p[2] === "apply") return json(await engine.stashApply(cwd, body?.index, body || {}));
118
+ if (p[2] === "drop") return json(await engine.stashDrop(cwd, body?.index));
119
+ if (p[2] === "branch") return json(await engine.stashBranch(cwd, body?.index, body?.name));
120
+ break;
121
+ case "push": return json(await engine.gitPush(cwd, body || {}));
122
+ case "pull": return json(await engine.gitPull(cwd, body || {}));
123
+ case "fetch": return json(await engine.gitFetch(cwd, body?.remote));
124
+ }
125
+ return json({ ok: false, error: "not found: git/" + p.slice(1).join("/") }, 404);
126
+ } catch (e) {
127
+ const err = e as engine.GitOpsFail;
128
+ return json(
129
+ { ok: false, error: err?.message || String(e), ...(err?.conflict ? { conflict: true, files: err.files } : {}) },
130
+ err?.status && Number.isInteger(err.status) ? err.status : 500,
131
+ );
132
+ }
133
+ },
134
+ },
135
+ };
136
+
137
+ // ── helpers ─────────────────────────────────────────────────────────────────
138
+
139
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
140
+ status,
141
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
142
+ });
143
+
144
+ const readBody = async (req: Request): Promise<any> => {
145
+ try { return await req.json(); } catch { return {}; }
146
+ };
147
+
148
+ // ── 事件发布(aiti-event-bus publish-local + aliveMap 保活停推,aiti-cmd 范式) ──
149
+
150
+ const ALIVE_TIMEOUT_MS = 45_000;
151
+ const aliveMap = new Map<string, number>();
152
+ let servicesCtx: { get?: (n: string) => { publish?: (t: string, d?: Record<string, unknown>) => void } | undefined } | null = null;
153
+
154
+ function publish(type: string, data: Record<string, unknown>) {
155
+ try {
156
+ const last = aliveMap.get(type);
157
+ if (last !== undefined && Date.now() - last > ALIVE_TIMEOUT_MS) return; // 订阅停止:停推
158
+ const svc = servicesCtx?.get?.("aiti-event-bus.publish-local") ?? servicesCtx?.get?.("aiti-event-bus.publish");
159
+ svc?.publish?.(type, data);
160
+ } catch { /* 事件失败不阻断 */ }
161
+ }
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@aiti-ai/aiti-git-ops",
3
+ "version": "0.1.9",
4
+ "description": "Git 操作共享引擎扩展 — 白名单写命令 / checkout 预检 / stash / plan 断点 / 审计 / changed topic(零 UI,folder 与 session-manager 消费)",
5
+ "soul": "一处写仓,处处安全。",
6
+ "aitiExtProtocol": "1.0",
7
+ "dependencies": {
8
+ "@aiti-ai/ext-shared": "^0.1.3"
9
+ },
10
+ "license": "MIT",
11
+ "contentHash": "51ba71f73db91720",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/aiti-ai/aiti-ai.git",
15
+ "directory": "extensions/aiti-git-ops"
16
+ },
17
+ "homepage": "https://github.com/aiti-ai/aiti-ai#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/aiti-ai/aiti-ai/issues"
20
+ }
21
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * _shared/reconcile-deps.mjs · 通知 pi-web 双实例对齐扩展共享依赖(各扩展 deploy.mjs 共用)
3
+ *
4
+ * 背景:扩展运行时依赖统一装进共享根 <webRoot>/node_modules(jiti 从扩展目录向上解析
5
+ * 自动命中;机制仿 pi 本体 npm: 包安装)。共享根的唯一写入方是 aiti-extman 的
6
+ * shared-deps reconcile——deploy.mjs 拷完文件后 POST 本通知即可,不在部署脚本里跑 npm。
7
+ *
8
+ * 用法(与 reload-instances 同款:允许失败,永不 throw、不影响 deploy 退出码):
9
+ * import { notifyReconcile } from "../../_shared/reconcile-deps.mjs";
10
+ * await notifyReconcile(); // 默认 "[deploy] " 前缀;建议在 reloadInstances() 之前调
11
+ *
12
+ * 失败无害:extman 在下一次 install/remove/reconcile-deps 时会自愈对齐;双实例各自
13
+ * reconcile 各自的 webRoot(~/.pi/web 与 ~/.pi/web-dev),互不相干。
14
+ */
15
+ import { buildInstances } from "./reload-instances.mjs";
16
+
17
+ export async function notifyReconcile(prefix = "[deploy] ") {
18
+ for (const inst of buildInstances()) {
19
+ if (inst.base === null) {
20
+ console.log(`${prefix}reconcile ${inst.name} 跳过:basePath 非法`);
21
+ continue;
22
+ }
23
+ try {
24
+ const r = await fetch(inst.base + "/api/extensions/aiti-extman/ops", {
25
+ method: "POST",
26
+ headers: { "content-type": "application/json" },
27
+ body: JSON.stringify({ action: "reconcile-deps", source: "deploy" }),
28
+ });
29
+ const body = await r.json().catch(() => null);
30
+ const err = body && body.deps && body.deps.error;
31
+ if (r.ok && body && body.ok) {
32
+ console.log(`${prefix}reconcile ${inst.name} → ✓(${Object.keys(body.deps?.deps || {}).length} 个共享依赖)`);
33
+ } else {
34
+ console.log(`${prefix}reconcile ${inst.name} → HTTP ${r.status} ⚠${err ? " " + err : "(extman 未就绪?下次安装时自动对齐)"}`);
35
+ }
36
+ } catch (e) {
37
+ const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
38
+ console.log(`${prefix}reconcile ${inst.name} 不可达(${cause})— 下次安装时自动对齐`);
39
+ }
40
+ }
41
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * _shared/reload-instances.mjs · pi-web 双实例热重载(各扩展 deploy.mjs 共用)
3
+ *
4
+ * dev 3001 / 生产 3002;端口可经 AITI_DEV_PORT / AITI_PROD_PORT 覆盖;
5
+ * basePath 双 env(AITI_DEV_BASE_PATH / AITI_PROD_BASE_PATH)按机器设值,
6
+ * 推荐值不带斜杠(48:dev 与 空;155:系统级 wdev 与 win)——git-bash 启动
7
+ * 原生程序时会把 / 开头的 env 值做 MSYS 路径转换(/wdev → D:/apps/Git/wdev)
8
+ * 致 URL 非法;不带斜杠则不触发转换。此处自动补 /(旧 /xxx 格式仍兼容),
9
+ * 兼容不了时提示 MSYS_NO_PATHCONV=1。
10
+ * 避免「server 端代码改了、实例没 reload 导致跑旧逻辑」。
11
+ *
12
+ * 用法(静态 import 或顶层 await import 均可):
13
+ * import { reloadInstances } from "../../_shared/reload-instances.mjs";
14
+ * await reloadInstances(); // 默认 "[deploy] " 前缀
15
+ */
16
+ const BASE_PATH_RE = /^\/[A-Za-z0-9._-]*$/;
17
+
18
+ function buildInstance(name, portEnv, portDefault, pathEnv, pathDefault) {
19
+ const origin = `http://127.0.0.1:${process.env[portEnv] || portDefault}`;
20
+ const raw = process.env[pathEnv];
21
+ if (raw === undefined || raw === null || String(raw).trim() === "") return { name, base: origin + pathDefault };
22
+ // 自动补 /:wdev → /wdev(推荐无斜杠格式,MSYS 不转换);/wdev → /wdev(旧格式兼容)
23
+ const p = "/" + String(raw).trim().replace(/^\/+|\/+$/g, "");
24
+ if (BASE_PATH_RE.test(p)) return { name, base: origin + p };
25
+ return { name, base: null, raw };
26
+ }
27
+
28
+ /** 双实例清单(dev/prod 各 {name, base});reload-instances 与 reconcile-deps 等共用。 */
29
+ export function buildInstances() {
30
+ return [
31
+ buildInstance("dev", "AITI_DEV_PORT", 3001, "AITI_DEV_BASE_PATH", "/dev"),
32
+ buildInstance("prod", "AITI_PROD_PORT", 3002, "AITI_PROD_BASE_PATH", ""),
33
+ ];
34
+ }
35
+
36
+ export async function reloadInstances(prefix = "[deploy] ") {
37
+ // 批次合并(deploy-all 场景):子条目部署脚本被注入 PI_WEB_DEFER_RELOAD=1 时不各自 reload,
38
+ // 由 deploy-all 在全部条目完成后统一执行一轮(N 条目 × 2 实例 → 2 次 POST)。
39
+ // 避免批量部署时的 reload 风暴(2026-09-15 实测:65 条目逐个 reload 把 dev 实例打满)。
40
+ // 单独跑某个扩展 deploy.mjs 不带该 env → 行为不变(部署完立即 reload)。
41
+ if (process.env.PI_WEB_DEFER_RELOAD === "1") {
42
+ console.log(`${prefix}reload 已 defer(PI_WEB_DEFER_RELOAD=1,由 deploy-all 收尾统一执行)`);
43
+ return;
44
+ }
45
+ // 允许失败:网络异常/非 2xx/服务未启动/env 非法一律只打提示,永不 throw——不影响 deploy 退出码
46
+ for (const inst of buildInstances()) {
47
+ if (inst.base === null) {
48
+ const msysHint = /[\\:]/.test(inst.raw) ? "——疑似 git-bash MSYS 路径转换,用 MSYS_NO_PATHCONV=1 前缀重跑" : "";
49
+ console.log(`${prefix}reload ${inst.name} 跳过:AITI_${inst.name.toUpperCase()}_BASE_PATH="${inst.raw}" 非法(须形如 /xxx 或留空)${msysHint}`);
50
+ continue;
51
+ }
52
+ try {
53
+ const r = await fetch(inst.base + "/api/extensions/reload", { method: "POST" });
54
+ console.log(`${prefix}reload ${inst.name} → HTTP ${r.status} ${r.ok ? "✓" : "⚠ 失败(请手动 POST /api/extensions/reload)"}`);
55
+ } catch (e) {
56
+ const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
57
+ console.log(`${prefix}reload ${inst.name} 不可达(${cause})— 需手动 POST /api/extensions/reload`);
58
+ }
59
+ }
60
+ }
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * aiti-git-ops · 部署到 ~/.pi/web{,-dev}/extensions/(零 client bundle,纯服务端)
4
+ *
5
+ * 生效:POST /api/extensions/reload(自动)。
6
+ */
7
+ import { copyFileSync, mkdirSync } from "node:fs";
8
+ import { resolve } from "node:path";
9
+ import { homedir } from "node:os";
10
+ import { deployCommit } from "../../_shared/deploy-commit.mjs";
11
+
12
+ const root = resolve(import.meta.dirname, "..");
13
+ const files = ["package.json", "index.ts", "git-engine.ts"];
14
+
15
+ const targets = [
16
+ resolve(homedir(), ".pi/web/extensions/aiti-git-ops"),
17
+ resolve(homedir(), ".pi/web-dev/extensions/aiti-git-ops"),
18
+ ];
19
+ for (const dir of targets) {
20
+ mkdirSync(dir, { recursive: true });
21
+ for (const f of files) copyFileSync(resolve(root, f), resolve(dir, f));
22
+ {
23
+ const { copyIcons } = await import("../../_shared/ext-icons-deploy.mjs");
24
+ copyIcons(resolve(dir, "icons"), ["git-branch"], { log: (m) => console.log("[deploy] " + m) });
25
+ }
26
+ console.log(`[deploy] → ${dir}`);
27
+ }
28
+
29
+ const extRepo = resolve(homedir(), ".pi", "web", "extensions");
30
+ deployCommit({ repo: extRepo, name: "aiti-git-ops", paths: ["aiti-git-ops"], log: (m) => console.log("[deploy] " + m) });
31
+
32
+ console.log("[deploy] 完成。生效:POST /api/extensions/reload");
33
+
34
+ // ── 共享依赖 reconcile(package.json dependencies → <webRoot>/node_modules)——允许失败,下次安装自动对齐 ──
35
+ try {
36
+ const { notifyReconcile } = await import("../../_shared/reconcile-deps.mjs");
37
+ await notifyReconcile();
38
+ } catch (e) {
39
+ console.log("[deploy] reconcile 通知未执行(" + String((e && e.message) || e) + ")");
40
+ }
41
+
42
+ // ── 双实例热重载——允许失败,不影响退出码 ──
43
+ try {
44
+ const { reloadInstances } = await import("../../_shared/reload-instances.mjs");
45
+ await reloadInstances();
46
+ } catch (e) {
47
+ console.log("[deploy] 自动 reload 未执行(" + String((e && e.message) || e) + ")— 需手动 POST /api/extensions/reload");
48
+ }
49
+
50
+ // ── dev-pack——允许失败 ──
51
+ try {
52
+ const { packDevPack } = await import("../../_shared/dev-pack.mjs");
53
+ packDevPack({ extRoot: root, log: (m) => console.log("[deploy] " + m) });
54
+ } catch (e) {
55
+ console.log("[deploy] dev-pack 未执行(" + String((e && e.message) || e) + ")");
56
+ }