@mono-lit/utility 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +54 -0
- package/README.md +156 -2
- package/dist/app-roots-BJsIxzjk.d.ts +91 -0
- package/dist/app-roots-CvJnmXcs.js +128 -0
- package/dist/config-node-UzJrXg0Z.js +76 -0
- package/dist/config-node.d.ts +977 -0
- package/dist/config-node.js +7 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +3 -0
- package/dist/create-config-D3m6xTaQ.d.ts +733 -0
- package/dist/create-config-DdL3Fh6T.js +357 -0
- package/dist/fetching.d.ts +239 -0
- package/dist/fetching.js +867 -0
- package/dist/generate-CJ7MtcDd.js +291 -0
- package/dist/index-C2hZeNkq.d.ts +365 -0
- package/dist/index-ClrZbU7n.d.ts +518 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +939 -0
- package/dist/merge-file-C5nzi_MY.d.ts +122 -0
- package/dist/merge-file-CtyKTu5L.js +133 -0
- package/dist/mock-db-5mJTObSC.js +1282 -0
- package/dist/mock-db.d.ts +2 -0
- package/dist/mock-db.js +4 -0
- package/dist/mono-alias-DNDm-jB_.js +508 -0
- package/dist/mono-clone.mjs +958 -0
- package/dist/mono-db.d.ts +1 -0
- package/dist/mono-db.js +151 -0
- package/dist/mono-env.mjs +231 -0
- package/dist/mono-git.mjs +798 -0
- package/dist/mono-link-YlOQ2PVS.js +488 -0
- package/dist/mono-prepare.d.ts +1 -0
- package/dist/mono-prepare.js +27 -0
- package/dist/mono-skills.d.ts +1 -0
- package/dist/mono-skills.js +830 -0
- package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
- package/dist/mono.mjs +34 -0
- package/dist/nuxt-layers-DP1m7f1-.js +176 -0
- package/dist/nuxt-layers.d.ts +34 -0
- package/dist/nuxt-layers.js +3 -0
- package/dist/nuxt-runtime.d.ts +18 -0
- package/dist/nuxt-runtime.js +102 -0
- package/dist/nuxt.d.ts +386 -0
- package/dist/nuxt.js +590 -0
- package/dist/runtime-C_IWNrAG.js +5817 -0
- package/dist/runtime.d.ts +2583 -0
- package/dist/runtime.js +4 -0
- package/dist/session-Bk985AIM.js +1721 -0
- package/dist/types-B6FdB7LJ.d.ts +57 -0
- package/dist/universal-B2eD9xho.d.ts +97 -0
- package/dist/universal-BNTo_83u.js +599 -0
- package/dist/virtual-mono-apps.d.ts +16 -0
- package/dist/vite.d.ts +940 -0
- package/dist/vite.js +1132 -0
- package/package.json +141 -3
|
@@ -0,0 +1,1721 @@
|
|
|
1
|
+
import { i as extractSkill, n as extractConfig } from "./mono-alias-DNDm-jB_.js";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { config } from "dotenv";
|
|
5
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
//#region src/skills/config.ts
|
|
9
|
+
/**
|
|
10
|
+
* Built-in behavioural defaults. Users never configure these — they only set
|
|
11
|
+
* `skill.url` / `skill.envToken`.
|
|
12
|
+
*/
|
|
13
|
+
const SKILLS_DEFAULTS = Object.freeze({
|
|
14
|
+
/** Local staging + clone directory (under the already-gitignored `.mono/`). */
|
|
15
|
+
stagingDir: ".mono/skills",
|
|
16
|
+
/** Subfolder of `stagingDir` holding the working clone of the skills repo. */
|
|
17
|
+
repoDir: "repo",
|
|
18
|
+
/** Conversation chunk size before splitting into `part-NNNN.jsonl`. 750 KB. */
|
|
19
|
+
chunkSizeBytes: 750 * 1024,
|
|
20
|
+
/** Remove the local staging dir after a successful upload. */
|
|
21
|
+
cleanupAfterSuccess: true,
|
|
22
|
+
/** Move a failed session from `pending/` to `failed/`. */
|
|
23
|
+
moveFailedSessions: true,
|
|
24
|
+
/** `read`/`search` re-fetch the clone when its last fetch is older than this. */
|
|
25
|
+
refreshTtlMs: 600 * 1e3,
|
|
26
|
+
/** How many times a rejected (non-fast-forward) push is replayed on a fresh tip. */
|
|
27
|
+
pushAttempts: 3,
|
|
28
|
+
/** Timeout for a single remote git operation (probe, fetch, push). */
|
|
29
|
+
gitTimeoutMs: 120 * 1e3
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* The ONLY CLI flags any `mono skills` subcommand may accept. The argument guard
|
|
33
|
+
* rejects everything else — in particular `--token`, `--owner`, `--repo`,
|
|
34
|
+
* `--branch`, `--url`, `--destination`, etc. — so the AI can never (accidentally
|
|
35
|
+
* or otherwise) retarget the repo or leak a token via argv.
|
|
36
|
+
*/
|
|
37
|
+
const ALLOWED_FLAGS = Object.freeze([
|
|
38
|
+
"app",
|
|
39
|
+
"dir",
|
|
40
|
+
"type",
|
|
41
|
+
"path",
|
|
42
|
+
"query",
|
|
43
|
+
"limit",
|
|
44
|
+
"session-id",
|
|
45
|
+
"dry-run"
|
|
46
|
+
]);
|
|
47
|
+
/**
|
|
48
|
+
* Default/generic template app names. While an app still carries one of these
|
|
49
|
+
* placeholder names, `save`/`retry` are skipped — we don't want session history
|
|
50
|
+
* filed under a non-specific id. The user is expected to rename the app first
|
|
51
|
+
* (see Template Rule 1 — "confirm the app name"). Comparison is case-insensitive
|
|
52
|
+
* against the normalized app id.
|
|
53
|
+
*/
|
|
54
|
+
const GENERIC_APP_NAMES = Object.freeze([
|
|
55
|
+
"mono-host",
|
|
56
|
+
"mono-vue",
|
|
57
|
+
"mono-vue-host",
|
|
58
|
+
"mono-nuxt-host",
|
|
59
|
+
"mono-vue-remote"
|
|
60
|
+
]);
|
|
61
|
+
/** True when `id` is still a default/generic template name. */
|
|
62
|
+
function isGenericAppName(id) {
|
|
63
|
+
return GENERIC_APP_NAMES.includes(String(id).trim().toLowerCase());
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Load `.env` (and `.env.dev` if present) from `cwd` into `process.env` without
|
|
67
|
+
* overriding values already set in the real environment, so `skill.envToken`
|
|
68
|
+
* can name a variable kept in a dotenv file — exactly like `apps[].envToken`
|
|
69
|
+
* for `mono sync`. Missing files are ignored silently.
|
|
70
|
+
*/
|
|
71
|
+
function loadSkillsEnv(cwd = process.cwd()) {
|
|
72
|
+
for (const name of [".env", ".env.dev"]) {
|
|
73
|
+
const file = path.resolve(cwd, name);
|
|
74
|
+
if (fs.existsSync(file)) config({
|
|
75
|
+
path: file,
|
|
76
|
+
override: false,
|
|
77
|
+
quiet: true
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Read `skill` from the `mono.config.ts` in `cwd`. `null` = not configured (the
|
|
83
|
+
* feature is off). Throws when the key is present but malformed.
|
|
84
|
+
*/
|
|
85
|
+
function loadSkillConfig(cwd = process.cwd()) {
|
|
86
|
+
return extractSkill(cwd);
|
|
87
|
+
}
|
|
88
|
+
const RE_SCP_SSH = /^([A-Za-z0-9_.-]+)@([^:/]+):(.+)$/;
|
|
89
|
+
/**
|
|
90
|
+
* Parse `skill.url` into a {@link SkillTarget}. Throws `Invalid skill.url: …`
|
|
91
|
+
* for anything that is not a repository (`/blob/` file links, an owner with no
|
|
92
|
+
* repo, garbage).
|
|
93
|
+
*/
|
|
94
|
+
function resolveSkillTarget(cfg) {
|
|
95
|
+
const raw = String(cfg.url ?? "").trim();
|
|
96
|
+
const tokenEnv = cfg.envToken?.trim() || void 0;
|
|
97
|
+
const bad = (why) => {
|
|
98
|
+
throw new Error(`Invalid skill.url '${raw}': ${why}`);
|
|
99
|
+
};
|
|
100
|
+
if (!raw) bad("empty");
|
|
101
|
+
const scp = RE_SCP_SSH.exec(raw);
|
|
102
|
+
if (scp) return {
|
|
103
|
+
kind: "ssh",
|
|
104
|
+
remoteUrl: raw,
|
|
105
|
+
host: scp[2],
|
|
106
|
+
ref: null,
|
|
107
|
+
refAndDir: null,
|
|
108
|
+
dir: "",
|
|
109
|
+
tokenEnv,
|
|
110
|
+
tokenSupported: false
|
|
111
|
+
};
|
|
112
|
+
if (/^([A-Za-z]:[\\/]|\/)/.test(raw)) return {
|
|
113
|
+
kind: "local",
|
|
114
|
+
remoteUrl: raw,
|
|
115
|
+
host: null,
|
|
116
|
+
ref: null,
|
|
117
|
+
refAndDir: null,
|
|
118
|
+
dir: "",
|
|
119
|
+
tokenEnv,
|
|
120
|
+
tokenSupported: false
|
|
121
|
+
};
|
|
122
|
+
let u;
|
|
123
|
+
try {
|
|
124
|
+
u = new URL(raw);
|
|
125
|
+
} catch {
|
|
126
|
+
return bad("not a URL (expected https://…, ssh://…, git@host:…, or file://…)");
|
|
127
|
+
}
|
|
128
|
+
if (u.protocol === "file:") return {
|
|
129
|
+
kind: "local",
|
|
130
|
+
remoteUrl: raw,
|
|
131
|
+
host: null,
|
|
132
|
+
ref: null,
|
|
133
|
+
refAndDir: null,
|
|
134
|
+
dir: "",
|
|
135
|
+
tokenEnv,
|
|
136
|
+
tokenSupported: false
|
|
137
|
+
};
|
|
138
|
+
if (u.protocol === "ssh:" || u.protocol === "git:") return {
|
|
139
|
+
kind: "ssh",
|
|
140
|
+
remoteUrl: raw,
|
|
141
|
+
host: u.hostname,
|
|
142
|
+
ref: null,
|
|
143
|
+
refAndDir: null,
|
|
144
|
+
dir: "",
|
|
145
|
+
tokenEnv,
|
|
146
|
+
tokenSupported: false
|
|
147
|
+
};
|
|
148
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") return bad(`unsupported protocol '${u.protocol}'`);
|
|
149
|
+
if (u.username || u.password) bad("must not embed credentials — use `envToken` instead");
|
|
150
|
+
const parts = u.pathname.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
|
|
151
|
+
if (u.hostname.toLowerCase() === "github.com") {
|
|
152
|
+
if (parts.length < 2) return bad("expected https://github.com/<owner>/<repo>");
|
|
153
|
+
const owner = parts[0];
|
|
154
|
+
const repo = parts[1].replace(/\.git$/i, "");
|
|
155
|
+
if (!repo) return bad("missing repository name");
|
|
156
|
+
let refAndDir = null;
|
|
157
|
+
if (parts.length > 2) {
|
|
158
|
+
if (parts[2] !== "tree" || parts.length < 4) return bad("only `/tree/<ref>[/<dir>]` deep URLs are supported (not /blob/, /commit/, …)");
|
|
159
|
+
refAndDir = parts.slice(3).join("/");
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
kind: "github",
|
|
163
|
+
remoteUrl: `https://github.com/${owner}/${repo}.git`,
|
|
164
|
+
host: "github.com",
|
|
165
|
+
owner,
|
|
166
|
+
repo,
|
|
167
|
+
ref: null,
|
|
168
|
+
refAndDir,
|
|
169
|
+
dir: "",
|
|
170
|
+
tokenEnv,
|
|
171
|
+
tokenSupported: true
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
if (parts.length < 1) return bad("missing repository path");
|
|
175
|
+
return {
|
|
176
|
+
kind: "https",
|
|
177
|
+
remoteUrl: `${u.protocol}//${u.host}${u.pathname.replace(/\/+$/g, "")}`,
|
|
178
|
+
host: u.hostname,
|
|
179
|
+
ref: null,
|
|
180
|
+
refAndDir: null,
|
|
181
|
+
dir: "",
|
|
182
|
+
tokenEnv,
|
|
183
|
+
tokenSupported: true
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region src/skills/git.ts
|
|
189
|
+
/**
|
|
190
|
+
* Applied to EVERY git invocation (same list as `mono sync`, same reasons):
|
|
191
|
+
* stop Git Credential Manager from popping a dialog, keep LF so the tree is
|
|
192
|
+
* byte-identical across machines, no symlinks/submodules, long paths, no gc.
|
|
193
|
+
*/
|
|
194
|
+
const BASE_ARGS = [
|
|
195
|
+
"-c",
|
|
196
|
+
"credential.interactive=false",
|
|
197
|
+
"-c",
|
|
198
|
+
"credential.guiPrompt=false",
|
|
199
|
+
"-c",
|
|
200
|
+
"core.longpaths=true",
|
|
201
|
+
"-c",
|
|
202
|
+
"core.autocrlf=false",
|
|
203
|
+
"-c",
|
|
204
|
+
"core.eol=lf",
|
|
205
|
+
"-c",
|
|
206
|
+
"core.symlinks=false",
|
|
207
|
+
"-c",
|
|
208
|
+
"submodule.recurse=false",
|
|
209
|
+
"-c",
|
|
210
|
+
"gc.auto=0",
|
|
211
|
+
"-c",
|
|
212
|
+
"advice.detachedHead=false",
|
|
213
|
+
"--no-pager"
|
|
214
|
+
];
|
|
215
|
+
/** Environment for every git child process. */
|
|
216
|
+
function gitEnv(extra = {}) {
|
|
217
|
+
return {
|
|
218
|
+
...process.env,
|
|
219
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
220
|
+
GCM_INTERACTIVE: "never",
|
|
221
|
+
GIT_LFS_SKIP_SMUDGE: "1",
|
|
222
|
+
...extra
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Run git. NEVER throws — returns a record for the caller to classify.
|
|
227
|
+
* `shell: false` so a path like `C:\Program Files\…` needs no quoting.
|
|
228
|
+
*/
|
|
229
|
+
function runGit(args, { cwd, timeoutMs = 2e4, env } = {}) {
|
|
230
|
+
const res = spawnSync("git", [...BASE_ARGS, ...args], {
|
|
231
|
+
cwd,
|
|
232
|
+
env: gitEnv(env),
|
|
233
|
+
encoding: "utf8",
|
|
234
|
+
shell: false,
|
|
235
|
+
windowsHide: true,
|
|
236
|
+
timeout: timeoutMs,
|
|
237
|
+
killSignal: "SIGKILL",
|
|
238
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
239
|
+
stdio: [
|
|
240
|
+
"ignore",
|
|
241
|
+
"pipe",
|
|
242
|
+
"pipe"
|
|
243
|
+
]
|
|
244
|
+
});
|
|
245
|
+
const timedOut = res.error?.code === "ETIMEDOUT" || res.signal === "SIGKILL";
|
|
246
|
+
return {
|
|
247
|
+
ok: res.status === 0 && !timedOut,
|
|
248
|
+
code: res.status,
|
|
249
|
+
signal: res.signal,
|
|
250
|
+
stdout: res.stdout || "",
|
|
251
|
+
stderr: res.stderr || "",
|
|
252
|
+
error: res.error,
|
|
253
|
+
timedOut
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const RE_NETWORK = /Could not resolve host|Failed to connect|Connection (timed out|refused|reset)|Operation timed out|network is unreachable|unable to access '[^']*': (Proxy|SSL|OpenSSL|GnuTLS|Recv failure|send failure)|SSL certificate problem/i;
|
|
257
|
+
const RE_NOTFOUND = /remote: Repository not found|repository '[^']*' not found|remote: Not Found|does not appear to be a git repository/i;
|
|
258
|
+
const RE_BADCRED = /Authentication failed|Invalid username or (password|token)|Support for password authentication|The requested URL returned error: 40[13]|403 Forbidden|Permission (to [^ ]+ )?denied/i;
|
|
259
|
+
const RE_NOCRED = /could not read (Username|Password)|unable to get (password|username) from user|terminal prompts disabled|no supported authentication methods/i;
|
|
260
|
+
/** First `fatal:`/`error:`/`remote:` line of stderr, tag stripped — and redacted. */
|
|
261
|
+
function firstFatal(stderr) {
|
|
262
|
+
const lines = String(stderr).split("\n").map((s) => s.trim());
|
|
263
|
+
return redactUrl((lines.find((s) => /^(fatal|error|remote):/i.test(s)) || lines.find(Boolean) || "").replace(/^(fatal|error|remote):\s*/i, ""));
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Turn a `runGit` result into an actionable cause. The `not-invited` vs
|
|
267
|
+
* `bad-credential` split matters: GitHub answers 404 for private repos you
|
|
268
|
+
* cannot see, but a STALE cached credential answers "Authentication failed".
|
|
269
|
+
*/
|
|
270
|
+
function classifyGitFailure(res) {
|
|
271
|
+
if (res?.error?.code === "ENOENT") return { kind: "no-git" };
|
|
272
|
+
if (res?.timedOut) return { kind: "timeout" };
|
|
273
|
+
const err = res?.stderr || "";
|
|
274
|
+
if (res?.code === 2 && !err.trim()) return { kind: "ref-missing" };
|
|
275
|
+
if (RE_NETWORK.test(err)) return {
|
|
276
|
+
kind: "network",
|
|
277
|
+
detail: firstFatal(err)
|
|
278
|
+
};
|
|
279
|
+
if (RE_NOTFOUND.test(err)) return {
|
|
280
|
+
kind: "no-access",
|
|
281
|
+
why: "not-invited",
|
|
282
|
+
detail: firstFatal(err)
|
|
283
|
+
};
|
|
284
|
+
if (RE_BADCRED.test(err)) return {
|
|
285
|
+
kind: "no-access",
|
|
286
|
+
why: "bad-credential",
|
|
287
|
+
detail: firstFatal(err)
|
|
288
|
+
};
|
|
289
|
+
if (RE_NOCRED.test(err)) return {
|
|
290
|
+
kind: "no-access",
|
|
291
|
+
why: "no-credential",
|
|
292
|
+
detail: firstFatal(err)
|
|
293
|
+
};
|
|
294
|
+
return {
|
|
295
|
+
kind: "unknown",
|
|
296
|
+
detail: firstFatal(err) || `git exited ${res?.code}`
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/** Strip any embedded credential before a URL (or a line containing one) reaches a log or an error. */
|
|
300
|
+
function redactUrl(text) {
|
|
301
|
+
return String(text).replace(/(\w+:)?\/\/[^/@\s]*@/g, "$1//***@");
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Put a token on an https clone URL for ONE fetch/push. GitHub authenticates a
|
|
305
|
+
* PAT as user `x-access-token`; GitLab-style hosts as `oauth2`; Azure DevOps
|
|
306
|
+
* accepts any user name with a PAT password. Never store the result — pass it
|
|
307
|
+
* as the positional remote argument only, so `.git/config` stays clean.
|
|
308
|
+
*/
|
|
309
|
+
function tokenRemote(remoteUrl, token) {
|
|
310
|
+
let u;
|
|
311
|
+
try {
|
|
312
|
+
u = new URL(remoteUrl);
|
|
313
|
+
} catch {
|
|
314
|
+
throw new Error(`A token can only be used with an https URL (${redactUrl(remoteUrl)})`);
|
|
315
|
+
}
|
|
316
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error(`A token can only be used with an https URL (${redactUrl(remoteUrl)})`);
|
|
317
|
+
u.username = u.hostname.toLowerCase() === "github.com" ? "x-access-token" : "oauth2";
|
|
318
|
+
u.password = token;
|
|
319
|
+
return u.toString();
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Every legal split of a `/tree/<refAndDir>` URL remainder into ref + folder,
|
|
323
|
+
* longest ref first — `release/v2/app` may be branch `release/v2` + `app` or
|
|
324
|
+
* branch `release` + `v2/app`. Only the remote can tell, so the caller probes
|
|
325
|
+
* each candidate in this order. (Ported from `bin/mono-git.mjs`.)
|
|
326
|
+
*/
|
|
327
|
+
function refDirCandidates(refAndDir) {
|
|
328
|
+
const segs = String(refAndDir).split("/").filter(Boolean);
|
|
329
|
+
const out = [];
|
|
330
|
+
for (let i = segs.length; i >= 1; i--) out.push({
|
|
331
|
+
ref: segs.slice(0, i).join("/"),
|
|
332
|
+
dir: segs.slice(i).join("/")
|
|
333
|
+
});
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
/** Refs to ask `ls-remote` about for a branch-or-tag name. */
|
|
337
|
+
function refPatterns(ref) {
|
|
338
|
+
return [
|
|
339
|
+
`refs/heads/${ref}`,
|
|
340
|
+
`refs/tags/${ref}`,
|
|
341
|
+
`refs/tags/${ref}^{}`
|
|
342
|
+
];
|
|
343
|
+
}
|
|
344
|
+
/** Pick the SHA for `ref` out of `ls-remote` output. Branch beats tag. */
|
|
345
|
+
function parseLsRemote(stdout, ref) {
|
|
346
|
+
const rows = String(stdout).split("\n").map((l) => l.trim()).filter(Boolean).map((l) => {
|
|
347
|
+
const [sha, name] = l.split(" ");
|
|
348
|
+
return {
|
|
349
|
+
sha,
|
|
350
|
+
name
|
|
351
|
+
};
|
|
352
|
+
});
|
|
353
|
+
const pick = (name) => rows.find((r) => r.name === name)?.sha || null;
|
|
354
|
+
return pick(`refs/heads/${ref}`) ?? pick(`refs/tags/${ref}^{}`) ?? pick(`refs/tags/${ref}`) ?? null;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* The default branch from `git ls-remote --symref <url> HEAD`:
|
|
358
|
+
* `ref: refs/heads/main\tHEAD` → `main`. `null` for an empty (unborn) remote.
|
|
359
|
+
*/
|
|
360
|
+
function parseSymref(stdout) {
|
|
361
|
+
const m = /^ref:\s*refs\/heads\/(\S+)\s+HEAD/m.exec(String(stdout));
|
|
362
|
+
return m ? m[1] : null;
|
|
363
|
+
}
|
|
364
|
+
/** The SHA that `ls-remote … HEAD` reports (second line of a `--symref` answer). */
|
|
365
|
+
function parseHeadSha(stdout) {
|
|
366
|
+
const m = /^([0-9a-f]{40})\s+HEAD$/m.exec(String(stdout));
|
|
367
|
+
return m ? m[1] : null;
|
|
368
|
+
}
|
|
369
|
+
/** Did a push get rejected because the remote moved on (someone else pushed first)? */
|
|
370
|
+
function isNonFastForward(stderr) {
|
|
371
|
+
return /rejected\][^\n]*\((fetch first|non-fast-forward|stale info)\)|Updates were rejected/i.test(String(stderr));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/skills/repo.ts
|
|
376
|
+
/** The remote could not be reached with any transport we were allowed to try. */
|
|
377
|
+
var SkillsAccessError = class extends Error {
|
|
378
|
+
kind;
|
|
379
|
+
why;
|
|
380
|
+
transportTried;
|
|
381
|
+
constructor(message, failure, transportTried) {
|
|
382
|
+
super(message);
|
|
383
|
+
this.name = "SkillsAccessError";
|
|
384
|
+
this.kind = failure.kind;
|
|
385
|
+
this.why = failure.why;
|
|
386
|
+
this.transportTried = transportTried;
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
/** One `ls-remote` round-trip (or a few, for a deep URL) against one URL. */
|
|
390
|
+
function probe(target, url, run, timeoutMs) {
|
|
391
|
+
if (target.refAndDir) {
|
|
392
|
+
const candidates = refDirCandidates(target.refAndDir);
|
|
393
|
+
let sawRepo = false;
|
|
394
|
+
for (const c of candidates) {
|
|
395
|
+
const real = run([
|
|
396
|
+
"ls-remote",
|
|
397
|
+
"--exit-code",
|
|
398
|
+
url,
|
|
399
|
+
...refPatterns(c.ref)
|
|
400
|
+
], { timeoutMs });
|
|
401
|
+
if (real.ok) {
|
|
402
|
+
const sha = parseLsRemote(real.stdout, c.ref);
|
|
403
|
+
if (sha) return {
|
|
404
|
+
ok: true,
|
|
405
|
+
ref: c.ref,
|
|
406
|
+
dir: c.dir,
|
|
407
|
+
headSha: sha,
|
|
408
|
+
emptyRemote: false
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
const failure = classifyGitFailure(real);
|
|
412
|
+
if (failure.kind !== "ref-missing") return {
|
|
413
|
+
ok: false,
|
|
414
|
+
failure
|
|
415
|
+
};
|
|
416
|
+
sawRepo = true;
|
|
417
|
+
}
|
|
418
|
+
if (sawRepo) {
|
|
419
|
+
const head = run([
|
|
420
|
+
"ls-remote",
|
|
421
|
+
"--symref",
|
|
422
|
+
url,
|
|
423
|
+
"HEAD"
|
|
424
|
+
], { timeoutMs });
|
|
425
|
+
if (head.ok && !head.stdout.trim()) {
|
|
426
|
+
const first = candidates[candidates.length - 1];
|
|
427
|
+
return {
|
|
428
|
+
ok: true,
|
|
429
|
+
ref: first.ref,
|
|
430
|
+
dir: first.dir,
|
|
431
|
+
headSha: null,
|
|
432
|
+
emptyRemote: true
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
ok: false,
|
|
438
|
+
failure: {
|
|
439
|
+
kind: "ref-missing",
|
|
440
|
+
detail: `none of these branches exist on the remote: ${candidates.map((c) => c.ref).join(", ")}`
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
if (target.ref) {
|
|
445
|
+
const res = run([
|
|
446
|
+
"ls-remote",
|
|
447
|
+
"--exit-code",
|
|
448
|
+
url,
|
|
449
|
+
...refPatterns(target.ref)
|
|
450
|
+
], { timeoutMs });
|
|
451
|
+
if (res.ok) {
|
|
452
|
+
const sha = parseLsRemote(res.stdout, target.ref);
|
|
453
|
+
if (sha) return {
|
|
454
|
+
ok: true,
|
|
455
|
+
ref: target.ref,
|
|
456
|
+
dir: target.dir,
|
|
457
|
+
headSha: sha,
|
|
458
|
+
emptyRemote: false
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
return {
|
|
462
|
+
ok: false,
|
|
463
|
+
failure: classifyGitFailure(res)
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
const res = run([
|
|
467
|
+
"ls-remote",
|
|
468
|
+
"--symref",
|
|
469
|
+
url,
|
|
470
|
+
"HEAD"
|
|
471
|
+
], { timeoutMs });
|
|
472
|
+
if (!res.ok) return {
|
|
473
|
+
ok: false,
|
|
474
|
+
failure: classifyGitFailure(res)
|
|
475
|
+
};
|
|
476
|
+
const ref = parseSymref(res.stdout);
|
|
477
|
+
if (!ref) return {
|
|
478
|
+
ok: true,
|
|
479
|
+
ref: "main",
|
|
480
|
+
dir: target.dir,
|
|
481
|
+
headSha: null,
|
|
482
|
+
emptyRemote: true
|
|
483
|
+
};
|
|
484
|
+
return {
|
|
485
|
+
ok: true,
|
|
486
|
+
ref,
|
|
487
|
+
dir: target.dir,
|
|
488
|
+
headSha: parseHeadSha(res.stdout),
|
|
489
|
+
emptyRemote: false
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Work out how to reach `skill.url` and what branch/folder it names.
|
|
494
|
+
* Throws {@link SkillsAccessError} (message already redacted) when neither the
|
|
495
|
+
* machine's credentials nor the configured token get through.
|
|
496
|
+
*/
|
|
497
|
+
function resolveRemote({ target, env = process.env, run = runGit, timeoutMs = SKILLS_DEFAULTS.gitTimeoutMs }) {
|
|
498
|
+
const token = target.tokenEnv ? env[target.tokenEnv]?.trim() || void 0 : void 0;
|
|
499
|
+
const attempts = [{
|
|
500
|
+
transport: "git",
|
|
501
|
+
url: target.remoteUrl
|
|
502
|
+
}];
|
|
503
|
+
if (token && target.tokenSupported) attempts.push({
|
|
504
|
+
transport: "token",
|
|
505
|
+
url: tokenRemote(target.remoteUrl, token)
|
|
506
|
+
});
|
|
507
|
+
const tried = [];
|
|
508
|
+
let last = { kind: "unknown" };
|
|
509
|
+
for (const attempt of attempts) {
|
|
510
|
+
tried.push(attempt.transport);
|
|
511
|
+
const res = probe(target, attempt.url, run, timeoutMs);
|
|
512
|
+
if (res.ok) return {
|
|
513
|
+
target,
|
|
514
|
+
transport: attempt.transport,
|
|
515
|
+
fetchUrl: attempt.url,
|
|
516
|
+
ref: res.ref,
|
|
517
|
+
dir: res.dir,
|
|
518
|
+
headSha: res.headSha,
|
|
519
|
+
emptyRemote: res.emptyRemote
|
|
520
|
+
};
|
|
521
|
+
last = res.failure;
|
|
522
|
+
if (last.kind !== "no-access") break;
|
|
523
|
+
}
|
|
524
|
+
throw new SkillsAccessError(describeFailure(target, last, tried, !!token), last, tried);
|
|
525
|
+
}
|
|
526
|
+
function describeFailure(target, f, tried, hadToken) {
|
|
527
|
+
const url = redactUrl(target.remoteUrl);
|
|
528
|
+
const detail = f.detail ? ` (${f.detail})` : "";
|
|
529
|
+
switch (f.kind) {
|
|
530
|
+
case "no-git": return "git is not installed or not on PATH — mono skills needs git.";
|
|
531
|
+
case "timeout": return `Timed out reaching ${url}${detail}.`;
|
|
532
|
+
case "network": return `Cannot reach ${url} — network/proxy/TLS problem${detail}.`;
|
|
533
|
+
case "ref-missing": return `${url}: ${f.detail ?? "branch not found"}.`;
|
|
534
|
+
case "no-access": return `No access to ${url}: ${f.why === "not-invited" ? "this machine is not a collaborator on the repository" : f.why === "bad-credential" ? "the stored git credential was rejected" : "git found no credential for the host"}${detail}. ${tried.includes("token") ? `The token in ${target.tokenEnv} was rejected too — check its scope / SSO authorization.` : target.tokenEnv ? hadToken ? `A token can only be used with an https URL.` : `Set ${target.tokenEnv} (a PAT with read/write access) to fall back to token access.` : `Ask for access, or add \`envToken\` to \`skill\` in mono.config.ts and set that variable.`}`;
|
|
535
|
+
default: return `git failed against ${url}${detail}.`;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
/** Absolute path of the working clone: `<cwd>/.mono/skills/repo`. */
|
|
539
|
+
function repoDir(cwd = process.cwd()) {
|
|
540
|
+
return path.resolve(cwd, SKILLS_DEFAULTS.stagingDir, SKILLS_DEFAULTS.repoDir);
|
|
541
|
+
}
|
|
542
|
+
function fetchHeadAge(dir) {
|
|
543
|
+
try {
|
|
544
|
+
return Date.now() - fs.statSync(path.join(dir, ".git", "FETCH_HEAD")).mtimeMs;
|
|
545
|
+
} catch {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
function localHead(dir, run) {
|
|
550
|
+
const r = run([
|
|
551
|
+
"rev-parse",
|
|
552
|
+
"--verify",
|
|
553
|
+
"-q",
|
|
554
|
+
"HEAD"
|
|
555
|
+
], {
|
|
556
|
+
cwd: dir,
|
|
557
|
+
timeoutMs: 15e3
|
|
558
|
+
});
|
|
559
|
+
return r.ok ? r.stdout.trim() : null;
|
|
560
|
+
}
|
|
561
|
+
/** `fetch` the branch and hard-reset the working tree onto it. Returns the failure line, or null. */
|
|
562
|
+
function refreshClone(dir, remote, run, timeoutMs) {
|
|
563
|
+
const spec = `+refs/heads/${remote.ref}:refs/remotes/origin/${remote.ref}`;
|
|
564
|
+
const f = run([
|
|
565
|
+
"fetch",
|
|
566
|
+
"--quiet",
|
|
567
|
+
"--no-tags",
|
|
568
|
+
"--no-recurse-submodules",
|
|
569
|
+
remote.fetchUrl,
|
|
570
|
+
spec
|
|
571
|
+
], {
|
|
572
|
+
cwd: dir,
|
|
573
|
+
timeoutMs
|
|
574
|
+
});
|
|
575
|
+
if (!f.ok) return firstFatal(f.stderr) || f.error?.message || `fetch exited ${f.code}`;
|
|
576
|
+
const r = run([
|
|
577
|
+
"reset",
|
|
578
|
+
"--quiet",
|
|
579
|
+
"--hard",
|
|
580
|
+
`refs/remotes/origin/${remote.ref}`
|
|
581
|
+
], {
|
|
582
|
+
cwd: dir,
|
|
583
|
+
timeoutMs: 6e4
|
|
584
|
+
});
|
|
585
|
+
if (!r.ok) return firstFatal(r.stderr) || `reset exited ${r.code}`;
|
|
586
|
+
run([
|
|
587
|
+
"clean",
|
|
588
|
+
"--quiet",
|
|
589
|
+
"-fdx"
|
|
590
|
+
], {
|
|
591
|
+
cwd: dir,
|
|
592
|
+
timeoutMs: 6e4
|
|
593
|
+
});
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Make `.mono/skills/repo` a valid clone of the resolved remote on `ref`, and
|
|
598
|
+
* bring it up to date according to `refresh`:
|
|
599
|
+
*
|
|
600
|
+
* - `always` — fetch now (before a save).
|
|
601
|
+
* - `if-stale` — fetch when the last fetch is older than `refreshTtlMs`, or the
|
|
602
|
+
* branch was never fetched (before a read).
|
|
603
|
+
* - `never` — serve whatever is there (diagnostics), fetching only if the
|
|
604
|
+
* branch has never been fetched at all.
|
|
605
|
+
*
|
|
606
|
+
* A failed refresh of an EXISTING clone degrades to `stale: true` — offline
|
|
607
|
+
* reads still work. A failed FIRST fetch throws, since there is nothing to serve.
|
|
608
|
+
*/
|
|
609
|
+
function ensureRepo({ cwd = process.cwd(), remote, refresh, run = runGit, timeoutMs = SKILLS_DEFAULTS.gitTimeoutMs }) {
|
|
610
|
+
const dir = repoDir(cwd);
|
|
611
|
+
const plainUrl = remote.target.remoteUrl;
|
|
612
|
+
if (!(fs.existsSync(path.join(dir, ".git")) && run(["rev-parse", "--git-dir"], {
|
|
613
|
+
cwd: dir,
|
|
614
|
+
timeoutMs: 15e3
|
|
615
|
+
}).ok)) {
|
|
616
|
+
fs.rmSync(dir, {
|
|
617
|
+
recursive: true,
|
|
618
|
+
force: true
|
|
619
|
+
});
|
|
620
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
621
|
+
const step = (args, what) => {
|
|
622
|
+
const r = run(args, {
|
|
623
|
+
cwd: dir,
|
|
624
|
+
timeoutMs: 3e4
|
|
625
|
+
});
|
|
626
|
+
if (!r.ok) throw new Error(`git ${what} failed: ${firstFatal(r.stderr) || r.error?.message || r.code}`);
|
|
627
|
+
};
|
|
628
|
+
step(["init", "--quiet"], "init");
|
|
629
|
+
step([
|
|
630
|
+
"symbolic-ref",
|
|
631
|
+
"HEAD",
|
|
632
|
+
`refs/heads/${remote.ref}`
|
|
633
|
+
], "symbolic-ref");
|
|
634
|
+
step([
|
|
635
|
+
"remote",
|
|
636
|
+
"add",
|
|
637
|
+
"origin",
|
|
638
|
+
plainUrl
|
|
639
|
+
], "remote add");
|
|
640
|
+
} else {
|
|
641
|
+
const cur = run([
|
|
642
|
+
"remote",
|
|
643
|
+
"get-url",
|
|
644
|
+
"origin"
|
|
645
|
+
], {
|
|
646
|
+
cwd: dir,
|
|
647
|
+
timeoutMs: 15e3
|
|
648
|
+
});
|
|
649
|
+
if (!cur.ok || cur.stdout.trim() !== plainUrl) run(cur.ok ? [
|
|
650
|
+
"remote",
|
|
651
|
+
"set-url",
|
|
652
|
+
"origin",
|
|
653
|
+
plainUrl
|
|
654
|
+
] : [
|
|
655
|
+
"remote",
|
|
656
|
+
"add",
|
|
657
|
+
"origin",
|
|
658
|
+
plainUrl
|
|
659
|
+
], {
|
|
660
|
+
cwd: dir,
|
|
661
|
+
timeoutMs: 15e3
|
|
662
|
+
});
|
|
663
|
+
const head = run([
|
|
664
|
+
"symbolic-ref",
|
|
665
|
+
"-q",
|
|
666
|
+
"HEAD"
|
|
667
|
+
], {
|
|
668
|
+
cwd: dir,
|
|
669
|
+
timeoutMs: 15e3
|
|
670
|
+
});
|
|
671
|
+
if (!head.ok || head.stdout.trim() !== `refs/heads/${remote.ref}`) run([
|
|
672
|
+
"symbolic-ref",
|
|
673
|
+
"HEAD",
|
|
674
|
+
`refs/heads/${remote.ref}`
|
|
675
|
+
], {
|
|
676
|
+
cwd: dir,
|
|
677
|
+
timeoutMs: 15e3
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
if (remote.emptyRemote) {
|
|
681
|
+
if (localHead(dir, run)) run([
|
|
682
|
+
"update-ref",
|
|
683
|
+
"-d",
|
|
684
|
+
`refs/heads/${remote.ref}`
|
|
685
|
+
], {
|
|
686
|
+
cwd: dir,
|
|
687
|
+
timeoutMs: 15e3
|
|
688
|
+
});
|
|
689
|
+
run([
|
|
690
|
+
"clean",
|
|
691
|
+
"--quiet",
|
|
692
|
+
"-fdx"
|
|
693
|
+
], {
|
|
694
|
+
cwd: dir,
|
|
695
|
+
timeoutMs: 6e4
|
|
696
|
+
});
|
|
697
|
+
return {
|
|
698
|
+
repoDir: dir,
|
|
699
|
+
refreshed: false,
|
|
700
|
+
stale: false,
|
|
701
|
+
headSha: null,
|
|
702
|
+
lastFetchMs: null
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
const hasTip = run([
|
|
706
|
+
"rev-parse",
|
|
707
|
+
"--verify",
|
|
708
|
+
"-q",
|
|
709
|
+
`refs/remotes/origin/${remote.ref}`
|
|
710
|
+
], {
|
|
711
|
+
cwd: dir,
|
|
712
|
+
timeoutMs: 15e3
|
|
713
|
+
}).ok;
|
|
714
|
+
const age = fetchHeadAge(dir);
|
|
715
|
+
const isStale = age == null || age > SKILLS_DEFAULTS.refreshTtlMs;
|
|
716
|
+
if (!(!hasTip || refresh === "always" || refresh === "if-stale" && isStale)) return {
|
|
717
|
+
repoDir: dir,
|
|
718
|
+
refreshed: false,
|
|
719
|
+
stale: false,
|
|
720
|
+
headSha: localHead(dir, run),
|
|
721
|
+
lastFetchMs: age
|
|
722
|
+
};
|
|
723
|
+
const failed = refreshClone(dir, remote, run, timeoutMs);
|
|
724
|
+
if (failed) {
|
|
725
|
+
if (!hasTip) throw new Error(`Cannot fetch ${redactUrl(plainUrl)}: ${failed}`);
|
|
726
|
+
return {
|
|
727
|
+
repoDir: dir,
|
|
728
|
+
refreshed: false,
|
|
729
|
+
stale: true,
|
|
730
|
+
headSha: localHead(dir, run),
|
|
731
|
+
lastFetchMs: age
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
return {
|
|
735
|
+
repoDir: dir,
|
|
736
|
+
refreshed: true,
|
|
737
|
+
stale: false,
|
|
738
|
+
headSha: localHead(dir, run),
|
|
739
|
+
lastFetchMs: 0
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Write files (via `apply`), commit them as `actor`, push to `ref`. On a
|
|
744
|
+
* non-fast-forward rejection: fetch, hard-reset to the new remote tip, run
|
|
745
|
+
* `apply` again (it re-checks immutability on the fresh tree), commit, push —
|
|
746
|
+
* up to `attempts` times.
|
|
747
|
+
*/
|
|
748
|
+
function commitAndPush({ repoDir: dir, remote, actor, message, apply, attempts = SKILLS_DEFAULTS.pushAttempts, run = runGit, timeoutMs = SKILLS_DEFAULTS.gitTimeoutMs }) {
|
|
749
|
+
const identity = [
|
|
750
|
+
"-c",
|
|
751
|
+
`user.name=${actor.name}`,
|
|
752
|
+
"-c",
|
|
753
|
+
`user.email=${actor.email}`,
|
|
754
|
+
"-c",
|
|
755
|
+
"commit.gpgsign=false"
|
|
756
|
+
];
|
|
757
|
+
let lastReject = "";
|
|
758
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
759
|
+
apply(dir);
|
|
760
|
+
const add = run([
|
|
761
|
+
"add",
|
|
762
|
+
"-A",
|
|
763
|
+
"--",
|
|
764
|
+
"."
|
|
765
|
+
], {
|
|
766
|
+
cwd: dir,
|
|
767
|
+
timeoutMs: 6e4
|
|
768
|
+
});
|
|
769
|
+
if (!add.ok) throw new Error(`git add failed: ${firstFatal(add.stderr) || add.code}`);
|
|
770
|
+
const commit = run([
|
|
771
|
+
...identity,
|
|
772
|
+
"commit",
|
|
773
|
+
"--quiet",
|
|
774
|
+
"--no-verify",
|
|
775
|
+
"-m",
|
|
776
|
+
message
|
|
777
|
+
], {
|
|
778
|
+
cwd: dir,
|
|
779
|
+
timeoutMs: 6e4
|
|
780
|
+
});
|
|
781
|
+
if (!commit.ok) {
|
|
782
|
+
const why = firstFatal(commit.stderr) || commit.stdout.trim() || `exit ${commit.code}`;
|
|
783
|
+
throw new Error(`git commit failed: ${why}`);
|
|
784
|
+
}
|
|
785
|
+
const push = run([
|
|
786
|
+
"push",
|
|
787
|
+
"--quiet",
|
|
788
|
+
remote.fetchUrl,
|
|
789
|
+
`HEAD:refs/heads/${remote.ref}`
|
|
790
|
+
], {
|
|
791
|
+
cwd: dir,
|
|
792
|
+
timeoutMs
|
|
793
|
+
});
|
|
794
|
+
if (push.ok) {
|
|
795
|
+
const sha = localHead(dir, run) ?? "";
|
|
796
|
+
run([
|
|
797
|
+
"update-ref",
|
|
798
|
+
`refs/remotes/origin/${remote.ref}`,
|
|
799
|
+
"HEAD"
|
|
800
|
+
], {
|
|
801
|
+
cwd: dir,
|
|
802
|
+
timeoutMs: 15e3
|
|
803
|
+
});
|
|
804
|
+
return {
|
|
805
|
+
sha,
|
|
806
|
+
attempts: attempt
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
if (!isNonFastForward(push.stderr) || attempt === attempts) {
|
|
810
|
+
const cls = classifyGitFailure(push);
|
|
811
|
+
const why = cls.kind === "no-access" ? `no push access (${cls.detail ?? cls.why})` : firstFatal(push.stderr) || `exit ${push.code}`;
|
|
812
|
+
throw new Error(`git push to ${redactUrl(remote.target.remoteUrl)} failed: ${why}`);
|
|
813
|
+
}
|
|
814
|
+
lastReject = firstFatal(push.stderr);
|
|
815
|
+
const failed = refreshClone(dir, remote, run, timeoutMs);
|
|
816
|
+
if (failed) throw new Error(`git push was rejected (${lastReject}) and re-fetch failed: ${failed}`);
|
|
817
|
+
}
|
|
818
|
+
throw new Error(`git push kept being rejected after ${attempts} attempts (${lastReject})`);
|
|
819
|
+
}
|
|
820
|
+
/** Guard a repo-relative path: no absolute, no `..`, no NUL. */
|
|
821
|
+
function assertInside(rel) {
|
|
822
|
+
const norm = String(rel).replace(/\\/g, "/");
|
|
823
|
+
if (norm.startsWith("/") || /^[A-Za-z]:/.test(norm) || norm.split("/").includes("..") || norm.includes("\0")) throw new Error(`Unsafe path '${rel}': path traversal is not allowed`);
|
|
824
|
+
}
|
|
825
|
+
/** Absolute path of the skills root inside the clone (`repoDir/<dir>`). */
|
|
826
|
+
function skillsRoot(dir, sub) {
|
|
827
|
+
if (sub) assertInside(sub);
|
|
828
|
+
return sub ? path.join(dir, sub) : dir;
|
|
829
|
+
}
|
|
830
|
+
/** Read one file under `<repoDir>/<dir>/<rel>`; `null` when absent or a directory. */
|
|
831
|
+
function readRepoFile(dir, sub, rel) {
|
|
832
|
+
assertInside(rel);
|
|
833
|
+
const file = path.join(skillsRoot(dir, sub), rel);
|
|
834
|
+
try {
|
|
835
|
+
return fs.statSync(file).isFile() ? fs.readFileSync(file, "utf8") : null;
|
|
836
|
+
} catch {
|
|
837
|
+
return null;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* List files under `<repoDir>/<dir>/<prefix>` recursively, as forward-slash
|
|
842
|
+
* paths relative to `<repoDir>/<dir>`. `.git` is never entered.
|
|
843
|
+
*/
|
|
844
|
+
function listRepoFiles(dir, sub, prefix = "") {
|
|
845
|
+
if (prefix) assertInside(prefix);
|
|
846
|
+
const root = skillsRoot(dir, sub);
|
|
847
|
+
const start = prefix ? path.join(root, prefix) : root;
|
|
848
|
+
const out = [];
|
|
849
|
+
const walk = (abs) => {
|
|
850
|
+
let entries;
|
|
851
|
+
try {
|
|
852
|
+
entries = fs.readdirSync(abs, { withFileTypes: true });
|
|
853
|
+
} catch {
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
for (const e of entries) {
|
|
857
|
+
if (e.name === ".git") continue;
|
|
858
|
+
const full = path.join(abs, e.name);
|
|
859
|
+
if (e.isDirectory()) walk(full);
|
|
860
|
+
else if (e.isFile()) out.push(path.relative(root, full).split(path.sep).join("/"));
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
walk(start);
|
|
864
|
+
return out.sort();
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
//#endregion
|
|
868
|
+
//#region src/skills/actor.ts
|
|
869
|
+
/** Read one `git config --get <key>`; returns '' if unset or git is unavailable. */
|
|
870
|
+
function gitConfig(key, cwd) {
|
|
871
|
+
try {
|
|
872
|
+
return execFileSync("git", [
|
|
873
|
+
"config",
|
|
874
|
+
"--get",
|
|
875
|
+
key
|
|
876
|
+
], {
|
|
877
|
+
cwd,
|
|
878
|
+
encoding: "utf8",
|
|
879
|
+
stdio: [
|
|
880
|
+
"ignore",
|
|
881
|
+
"pipe",
|
|
882
|
+
"ignore"
|
|
883
|
+
]
|
|
884
|
+
}).trim();
|
|
885
|
+
} catch {
|
|
886
|
+
return "";
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Slugify a display name into a filesystem-safe folder fragment:
|
|
891
|
+
* lowercase, non-alphanumerics → `_`, collapsed, trimmed.
|
|
892
|
+
*/
|
|
893
|
+
function slugifyName(name) {
|
|
894
|
+
return name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "unknown";
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Resolve the actor from `git config user.name` / `user.email`.
|
|
898
|
+
*
|
|
899
|
+
* `actorFolder` = `<name-slug>__<6 hex>` where the 6 hex come from a sha256 of
|
|
900
|
+
* the email (stable per identity, so the same person always maps to the same
|
|
901
|
+
* folder). Example: `John Doe` / `john.doe@company.com` -> `john_doe__8f219a`.
|
|
902
|
+
*/
|
|
903
|
+
function detectActor(cwd = process.cwd()) {
|
|
904
|
+
const name = gitConfig("user.name", cwd) || "unknown";
|
|
905
|
+
const email = gitConfig("user.email", cwd) || "unknown@unknown";
|
|
906
|
+
const hash = createHash("sha256").update(email.toLowerCase()).digest("hex").slice(0, 6);
|
|
907
|
+
return {
|
|
908
|
+
name,
|
|
909
|
+
email,
|
|
910
|
+
actorFolder: `${slugifyName(name)}__${hash}`
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
//#endregion
|
|
915
|
+
//#region src/skills/appid.ts
|
|
916
|
+
/**
|
|
917
|
+
* Normalize an app id: lowercase, keep only `[a-z0-9_-]`, collapse the rest to
|
|
918
|
+
* `-`, trim separators. Rejects path-traversal / separators outright.
|
|
919
|
+
*/
|
|
920
|
+
function normalizeAppId(raw) {
|
|
921
|
+
if (/[\\/]|\.\./.test(raw)) throw new Error(`Invalid app id '${raw}': must not contain '..', '/', or '\\'`);
|
|
922
|
+
const id = raw.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "");
|
|
923
|
+
if (!id) throw new Error(`Invalid app id '${raw}': empty after normalization`);
|
|
924
|
+
return id;
|
|
925
|
+
}
|
|
926
|
+
/** If `cwd` is inside a `.mono/apps/<name>/...` tree, return `<name>`. */
|
|
927
|
+
function appNameFromMonoApps(cwd) {
|
|
928
|
+
const parts = cwd.replace(/\\/g, "/").split("/");
|
|
929
|
+
const i = parts.lastIndexOf("apps");
|
|
930
|
+
if (i > 0 && parts[i - 1] === ".mono" && parts[i + 1]) return parts[i + 1];
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Resolve the effective app id for a command. `app` is the explicit `--app`
|
|
935
|
+
* value (if any); `cwd` is the working directory.
|
|
936
|
+
*/
|
|
937
|
+
function resolveAppId({ app, cwd = process.cwd() }) {
|
|
938
|
+
if (app && app.trim()) return normalizeAppId(app);
|
|
939
|
+
const sub = appNameFromMonoApps(cwd);
|
|
940
|
+
if (sub) return normalizeAppId(sub);
|
|
941
|
+
return normalizeAppId(extractConfig(cwd).name || path.basename(cwd) || "mono-host");
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
//#endregion
|
|
945
|
+
//#region src/skills/validate.ts
|
|
946
|
+
/** Canonical enums, mirrored from `types.ts` (SessionStatus / ChangedFile.operation). */
|
|
947
|
+
const STATUSES = [
|
|
948
|
+
"completed",
|
|
949
|
+
"partial",
|
|
950
|
+
"failed"
|
|
951
|
+
];
|
|
952
|
+
const OPERATIONS = [
|
|
953
|
+
"added",
|
|
954
|
+
"modified",
|
|
955
|
+
"deleted",
|
|
956
|
+
"renamed"
|
|
957
|
+
];
|
|
958
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
959
|
+
const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0;
|
|
960
|
+
const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
961
|
+
function readIfExists$1(dir, name) {
|
|
962
|
+
const f = path.join(dir, name);
|
|
963
|
+
return fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null;
|
|
964
|
+
}
|
|
965
|
+
/** Collect metadata.json shape problems. */
|
|
966
|
+
function checkMetadata(metadata, errors) {
|
|
967
|
+
const m = metadata;
|
|
968
|
+
if (!isObject(m)) {
|
|
969
|
+
errors.push("metadata.json: expected a JSON object");
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (typeof m.schemaVersion !== "number") errors.push("metadata.json: `schemaVersion` must be a number");
|
|
973
|
+
if (!isNonEmptyString(m.sessionId)) errors.push("metadata.json: `sessionId` must be a non-empty string");
|
|
974
|
+
if (!STATUSES.includes(m.status)) errors.push(`metadata.json: \`status\` must be one of ${STATUSES.join(" | ")}`);
|
|
975
|
+
for (const key of ["startedAt", "finishedAt"]) if (m[key] !== void 0 && typeof m[key] !== "string") errors.push(`metadata.json: \`${key}\` must be an ISO 8601 string when present`);
|
|
976
|
+
for (const key of [
|
|
977
|
+
"topics",
|
|
978
|
+
"userRequests",
|
|
979
|
+
"commandsRun"
|
|
980
|
+
]) if (m[key] !== void 0 && !isStringArray(m[key])) errors.push(`metadata.json: \`${key}\` must be a string[] when present`);
|
|
981
|
+
if (m.validation !== void 0 && !isObject(m.validation)) errors.push("metadata.json: `validation` must be an object when present");
|
|
982
|
+
if (m.outcome !== void 0 && !isObject(m.outcome)) errors.push("metadata.json: `outcome` must be an object when present");
|
|
983
|
+
}
|
|
984
|
+
/** Parse a sidecar JSON file, pushing a clear error and returning null on failure. */
|
|
985
|
+
function parseSidecar(dir, name, errors) {
|
|
986
|
+
const text = readIfExists$1(dir, name);
|
|
987
|
+
if (text == null) return void 0;
|
|
988
|
+
try {
|
|
989
|
+
return JSON.parse(text);
|
|
990
|
+
} catch (e) {
|
|
991
|
+
errors.push(`${name}: invalid JSON (${e.message})`);
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
/** Collect decisions.json shape problems (optional file). */
|
|
996
|
+
function checkDecisions(dir, errors) {
|
|
997
|
+
const data = parseSidecar(dir, "decisions.json", errors);
|
|
998
|
+
if (data === void 0 || data === null) return;
|
|
999
|
+
if (!isObject(data) || !Array.isArray(data.decisions)) {
|
|
1000
|
+
errors.push("decisions.json: expected `{ \"decisions\": [ { title, decision, reason } ] }`");
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
data.decisions.forEach((d, i) => {
|
|
1004
|
+
if (!isObject(d)) {
|
|
1005
|
+
errors.push(`decisions.json: decisions[${i}] must be an object`);
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
if (!isNonEmptyString(d.title)) errors.push(`decisions.json: decisions[${i}].title is required (non-empty string)`);
|
|
1009
|
+
if (!isNonEmptyString(d.decision)) errors.push(`decisions.json: decisions[${i}].decision is required (non-empty string)`);
|
|
1010
|
+
if (d.reason !== void 0 && typeof d.reason !== "string") errors.push(`decisions.json: decisions[${i}].reason must be a string when present`);
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
/** Collect files-changed.json shape problems (optional file). */
|
|
1014
|
+
function checkFilesChanged(dir, errors) {
|
|
1015
|
+
const data = parseSidecar(dir, "files-changed.json", errors);
|
|
1016
|
+
if (data === void 0 || data === null) return;
|
|
1017
|
+
if (!isObject(data) || !Array.isArray(data.files)) {
|
|
1018
|
+
errors.push("files-changed.json: expected `{ \"files\": [ { path, operation, note? } ] }`");
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
data.files.forEach((f, i) => {
|
|
1022
|
+
if (!isObject(f)) {
|
|
1023
|
+
errors.push(`files-changed.json: files[${i}] must be an object`);
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
if (!isNonEmptyString(f.path)) errors.push(`files-changed.json: files[${i}].path is required (non-empty string)`);
|
|
1027
|
+
if (!OPERATIONS.includes(f.operation)) errors.push(`files-changed.json: files[${i}].operation must be one of ${OPERATIONS.join(" | ")}`);
|
|
1028
|
+
if (f.note !== void 0 && typeof f.note !== "string") errors.push(`files-changed.json: files[${i}].note must be a string when present`);
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
/** Collect conversation.jsonl problems (optional file): every non-blank line must be a JSON object. */
|
|
1032
|
+
function checkConversation(dir, errors) {
|
|
1033
|
+
const text = readIfExists$1(dir, "conversation.jsonl");
|
|
1034
|
+
if (text == null) return;
|
|
1035
|
+
const lines = text.split(/\r?\n/);
|
|
1036
|
+
let reported = 0;
|
|
1037
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1038
|
+
const line = lines[i].trim();
|
|
1039
|
+
if (!line) continue;
|
|
1040
|
+
if (reported >= 5) {
|
|
1041
|
+
errors.push("conversation.jsonl: …more invalid lines (showing first 5)");
|
|
1042
|
+
break;
|
|
1043
|
+
}
|
|
1044
|
+
let parsed;
|
|
1045
|
+
try {
|
|
1046
|
+
parsed = JSON.parse(line);
|
|
1047
|
+
} catch (e) {
|
|
1048
|
+
errors.push(`conversation.jsonl: line ${i + 1} is not valid JSON (${e.message})`);
|
|
1049
|
+
reported++;
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
if (!isObject(parsed)) {
|
|
1053
|
+
errors.push(`conversation.jsonl: line ${i + 1} must be a JSON object`);
|
|
1054
|
+
reported++;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Validate a staged session's files against the template standard. Throws a
|
|
1060
|
+
* single error listing every problem when the session doesn't conform, so
|
|
1061
|
+
* `save`/`retry` refuse to upload it. A conforming session returns silently.
|
|
1062
|
+
*/
|
|
1063
|
+
function validateStagedSession(dir, metadata) {
|
|
1064
|
+
const errors = [];
|
|
1065
|
+
checkMetadata(metadata, errors);
|
|
1066
|
+
checkDecisions(dir, errors);
|
|
1067
|
+
checkFilesChanged(dir, errors);
|
|
1068
|
+
checkConversation(dir, errors);
|
|
1069
|
+
if (errors.length > 0) throw new Error(`Staged session '${dir}' does not match the template standard:\n` + errors.map((e) => ` - ${e}`).join("\n") + `\nRun \`mono skills template\` to see the expected file shapes. Nothing was uploaded.`);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
//#endregion
|
|
1073
|
+
//#region src/skills/staging.ts
|
|
1074
|
+
/** Absolute `.mono/skills` for a given project root. */
|
|
1075
|
+
function stagingRoot(cwd = process.cwd()) {
|
|
1076
|
+
return path.resolve(cwd, SKILLS_DEFAULTS.stagingDir);
|
|
1077
|
+
}
|
|
1078
|
+
const REQUIRED_FILES = ["metadata.json", "summary.md"];
|
|
1079
|
+
function readJson(file) {
|
|
1080
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Load + validate a staged session directory. Throws a clear error when a
|
|
1084
|
+
* required file is missing, `metadata.json` is malformed, or any staged file
|
|
1085
|
+
* doesn't match the template standard — so the caller (save/retry) refuses to
|
|
1086
|
+
* upload a session that doesn't conform, and nothing reaches GitHub.
|
|
1087
|
+
*/
|
|
1088
|
+
function loadStagedSession(dir) {
|
|
1089
|
+
const abs = path.resolve(dir);
|
|
1090
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new Error(`Staging directory not found: ${dir}`);
|
|
1091
|
+
for (const req of REQUIRED_FILES) if (!fs.existsSync(path.join(abs, req))) throw new Error(`Staging directory '${dir}' is missing required file '${req}'`);
|
|
1092
|
+
let metadata;
|
|
1093
|
+
try {
|
|
1094
|
+
metadata = readJson(path.join(abs, "metadata.json"));
|
|
1095
|
+
} catch (e) {
|
|
1096
|
+
throw new Error(`Invalid metadata.json in '${dir}': ${e.message}`);
|
|
1097
|
+
}
|
|
1098
|
+
validateStagedSession(abs, metadata);
|
|
1099
|
+
return {
|
|
1100
|
+
sessionId: String(metadata.sessionId || path.basename(abs)),
|
|
1101
|
+
dir: abs,
|
|
1102
|
+
files: fs.readdirSync(abs, { withFileTypes: true }).filter((d) => d.isFile()).map((d) => d.name),
|
|
1103
|
+
metadata
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
/** List session ids under `pending/` (or `failed/`). */
|
|
1107
|
+
function listSessions(cwd, kind) {
|
|
1108
|
+
const base = path.join(stagingRoot(cwd), kind);
|
|
1109
|
+
if (!fs.existsSync(base)) return [];
|
|
1110
|
+
return fs.readdirSync(base, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
1111
|
+
}
|
|
1112
|
+
/** Move a session directory from `pending/` to `failed/` (spec §22). Returns the new path. */
|
|
1113
|
+
function moveToFailed(cwd, sessionId) {
|
|
1114
|
+
const from = path.join(stagingRoot(cwd), "pending", sessionId);
|
|
1115
|
+
const to = path.join(stagingRoot(cwd), "failed", sessionId);
|
|
1116
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
1117
|
+
if (fs.existsSync(to)) fs.rmSync(to, {
|
|
1118
|
+
recursive: true,
|
|
1119
|
+
force: true
|
|
1120
|
+
});
|
|
1121
|
+
if (fs.existsSync(from)) fs.renameSync(from, to);
|
|
1122
|
+
return to;
|
|
1123
|
+
}
|
|
1124
|
+
/** Remove a staged session directory after a successful upload (spec §20 cleanup). */
|
|
1125
|
+
function removeSession(dir) {
|
|
1126
|
+
fs.rmSync(path.resolve(dir), {
|
|
1127
|
+
recursive: true,
|
|
1128
|
+
force: true
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
/** Cache directory for remote reads (`knowledge` / `skills` / `search`). */
|
|
1132
|
+
function cacheDir(cwd, kind) {
|
|
1133
|
+
const dir = path.join(stagingRoot(cwd), "cache", kind);
|
|
1134
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1135
|
+
return dir;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
//#endregion
|
|
1139
|
+
//#region src/skills/redact.ts
|
|
1140
|
+
const REDACTED = "[REDACTED]";
|
|
1141
|
+
/**
|
|
1142
|
+
* Ordered list of (pattern -> replacement) rules. Each pattern is global so all
|
|
1143
|
+
* occurrences on every line are replaced.
|
|
1144
|
+
*/
|
|
1145
|
+
const RULES = [
|
|
1146
|
+
{
|
|
1147
|
+
re: /\bghp_[A-Za-z0-9]{20,}\b/g,
|
|
1148
|
+
replace: REDACTED
|
|
1149
|
+
},
|
|
1150
|
+
{
|
|
1151
|
+
re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
|
|
1152
|
+
replace: REDACTED
|
|
1153
|
+
},
|
|
1154
|
+
{
|
|
1155
|
+
re: /\b(gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g,
|
|
1156
|
+
replace: REDACTED
|
|
1157
|
+
},
|
|
1158
|
+
{
|
|
1159
|
+
re: /\bAKIA[0-9A-Z]{16}\b/g,
|
|
1160
|
+
replace: REDACTED
|
|
1161
|
+
},
|
|
1162
|
+
{
|
|
1163
|
+
re: /\b(Authorization|authorization)\s*:\s*(Bearer|Basic|token)\s+[A-Za-z0-9._\-+/=]+/g,
|
|
1164
|
+
replace: `$1: $2 ${REDACTED}`
|
|
1165
|
+
},
|
|
1166
|
+
{
|
|
1167
|
+
re: /\b(Set-Cookie|Cookie)\s*:\s*[^\r\n]+/gi,
|
|
1168
|
+
replace: `$1: ${REDACTED}`
|
|
1169
|
+
},
|
|
1170
|
+
{
|
|
1171
|
+
re: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,
|
|
1172
|
+
replace: REDACTED
|
|
1173
|
+
},
|
|
1174
|
+
{
|
|
1175
|
+
re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:[^\s:@/]+@[^\s/]+/gi,
|
|
1176
|
+
replace: REDACTED
|
|
1177
|
+
},
|
|
1178
|
+
{
|
|
1179
|
+
re: /\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|APIKEY|API_KEY|PRIVATE_KEY|ACCESS_KEY|CLIENT_SECRET|AUTH)[A-Za-z0-9_]*)\s*[:=]\s*("?)([^\s"'#]+)\2/gi,
|
|
1180
|
+
replace: `$1=${REDACTED}`
|
|
1181
|
+
}
|
|
1182
|
+
];
|
|
1183
|
+
/**
|
|
1184
|
+
* Redact a string. Returns the cleaned text. Safe to run on any text content
|
|
1185
|
+
* (summaries, conversation lines, decisions, metadata serialized to JSON).
|
|
1186
|
+
*/
|
|
1187
|
+
function redact(input) {
|
|
1188
|
+
let out = input;
|
|
1189
|
+
for (const { re, replace } of RULES) out = out.replace(re, replace);
|
|
1190
|
+
return out;
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* Redact a Buffer (e.g. a conversation chunk before upload) by round-tripping
|
|
1194
|
+
* through UTF-8. Returns a new Buffer.
|
|
1195
|
+
*/
|
|
1196
|
+
function redactBuffer(buf) {
|
|
1197
|
+
return Buffer.from(redact(buf.toString("utf8")), "utf8");
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
//#endregion
|
|
1201
|
+
//#region src/skills/chunk.ts
|
|
1202
|
+
/**
|
|
1203
|
+
* Chunk newline-delimited `jsonl` text into parts. Blank lines are dropped.
|
|
1204
|
+
* Returns `[]` for empty input.
|
|
1205
|
+
*/
|
|
1206
|
+
function chunkConversation(jsonl, chunkSizeBytes = SKILLS_DEFAULTS.chunkSizeBytes) {
|
|
1207
|
+
const lines = jsonl.split(/\r?\n/).filter((l) => l.trim().length > 0);
|
|
1208
|
+
if (lines.length === 0) return [];
|
|
1209
|
+
const parts = [];
|
|
1210
|
+
let current = [];
|
|
1211
|
+
let currentBytes = 0;
|
|
1212
|
+
const flush = () => {
|
|
1213
|
+
if (current.length === 0) return;
|
|
1214
|
+
const name = `part-${String(parts.length + 1).padStart(4, "0")}.jsonl`;
|
|
1215
|
+
parts.push({
|
|
1216
|
+
name,
|
|
1217
|
+
content: Buffer.from(current.join("\n") + "\n", "utf8")
|
|
1218
|
+
});
|
|
1219
|
+
current = [];
|
|
1220
|
+
currentBytes = 0;
|
|
1221
|
+
};
|
|
1222
|
+
for (const line of lines) {
|
|
1223
|
+
const lineBytes = Buffer.byteLength(line, "utf8") + 1;
|
|
1224
|
+
if (currentBytes > 0 && currentBytes + lineBytes > chunkSizeBytes) flush();
|
|
1225
|
+
current.push(line);
|
|
1226
|
+
currentBytes += lineBytes;
|
|
1227
|
+
}
|
|
1228
|
+
flush();
|
|
1229
|
+
return parts;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
//#endregion
|
|
1233
|
+
//#region src/skills/save.ts
|
|
1234
|
+
/** Two-digit zero pad. */
|
|
1235
|
+
const p2 = (n) => String(n).padStart(2, "0");
|
|
1236
|
+
/** `YYYY-MM-DD` + `HH-mm-ss` in LOCAL time from a Date. */
|
|
1237
|
+
function dateParts(d) {
|
|
1238
|
+
return {
|
|
1239
|
+
date: `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`,
|
|
1240
|
+
time: `${p2(d.getHours())}-${p2(d.getMinutes())}-${p2(d.getSeconds())}`
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
function readIfExists(dir, name) {
|
|
1244
|
+
const f = path.join(dir, name);
|
|
1245
|
+
return fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null;
|
|
1246
|
+
}
|
|
1247
|
+
/** `skill` from mono.config.ts, or a clear error when it is absent. */
|
|
1248
|
+
function requireTarget(cwd, target) {
|
|
1249
|
+
if (target) return target;
|
|
1250
|
+
const cfg = loadSkillConfig(cwd);
|
|
1251
|
+
if (!cfg) throw new Error("`skill` is not configured in mono.config.ts");
|
|
1252
|
+
return resolveSkillTarget(cfg);
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Build the full upload plan from a staged session WITHOUT touching the network.
|
|
1256
|
+
* `--dry-run` returns exactly this. Everything textual is redacted here.
|
|
1257
|
+
*/
|
|
1258
|
+
function buildSavePlan({ cwd = process.cwd(), app, dir, target }) {
|
|
1259
|
+
const resolvedTarget = requireTarget(cwd, target);
|
|
1260
|
+
const appId = resolveAppId({
|
|
1261
|
+
app,
|
|
1262
|
+
cwd
|
|
1263
|
+
});
|
|
1264
|
+
const actor = detectActor(cwd);
|
|
1265
|
+
const session = loadStagedSession(dir);
|
|
1266
|
+
const sessionId = session.sessionId;
|
|
1267
|
+
const when = session.metadata.finishedAt ? new Date(session.metadata.finishedAt) : /* @__PURE__ */ new Date();
|
|
1268
|
+
const { date, time } = dateParts(isNaN(when.getTime()) ? /* @__PURE__ */ new Date() : when);
|
|
1269
|
+
const sessionFolder = `${time}_${sessionId}`;
|
|
1270
|
+
const savedPath = `${appId}/history/${actor.actorFolder}/${date}/${sessionFolder}`;
|
|
1271
|
+
const files = [];
|
|
1272
|
+
const uploadedNames = [];
|
|
1273
|
+
const put = (repoRel, text) => {
|
|
1274
|
+
files.push({
|
|
1275
|
+
repoPath: `${savedPath}/${repoRel}`,
|
|
1276
|
+
content: Buffer.from(redact(text), "utf8")
|
|
1277
|
+
});
|
|
1278
|
+
uploadedNames.push(repoRel);
|
|
1279
|
+
};
|
|
1280
|
+
const augmented = {
|
|
1281
|
+
...session.metadata,
|
|
1282
|
+
app: appId,
|
|
1283
|
+
actor: {
|
|
1284
|
+
name: actor.name,
|
|
1285
|
+
email: actor.email
|
|
1286
|
+
},
|
|
1287
|
+
actorFolder: actor.actorFolder,
|
|
1288
|
+
repository: resolvedTarget.remoteUrl,
|
|
1289
|
+
savedPath,
|
|
1290
|
+
uploadedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1291
|
+
};
|
|
1292
|
+
put("metadata.json", JSON.stringify(augmented, null, 2));
|
|
1293
|
+
put("summary.md", readIfExists(session.dir, "summary.md") ?? "");
|
|
1294
|
+
for (const opt of ["files-changed.json", "decisions.json"]) {
|
|
1295
|
+
const text = readIfExists(session.dir, opt);
|
|
1296
|
+
if (text != null) put(opt, text);
|
|
1297
|
+
}
|
|
1298
|
+
const convo = readIfExists(session.dir, "conversation.jsonl");
|
|
1299
|
+
if (convo != null) {
|
|
1300
|
+
const parts = chunkConversation(redact(convo), SKILLS_DEFAULTS.chunkSizeBytes);
|
|
1301
|
+
for (const part of parts) {
|
|
1302
|
+
files.push({
|
|
1303
|
+
repoPath: `${savedPath}/conversation/${part.name}`,
|
|
1304
|
+
content: part.content
|
|
1305
|
+
});
|
|
1306
|
+
uploadedNames.push(`conversation/${part.name}`);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
const index = {
|
|
1310
|
+
schemaVersion: 1,
|
|
1311
|
+
sessionId,
|
|
1312
|
+
format: "jsonl",
|
|
1313
|
+
files: uploadedNames
|
|
1314
|
+
};
|
|
1315
|
+
files.push({
|
|
1316
|
+
repoPath: `${savedPath}/index.json`,
|
|
1317
|
+
content: Buffer.from(JSON.stringify(index, null, 2), "utf8")
|
|
1318
|
+
});
|
|
1319
|
+
return {
|
|
1320
|
+
appId,
|
|
1321
|
+
actor,
|
|
1322
|
+
sessionId,
|
|
1323
|
+
repository: resolvedTarget.remoteUrl,
|
|
1324
|
+
savedPath,
|
|
1325
|
+
files
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
function writeFileEnsured(file, content) {
|
|
1329
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
1330
|
+
fs.writeFileSync(file, content);
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Write the plan into the clone. Runs inside `commitAndPush`, so it may run
|
|
1334
|
+
* more than once (after a replay onto a newer tip) — every step is idempotent:
|
|
1335
|
+
* `app.json` / `user.json` are created once and never overwritten (so human
|
|
1336
|
+
* edits to them survive), and an existing session folder is REFUSED (sessions
|
|
1337
|
+
* are immutable).
|
|
1338
|
+
*/
|
|
1339
|
+
function applyPlan(plan, root) {
|
|
1340
|
+
if (fs.existsSync(path.join(root, plan.savedPath, "metadata.json"))) throw new Error(`Refusing to overwrite an existing session at ${plan.savedPath}`);
|
|
1341
|
+
const appJson = path.join(root, plan.appId, "app.json");
|
|
1342
|
+
if (!fs.existsSync(appJson)) writeFileEnsured(appJson, JSON.stringify({
|
|
1343
|
+
schemaVersion: 1,
|
|
1344
|
+
app: plan.appId,
|
|
1345
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1346
|
+
}, null, 2) + "\n");
|
|
1347
|
+
const userJson = path.join(root, plan.appId, "history", plan.actor.actorFolder, "user.json");
|
|
1348
|
+
if (!fs.existsSync(userJson)) writeFileEnsured(userJson, JSON.stringify({
|
|
1349
|
+
name: plan.actor.name,
|
|
1350
|
+
email: plan.actor.email,
|
|
1351
|
+
actorFolder: plan.actor.actorFolder
|
|
1352
|
+
}, null, 2) + "\n");
|
|
1353
|
+
for (const file of plan.files) writeFileEnsured(path.join(root, file.repoPath), file.content);
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Execute a save: resolve the remote, refresh the clone, apply, commit, push.
|
|
1357
|
+
* On any failure the local staging dir is preserved / moved to `failed/` and
|
|
1358
|
+
* the error is rethrown (already redacted).
|
|
1359
|
+
*/
|
|
1360
|
+
function runSave({ cwd = process.cwd(), app, dir, target, remote, env = process.env, run }) {
|
|
1361
|
+
const resolvedTarget = requireTarget(cwd, target ?? remote?.target);
|
|
1362
|
+
const plan = buildSavePlan({
|
|
1363
|
+
cwd,
|
|
1364
|
+
app,
|
|
1365
|
+
dir,
|
|
1366
|
+
target: resolvedTarget
|
|
1367
|
+
});
|
|
1368
|
+
try {
|
|
1369
|
+
const resolved = remote ?? resolveRemote({
|
|
1370
|
+
target: resolvedTarget,
|
|
1371
|
+
env,
|
|
1372
|
+
run
|
|
1373
|
+
});
|
|
1374
|
+
const repo = ensureRepo({
|
|
1375
|
+
cwd,
|
|
1376
|
+
remote: resolved,
|
|
1377
|
+
refresh: "always",
|
|
1378
|
+
run
|
|
1379
|
+
});
|
|
1380
|
+
const root = skillsRoot(repo.repoDir, resolved.dir);
|
|
1381
|
+
const pushed = commitAndPush({
|
|
1382
|
+
repoDir: repo.repoDir,
|
|
1383
|
+
remote: resolved,
|
|
1384
|
+
actor: plan.actor,
|
|
1385
|
+
message: `feat(${plan.appId}): session ${plan.sessionId}`,
|
|
1386
|
+
apply: () => applyPlan(plan, root),
|
|
1387
|
+
run
|
|
1388
|
+
});
|
|
1389
|
+
if (SKILLS_DEFAULTS.cleanupAfterSuccess) removeSession(dir);
|
|
1390
|
+
return {
|
|
1391
|
+
success: true,
|
|
1392
|
+
sessionId: plan.sessionId,
|
|
1393
|
+
repository: resolvedTarget.remoteUrl,
|
|
1394
|
+
ref: resolved.ref,
|
|
1395
|
+
dir: resolved.dir,
|
|
1396
|
+
transport: resolved.transport,
|
|
1397
|
+
savedPath: plan.savedPath,
|
|
1398
|
+
repoPath: resolved.dir ? `${resolved.dir}/${plan.savedPath}` : plan.savedPath,
|
|
1399
|
+
commit: pushed.sha,
|
|
1400
|
+
pushAttempts: pushed.attempts,
|
|
1401
|
+
filesUploaded: plan.files.length,
|
|
1402
|
+
localCleanup: SKILLS_DEFAULTS.cleanupAfterSuccess
|
|
1403
|
+
};
|
|
1404
|
+
} catch (e) {
|
|
1405
|
+
if (SKILLS_DEFAULTS.moveFailedSessions) try {
|
|
1406
|
+
moveToFailed(cwd, plan.sessionId);
|
|
1407
|
+
} catch {}
|
|
1408
|
+
if (e && typeof e === "object") e.sessionId = plan.sessionId;
|
|
1409
|
+
throw e;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
//#endregion
|
|
1414
|
+
//#region src/skills/read.ts
|
|
1415
|
+
/** Reject path traversal in a `--path` value. */
|
|
1416
|
+
function assertSafeRelPath(rel) {
|
|
1417
|
+
const norm = rel.replace(/\\/g, "/");
|
|
1418
|
+
if (norm.startsWith("/") || norm.includes("../") || norm.includes("..\\") || norm.includes("\0")) throw new Error(`Unsafe path '${rel}': path traversal is not allowed`);
|
|
1419
|
+
}
|
|
1420
|
+
/** Refresh-if-stale, then hand back the clone root + `dir` + provenance. */
|
|
1421
|
+
function openRepo({ cwd = process.cwd(), remote, run }) {
|
|
1422
|
+
const repo = ensureRepo({
|
|
1423
|
+
cwd,
|
|
1424
|
+
remote,
|
|
1425
|
+
refresh: "if-stale",
|
|
1426
|
+
run
|
|
1427
|
+
});
|
|
1428
|
+
const source = {
|
|
1429
|
+
source: "local-clone",
|
|
1430
|
+
stale: repo.stale,
|
|
1431
|
+
ref: remote.ref,
|
|
1432
|
+
dir: remote.dir
|
|
1433
|
+
};
|
|
1434
|
+
return {
|
|
1435
|
+
repoDir: repo.repoDir,
|
|
1436
|
+
dir: remote.dir,
|
|
1437
|
+
source
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Read either a whole `--type knowledge|skills` folder for an app, or a single
|
|
1442
|
+
* safe `--path` under that app. Returns the matched files' text.
|
|
1443
|
+
*/
|
|
1444
|
+
function runRead({ cwd = process.cwd(), app, type, path: relPath, remote, run }) {
|
|
1445
|
+
const appId = app ? normalizeAppId(app) : resolveAppId({ cwd });
|
|
1446
|
+
const { repoDir, dir, source } = openRepo({
|
|
1447
|
+
cwd,
|
|
1448
|
+
remote,
|
|
1449
|
+
run
|
|
1450
|
+
});
|
|
1451
|
+
if (relPath) {
|
|
1452
|
+
assertSafeRelPath(relPath);
|
|
1453
|
+
const full = `${appId}/${relPath}`;
|
|
1454
|
+
const text = readRepoFile(repoDir, dir, full);
|
|
1455
|
+
if (text == null) throw new Error(`Not found: ${full}`);
|
|
1456
|
+
return {
|
|
1457
|
+
...source,
|
|
1458
|
+
app: appId,
|
|
1459
|
+
files: [{
|
|
1460
|
+
path: full,
|
|
1461
|
+
text
|
|
1462
|
+
}]
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
if (type !== "knowledge" && type !== "skills") throw new Error(`--type must be 'knowledge' or 'skills' (or pass --path)`);
|
|
1466
|
+
const files = [];
|
|
1467
|
+
for (const p of listRepoFiles(repoDir, dir, `${appId}/${type}`)) {
|
|
1468
|
+
const text = readRepoFile(repoDir, dir, p);
|
|
1469
|
+
if (text != null) files.push({
|
|
1470
|
+
path: p,
|
|
1471
|
+
text
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
return {
|
|
1475
|
+
...source,
|
|
1476
|
+
app: appId,
|
|
1477
|
+
type,
|
|
1478
|
+
files
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
/** Lowercase word tokens for naive relevance scoring. */
|
|
1482
|
+
function terms(q) {
|
|
1483
|
+
return q.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 1);
|
|
1484
|
+
}
|
|
1485
|
+
function scoreText(text, queryTerms) {
|
|
1486
|
+
const lower = text.toLowerCase();
|
|
1487
|
+
let score = 0;
|
|
1488
|
+
for (const t of queryTerms) {
|
|
1489
|
+
let idx = lower.indexOf(t);
|
|
1490
|
+
while (idx !== -1) {
|
|
1491
|
+
score++;
|
|
1492
|
+
idx = lower.indexOf(t, idx + t.length);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
return score;
|
|
1496
|
+
}
|
|
1497
|
+
function makeSnippet(text, queryTerms) {
|
|
1498
|
+
const lower = text.toLowerCase();
|
|
1499
|
+
let at = -1;
|
|
1500
|
+
for (const t of queryTerms) {
|
|
1501
|
+
const i = lower.indexOf(t);
|
|
1502
|
+
if (i !== -1 && (at === -1 || i < at)) at = i;
|
|
1503
|
+
}
|
|
1504
|
+
if (at === -1) at = 0;
|
|
1505
|
+
const start = Math.max(0, at - 80);
|
|
1506
|
+
return text.slice(start, start + 240).replace(/\s+/g, " ").trim();
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Search an app's knowledge/skills + history summaries/decisions/index for a
|
|
1510
|
+
* query. Returns the top `limit` matches with snippets. Conversation chunks are
|
|
1511
|
+
* intentionally excluded from the scan (too large / low signal).
|
|
1512
|
+
*/
|
|
1513
|
+
function runSearch({ cwd = process.cwd(), app, query, limit = 10, remote, run }) {
|
|
1514
|
+
const appId = app ? normalizeAppId(app) : resolveAppId({ cwd });
|
|
1515
|
+
const queryTerms = terms(query);
|
|
1516
|
+
if (queryTerms.length === 0) throw new Error("Empty --query");
|
|
1517
|
+
const { repoDir, dir, source } = openRepo({
|
|
1518
|
+
cwd,
|
|
1519
|
+
remote,
|
|
1520
|
+
run
|
|
1521
|
+
});
|
|
1522
|
+
const candidates = listRepoFiles(repoDir, dir, appId).filter((p) => p.startsWith(`${appId}/knowledge/`) || p.startsWith(`${appId}/skills/`) || /\/(summary\.md|decisions\.json|index\.json|metadata\.json)$/.test(p));
|
|
1523
|
+
const hits = [];
|
|
1524
|
+
for (const p of candidates) {
|
|
1525
|
+
const text = readRepoFile(repoDir, dir, p);
|
|
1526
|
+
if (text == null) continue;
|
|
1527
|
+
const score = scoreText(text, queryTerms);
|
|
1528
|
+
if (score > 0) hits.push({
|
|
1529
|
+
path: p,
|
|
1530
|
+
score,
|
|
1531
|
+
snippet: makeSnippet(text, queryTerms)
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
hits.sort((a, b) => b.score - a.score);
|
|
1535
|
+
return {
|
|
1536
|
+
...source,
|
|
1537
|
+
app: appId,
|
|
1538
|
+
query,
|
|
1539
|
+
hits: hits.slice(0, Math.max(1, limit))
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
//#endregion
|
|
1544
|
+
//#region src/skills/check.ts
|
|
1545
|
+
/**
|
|
1546
|
+
* Run every check that is possible given the current config. Never throws:
|
|
1547
|
+
* an absent `skill` reports `configured: false`; an unreachable remote reports
|
|
1548
|
+
* `null`s plus a note.
|
|
1549
|
+
*/
|
|
1550
|
+
function runCheck({ cwd = process.cwd(), env = process.env, run = runGit } = {}) {
|
|
1551
|
+
const actor = detectActor(cwd);
|
|
1552
|
+
const gitIdentityConfigured = actor.name !== "unknown" && actor.email !== "unknown@unknown";
|
|
1553
|
+
let currentApp = null;
|
|
1554
|
+
try {
|
|
1555
|
+
currentApp = resolveAppId({ cwd });
|
|
1556
|
+
} catch {
|
|
1557
|
+
currentApp = null;
|
|
1558
|
+
}
|
|
1559
|
+
const genericAppName = currentApp != null && isGenericAppName(currentApp);
|
|
1560
|
+
const clonePath = repoDir(cwd);
|
|
1561
|
+
const report = {
|
|
1562
|
+
configured: false,
|
|
1563
|
+
url: null,
|
|
1564
|
+
kind: null,
|
|
1565
|
+
ref: null,
|
|
1566
|
+
dir: null,
|
|
1567
|
+
tokenEnv: null,
|
|
1568
|
+
tokenPresent: false,
|
|
1569
|
+
tokenSupported: false,
|
|
1570
|
+
transport: null,
|
|
1571
|
+
canRead: null,
|
|
1572
|
+
canPush: null,
|
|
1573
|
+
remoteHead: null,
|
|
1574
|
+
emptyRemote: null,
|
|
1575
|
+
localClone: {
|
|
1576
|
+
path: clonePath,
|
|
1577
|
+
exists: fs.existsSync(path.join(clonePath, ".git")),
|
|
1578
|
+
headSha: null,
|
|
1579
|
+
lastFetchAt: null
|
|
1580
|
+
},
|
|
1581
|
+
currentApp,
|
|
1582
|
+
genericAppName,
|
|
1583
|
+
actor,
|
|
1584
|
+
gitIdentityConfigured,
|
|
1585
|
+
notes: []
|
|
1586
|
+
};
|
|
1587
|
+
if (genericAppName) report.notes.push(`App '${currentApp}' still uses a default template name — save/retry are skipped until you rename it (Template Rule 1).`);
|
|
1588
|
+
if (!gitIdentityConfigured) report.notes.push("git user.name / user.email are not set — attribution will be \"unknown\".");
|
|
1589
|
+
let target;
|
|
1590
|
+
try {
|
|
1591
|
+
const cfg = loadSkillConfig(cwd);
|
|
1592
|
+
if (!cfg) {
|
|
1593
|
+
report.notes.push("`skill` is not configured in mono.config.ts — the workflow is a no-op.");
|
|
1594
|
+
return report;
|
|
1595
|
+
}
|
|
1596
|
+
target = resolveSkillTarget(cfg);
|
|
1597
|
+
} catch (e) {
|
|
1598
|
+
report.notes.push(`Invalid \`skill\` in mono.config.ts: ${e.message}`);
|
|
1599
|
+
return report;
|
|
1600
|
+
}
|
|
1601
|
+
report.configured = true;
|
|
1602
|
+
report.url = redactUrl(target.remoteUrl);
|
|
1603
|
+
report.kind = target.kind;
|
|
1604
|
+
report.dir = target.dir;
|
|
1605
|
+
report.tokenEnv = target.tokenEnv ?? null;
|
|
1606
|
+
report.tokenSupported = target.tokenSupported;
|
|
1607
|
+
report.tokenPresent = !!(target.tokenEnv && env[target.tokenEnv]?.trim());
|
|
1608
|
+
if (target.tokenEnv && !report.tokenPresent) report.notes.push(`${target.tokenEnv} is not set — only this machine's own git credentials will be tried.`);
|
|
1609
|
+
if (target.tokenEnv && !target.tokenSupported) report.notes.push(`envToken is ignored for ${target.kind} URLs — a token can only ride an https URL.`);
|
|
1610
|
+
let remote;
|
|
1611
|
+
try {
|
|
1612
|
+
remote = resolveRemote({
|
|
1613
|
+
target,
|
|
1614
|
+
env,
|
|
1615
|
+
run
|
|
1616
|
+
});
|
|
1617
|
+
} catch (e) {
|
|
1618
|
+
report.canRead = false;
|
|
1619
|
+
report.canPush = false;
|
|
1620
|
+
if (e instanceof SkillsAccessError) report.transport = e.transportTried[e.transportTried.length - 1] ?? null;
|
|
1621
|
+
report.notes.push(e.message);
|
|
1622
|
+
return report;
|
|
1623
|
+
}
|
|
1624
|
+
report.transport = remote.transport;
|
|
1625
|
+
report.ref = remote.ref;
|
|
1626
|
+
report.dir = remote.dir;
|
|
1627
|
+
report.canRead = true;
|
|
1628
|
+
report.remoteHead = remote.headSha;
|
|
1629
|
+
report.emptyRemote = remote.emptyRemote;
|
|
1630
|
+
try {
|
|
1631
|
+
const repo = ensureRepo({
|
|
1632
|
+
cwd,
|
|
1633
|
+
remote,
|
|
1634
|
+
refresh: "never",
|
|
1635
|
+
run
|
|
1636
|
+
});
|
|
1637
|
+
report.localClone = {
|
|
1638
|
+
path: repo.repoDir,
|
|
1639
|
+
exists: true,
|
|
1640
|
+
headSha: repo.headSha,
|
|
1641
|
+
lastFetchAt: repo.lastFetchMs == null ? null : new Date(Date.now() - repo.lastFetchMs).toISOString()
|
|
1642
|
+
};
|
|
1643
|
+
if (repo.stale) report.notes.push("The local clone could not be refreshed — reads may be behind the remote.");
|
|
1644
|
+
if (remote.emptyRemote || !repo.headSha) {
|
|
1645
|
+
report.canPush = null;
|
|
1646
|
+
report.notes.push("Remote is empty — push access is verified on the first save.");
|
|
1647
|
+
} else {
|
|
1648
|
+
const dry = run([
|
|
1649
|
+
"push",
|
|
1650
|
+
"--dry-run",
|
|
1651
|
+
"--quiet",
|
|
1652
|
+
remote.fetchUrl,
|
|
1653
|
+
`HEAD:refs/heads/${remote.ref}`
|
|
1654
|
+
], {
|
|
1655
|
+
cwd: repo.repoDir,
|
|
1656
|
+
timeoutMs: SKILLS_DEFAULTS.gitTimeoutMs
|
|
1657
|
+
});
|
|
1658
|
+
if (dry.ok) report.canPush = true;
|
|
1659
|
+
else {
|
|
1660
|
+
const cls = classifyGitFailure(dry);
|
|
1661
|
+
report.canPush = cls.kind === "no-access" ? false : null;
|
|
1662
|
+
report.notes.push(cls.kind === "no-access" ? `Can read but NOT push (${cls.detail ?? cls.why}) — saves will fail until write access is granted.` : `Push check inconclusive: ${firstFatal(dry.stderr) || cls.kind}.`);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
} catch (e) {
|
|
1666
|
+
report.notes.push(`Local clone check failed: ${redactUrl(e.message)}`);
|
|
1667
|
+
}
|
|
1668
|
+
return report;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
//#endregion
|
|
1672
|
+
//#region src/skills/session.ts
|
|
1673
|
+
/**
|
|
1674
|
+
* Locate `<app>/history/**/HH-mm-ss_<sessionId>/` in the clone, then return its
|
|
1675
|
+
* `metadata.json` + `summary.md`. Returns nulls when the session isn't found.
|
|
1676
|
+
*/
|
|
1677
|
+
function runSessionShow({ cwd = process.cwd(), app, sessionId, remote, run }) {
|
|
1678
|
+
const appId = app ? normalizeAppId(app) : resolveAppId({ cwd });
|
|
1679
|
+
const repo = ensureRepo({
|
|
1680
|
+
cwd,
|
|
1681
|
+
remote,
|
|
1682
|
+
refresh: "if-stale",
|
|
1683
|
+
run
|
|
1684
|
+
});
|
|
1685
|
+
const source = {
|
|
1686
|
+
source: "local-clone",
|
|
1687
|
+
stale: repo.stale,
|
|
1688
|
+
ref: remote.ref,
|
|
1689
|
+
dir: remote.dir
|
|
1690
|
+
};
|
|
1691
|
+
const suffix = `_${sessionId}/metadata.json`;
|
|
1692
|
+
const metaPath = listRepoFiles(repo.repoDir, remote.dir, `${appId}/history`).find((p) => p.endsWith(suffix));
|
|
1693
|
+
if (!metaPath) return {
|
|
1694
|
+
...source,
|
|
1695
|
+
app: appId,
|
|
1696
|
+
sessionId,
|
|
1697
|
+
path: null,
|
|
1698
|
+
metadata: null,
|
|
1699
|
+
summary: null
|
|
1700
|
+
};
|
|
1701
|
+
const folder = metaPath.replace(/\/metadata\.json$/, "");
|
|
1702
|
+
const metaText = readRepoFile(repo.repoDir, remote.dir, metaPath);
|
|
1703
|
+
const summary = readRepoFile(repo.repoDir, remote.dir, `${folder}/summary.md`);
|
|
1704
|
+
let metadata = null;
|
|
1705
|
+
try {
|
|
1706
|
+
metadata = metaText ? JSON.parse(metaText) : null;
|
|
1707
|
+
} catch {
|
|
1708
|
+
metadata = null;
|
|
1709
|
+
}
|
|
1710
|
+
return {
|
|
1711
|
+
...source,
|
|
1712
|
+
app: appId,
|
|
1713
|
+
sessionId,
|
|
1714
|
+
path: folder,
|
|
1715
|
+
metadata,
|
|
1716
|
+
summary
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
//#endregion
|
|
1721
|
+
export { BASE_ARGS as A, refPatterns as B, commitAndPush as C, repoDir as D, readRepoFile as E, parseHeadSha as F, SKILLS_DEFAULTS as G, tokenRemote as H, parseLsRemote as I, loadSkillsEnv as J, isGenericAppName as K, parseSymref as L, firstFatal as M, gitEnv as N, resolveRemote as O, isNonFastForward as P, redactUrl as R, SkillsAccessError as S, listRepoFiles as T, ALLOWED_FLAGS as U, runGit as V, GENERIC_APP_NAMES as W, resolveSkillTarget as Y, stagingRoot as _, applyPlan as a, resolveAppId as b, chunkConversation as c, REQUIRED_FILES as d, cacheDir as f, removeSession as g, moveToFailed as h, runSearch as i, classifyGitFailure as j, skillsRoot as k, redact as l, loadStagedSession as m, runCheck as n, buildSavePlan as o, listSessions as p, loadSkillConfig as q, runRead as r, runSave as s, runSessionShow as t, redactBuffer as u, validateStagedSession as v, ensureRepo as w, detectActor as x, normalizeAppId as y, refDirCandidates as z };
|