forked from career-ops-hq/career-ops
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate-system.mjs
More file actions
2330 lines (2195 loc) · 96.7 KB
/
Copy pathupdate-system.mjs
File metadata and controls
2330 lines (2195 loc) · 96.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* update-system.mjs — Safe auto-updater for career-ops
*
* Updates ONLY system layer files (modes, scripts, dashboard, templates).
* NEVER touches user data (cv.md, profile.yml, _profile.md, data/, reports/).
*
* Usage:
* node update-system.mjs check # Check if update available
* node update-system.mjs apply # Apply update (after user confirms)
* node update-system.mjs apply --force
* # …and overwrite system files this
* # install edited locally (#2337). Without
* # it those files are kept and listed.
* node update-system.mjs rollback # Rollback last update
* node update-system.mjs dismiss # Dismiss update check
*
* See DATA_CONTRACT.md for the full system/user layer definitions.
*/
import { execFile, execFileSync, execSync } from 'child_process';
import { copyFileSync, readFileSync, writeFileSync, existsSync, unlinkSync, rmSync, realpathSync } from 'fs';
import { join, dirname, resolve, posix as pathPosix } from 'path';
import { fileURLToPath } from 'url';
// NOTE: this file must stay *self-loading* — no static (top-level) relative
// imports. A pre-#1245 client's apply() self-reexec checks out ONLY
// update-system.mjs before re-execing the target updater, so a static top-level
// relative import here crashes that re-exec with ERR_MODULE_NOT_FOUND on the
// old→new jump, before the fuller checkout that would materialize the imported
// module ever runs (#1706). Local modules (e.g. the skill-entrypoints helper
// under scaffolder/) are instead pulled in lazily at their point of use, by
// which time the full update stage has already checked them out. The
// updater-migration and test-all suites enforce this invariant.
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = __dirname;
const CANONICAL_REPO = 'https://github.com/santifer/career-ops.git';
const RAW_VERSION_URL = 'https://raw.githubusercontent.com/santifer/career-ops/main/VERSION';
const RELEASES_API = 'https://api.github.com/repos/santifer/career-ops/releases/latest';
// Matches a semver, with or without a leading `v` and an optional
// Release Please component prefix (e.g. `career-ops-v1.9.0` → `1.9.0`).
// Anchoring on `(?:^|-)` lets the releases-API fallback parse our tags,
// which Release Please always prefixes with the component name.
export const SEMVER_RE = /(?:^|-)v?(\d+\.\d+\.\d+)$/i;
// 120s: local git commands are normally instant, but a cloud-evicted working
// tree (iCloud "optimize storage", OneDrive dehydration) can stall a plain
// `git status` for a minute of pure I/O wait re-materializing files (#1393).
export const DEFAULT_GIT_TIMEOUT_MS = parsePositiveInt(process.env.CAREER_OPS_GIT_TIMEOUT_MS, 120000);
export const DEFAULT_GIT_FETCH_TIMEOUT_MS = parsePositiveInt(
process.env.CAREER_OPS_GIT_FETCH_TIMEOUT_MS,
Math.max(DEFAULT_GIT_TIMEOUT_MS, 300000),
);
export const NPM_INSTALL_TIMEOUT_MS = parsePositiveInt(process.env.CAREER_OPS_NPM_INSTALL_TIMEOUT_MS, 60000);
export const PLAYWRIGHT_INSTALL_TIMEOUT_MS = parsePositiveInt(process.env.CAREER_OPS_PLAYWRIGHT_INSTALL_TIMEOUT_MS, 120000);
export const DASHBOARD_REBUILD_TIMEOUT_MS = parsePositiveInt(process.env.CAREER_OPS_DASHBOARD_REBUILD_TIMEOUT_MS, 60000);
export const UPDATE_PATH_CHECKOUT_BUDGET_MS = parsePositiveInt(process.env.CAREER_OPS_UPDATE_PATH_CHECKOUT_BUDGET_MS, 5000);
export const REEXEC_BUFFER_TIMEOUT_MS = parsePositiveInt(process.env.CAREER_OPS_REEXEC_BUFFER_TIMEOUT_MS, 60000);
// System layer paths — ONLY these files get updated
const SYSTEM_PATHS = [
'.gitattributes',
'modes/README.md',
'modes/_shared.md',
'modes/_writing.md',
'modes/_profile.template.md',
'modes/_custom.template.md',
'modes/_brief.template.md',
'voice-dna.template.md',
'modes/oferta.md',
'modes/pdf.md',
'modes/ats.md',
'modes/text.md',
'modes/pdf/',
'modes/cover.md',
'modes/email.md',
'modes/add.md',
'modes/expand.md',
'modes/scan.md',
'modes/discover.md',
'modes/batch.md',
'modes/apply.md',
'modes/auto-pipeline.md',
'modes/contacto.md',
'modes/deep.md',
'modes/ofertas.md',
'modes/pipeline.md',
'modes/triage.md',
'modes/project.md',
'modes/tracker.md',
'modes/training.md',
'modes/interview.md',
'modes/interview-redflag.md',
'modes/latex.md',
'modes/latex-tex.md',
'modes/followup.md',
'modes/offer-prep.md',
'modes/interview-prep.md',
'modes/interview/',
'interview-prep/sessions/.gitkeep',
'interview-prep/sessions/README.md',
'modes/patterns.md',
'modes/calibrate.md',
'modes/titles.md',
'modes/upskill.md',
'modes/intake.md',
'documents/.gitkeep',
'documents/README.md',
'modes/update.md',
'modes/agent-inbox.md',
'modes/reply-watch.md',
'modes/outcome.md',
'modes/ar/',
'modes/da/',
'modes/de/',
'modes/de/interview/',
'modes/fr/',
'modes/fr/interview/',
'modes/hi/',
'modes/es/',
'modes/es/interview/',
'modes/id/',
'modes/id/interview/',
'modes/it/',
'modes/it/interview/',
'modes/ja/',
'modes/ko/',
'modes/nl/',
'modes/pl/',
'modes/pt/',
'modes/pt/interview/',
'modes/ru/',
'modes/ru/interview/',
'modes/tr/',
'modes/ua/',
'modes/ua/interview/',
'modes/heuristics/',
'modes/regional/',
'modes/zh/',
'modes/zh/interview/',
'modes/zh-TW/',
'CLAUDE.md',
'CODEX.md',
'OPENCODE.md',
'AGENTS.md',
'GEMINI.md',
'KIMI.md',
'build-dashboard.mjs',
'clean-markers.mjs',
'generate-pdf.mjs',
'hired-share.mjs',
'hired-wall-build.mjs',
'HIRED.md',
'theme-style.mjs',
'generate-latex.mjs',
'extract-latex-content.mjs',
'patch-latex-content.mjs',
'lib/ascii-fold.mjs',
'lib/cli-flags.mjs',
'lib/gemini-node-floor.mjs',
'lib/local-today.mjs',
'lib/is-main-module.mjs',
'lib/mjs-files.mjs',
'lib/outcome-dir.mjs',
'lib/outcome-types.mjs',
'lib/latex-escape.mjs',
'scan-hn.mjs',
'scripts/check-syntax.mjs',
'scripts/export-ats-text.mjs',
'story-provenance-check.mjs',
'lib/latex-content.mjs',
'lib/context-budget.mjs',
'lib/context-budget.test.mjs',
'lib/golden-budget-analysis.mjs',
'img-to-pdf.mjs',
'archive-posting.mjs',
'jd-capture.mjs',
'application-answers.mjs',
'generate-cover-letter.mjs',
'merge-tracker.mjs',
'url-key.mjs',
'sync-pdf-flags.mjs',
'tracker-links.mjs',
'tracker.mjs',
'find.mjs',
'verify-pipeline.mjs',
'reconcile-pipeline.mjs',
'dedup-tracker.mjs',
'add-entry.mjs',
'role-matcher.mjs',
'tracker-utils.mjs',
'tracker-parse.mjs',
'tracker-aliases.json',
'set-status.mjs',
'set-status-tests.mjs',
'mark-pdf-ready.mjs',
'normalize-statuses.mjs',
'cv-sync-check.mjs',
'verify-cv-facts.mjs',
'verify-ats.mjs',
'update-system.mjs',
'path-resolver.mjs',
'reserve-report-num.mjs',
'scan.mjs',
'pipeline-lock.mjs',
'portal-health-lock.mjs',
'classify-tier.mjs',
'scan-ats-full.mjs',
'scan-interamt.mjs',
'company-funded.mjs',
'match-star.mjs',
'jd-skill-gap.mjs',
'prepare-application.mjs',
'application-artifacts.mjs',
'batch-evaluate-gemini.mjs',
'providers/',
'seeds/',
'tests/',
'user-agent.mjs',
'doctor.mjs',
'jsonc-parse.mjs',
'check-liveness.mjs',
'liveness-core.mjs',
'liveness-api.mjs',
'liveness-browser.mjs',
'browser-extract.mjs',
'analyze-patterns.mjs',
'calibrate.mjs',
'upskill.mjs',
'skill-extract.mjs',
'intake.mjs',
'stats.mjs',
'detect-reposts.mjs',
'rank-pipeline.mjs',
'discover-ats.mjs',
'tests/discover-ats.test.mjs',
'check-table-freshness.mjs',
'fingerprint-core.mjs',
'process-quality.mjs',
'tests/process-quality.test.mjs',
'company-history.mjs',
'tests/company-history.test.mjs',
'rejection-latency.mjs',
'salary-gap.mjs',
'negotiation-roi.mjs',
'funnel-velocity.mjs',
'assessment-log.mjs',
'contacts.mjs',
'linkedin-join.mjs',
'tests/contacts.test.mjs',
'weekly-digest.mjs',
'tracker-sync-check.mjs',
'followup-cadence.mjs',
'tests/followup-cadence.test.mjs',
'invite-match.mjs',
'tests/invite-match.test.mjs',
'agent-inbox.mjs',
'followup-seed.mjs',
'followup-seed-tests.mjs',
'profile-language.mjs',
'title-keywords.mjs',
'gemini-eval.mjs',
'ollama-eval.mjs',
'openai-eval.mjs',
'openai-tailor.mjs',
'eval-golden.mjs',
'evals/',
'openrouter-runner.mjs',
'jd-similarity.mjs',
'tests/jd-similarity.test.mjs',
'test-all.mjs',
'tests/detect-reposts.test.mjs',
'tests/salary-filter.test.mjs',
'tests/trust-validator.test.mjs',
'tracker-columns-tests.mjs',
'tracker-writer-lock-tests.mjs',
'agent-inbox-tests.mjs',
'validate-portals.mjs',
'verify-portals.mjs',
'fix-slugs.mjs',
'updater-migration-tests.mjs',
'validate-system-paths-coverage.mjs',
'validate-untrusted-content-coverage.mjs',
'reply-matcher.mjs',
'tests/reply-matcher.test.mjs',
'reply-watch.mjs',
'paste-reply.mjs',
'paste-reply-tests.mjs',
'outcome.mjs',
'tests/outcome.test.mjs',
'batch/batch-prompt.md',
'batch/batch-runner.sh',
'batch/aggregate-tokens.mjs',
'batch/README.md',
'utils/token-tracker.mjs',
'batch-tailor.mjs',
'dashboard/',
'templates/',
'config/cv-facts.example.json',
'fonts/',
'examples/',
'config/profile.example.yml',
'config/local-paths.example.txt',
'.env.example',
'.editorconfig',
'.agents/',
'.claude/skills/',
'.cursor/skills/',
'.opencode/skills/',
'.opencode/commands/',
'.claude-plugin/',
'.qwen/',
'.antigravitycli/skills/',
'.grok/skills/',
'.kimi/skills/',
'docs/',
'writing-samples/README.md',
'VERSION',
'DATA_CONTRACT.md',
'MANIFESTO.md',
'manifesto.mjs',
'SIGNATURES.md',
'CONTRIBUTING.md',
'MAINTAINERS.md',
'ARCHITECTURE.md',
'README.md',
'README.ar.md',
'README.cn.md',
'README.da.md',
'README.de.md',
'README.es.md',
'README.fr.md',
'README.hi.md',
'README.ja.md',
'README.ko-KR.md',
'README.pl.md',
'README.pt-BR.md',
'README.ru.md',
'README.ta.md',
'README.ua.md',
'README.zh-TW.md',
'README.tr.md',
'CHANGELOG.md',
'CODE_OF_CONDUCT.md',
'CONTRIBUTORS.md',
'.all-contributorsrc',
'GOVERNANCE.md',
'LEGAL_DISCLAIMER.md',
'SECURITY.md',
'SUPPORT.md',
'TRADEMARK.md',
'LICENSE',
'CITATION.cff',
'funding.json',
'.editorconfig',
'.github/',
'package.json',
'build-cv-latex.mjs',
'build-cv-html.mjs',
'cv-sections-core.mjs',
'cv-templates.mjs',
'playwright.cv.config.mjs',
'tests/cv-templates.test.mjs',
'tests/cover-resolver.test.mjs',
'tests/pipeline-lock.test.mjs',
'tests/profile-photo.test.mjs',
'templates/cv-template.zh-minimal.html',
'tests/zh-minimal-template.test.mjs',
'tests/cv-visual/',
'scaffolder/',
'Dockerfile',
'docker-compose.yml',
'.dockerignore',
'cops',
'DOCKER.md',
'plugins/',
'plugins.mjs',
'plugins-registry/',
'plugin-install.mjs',
'plugin-audit.mjs',
'validate-plugin-registry.mjs',
'config/plugins.example.yml',
'opencode.example.json',
'seed-fixture.mjs',
'test-fixtures/',
'upgrade-tests.mjs',
];
const BOOTSTRAP_PATHS = [
'.agents/',
'.cursor/skills/',
'.opencode/skills/',
'.antigravitycli/skills/',
'.grok/skills/',
'.kimi/skills/',
'providers/',
'liveness-browser.mjs',
'tracker-links.mjs',
'role-matcher.mjs',
'tracker-utils.mjs',
'tracker-parse.mjs',
'tracker-aliases.json',
'scaffolder/',
'reserve-report-num.mjs',
'updater-migration-tests.mjs',
'validate-portals.mjs',
'tracker-columns-tests.mjs',
'plugins/',
'plugins.mjs',
'plugins-registry/',
'plugin-install.mjs',
'plugin-audit.mjs',
'validate-plugin-registry.mjs',
'config/plugins.example.yml',
'agent-inbox.mjs',
'agent-inbox-tests.mjs',
];
// User layer paths — NEVER touch these (safety check)
/**
* Files and directories the updater must never touch — the USER layer of the
* data contract (DATA_CONTRACT.md). Exported so other tooling can derive the
* same boundary instead of re-listing it: a hardcoded second copy is how a
* fourth user file eventually gets policed by something that has no business
* having an opinion about it (#2480).
*/
export const USER_PATHS = [
'cv.md',
'config/profile.yml',
'modes/_profile.md',
'modes/_custom.md',
'modes/_brief.md',
'voice-dna.md',
'portals.yml',
'article-digest.md',
'interview-prep/',
'documents/',
'data/',
'reports/',
'output/',
'jds/',
'writing-samples/',
'config/plugins.yml',
'plugins.local/',
'plugins.lock',
'opencode.json',
'.claude/settings.json',
'.claude/hooks/',
];
// Local user layer — a fork's own files, declared OUTSIDE the system layer.
//
// USER_PATHS lives in this file, which `apply` overwrites and which git
// re-merges on every sync, so "this file is mine" was previously a statement
// you could only make inside the thing that keeps overwriting it (#2421). The
// declaration file is gitignored and read at runtime instead: one repo-relative
// path per line, `#` comments, trailing `/` for a directory prefix — the same
// shape as the arrays above. Absent file means no extra paths, which is the
// behaviour every existing install already has.
export const LOCAL_PATHS_FILE = 'config/local-paths.txt';
/**
* Parse a declaration file's contents into a de-duplicated path list.
* Pure and tolerant of CRLF: Windows forks are the population this exists
* for, and a stray \r would make every entry miss its match.
* @param {string} text - Raw file contents.
* @returns {string[]} Declared paths, in file order, without duplicates.
*/
export function parseLocalPaths(text) {
const seen = new Set();
for (const rawLine of String(text).split('\n')) {
const line = rawLine.replace(/\r$/, '').trim();
if (!line || line.startsWith('#')) continue;
seen.add(line);
}
return [...seen];
}
/**
* Read + validate the local declaration file.
*
* Refuses rather than honours anything ambiguous: a path the system layer
* already ships would silently stop updating, and a path that escapes the
* checkout would widen the "never touch" set over files the updater does not
* own. Both throw, naming the offending entry.
*
* @param {string} [root=ROOT] - Repo root to read from.
* @returns {string[]} Extra user-layer paths. Empty when the file is absent.
*/
export function localUserPaths(root = ROOT) {
const file = join(root, LOCAL_PATHS_FILE);
if (!existsSync(file)) return [];
const declared = parseLocalPaths(readFileSync(file, 'utf-8'));
const reject = (path, why) => {
throw new Error(`${LOCAL_PATHS_FILE}: refusing "${path}" — ${why}`);
};
for (const path of declared) {
if (path === LOCAL_PATHS_FILE) {
reject(path, 'the declaration file cannot list itself (it is gitignored, so nothing updates it)');
}
if (path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\')) {
reject(path, 'paths must be repo-relative, not absolute');
}
if (path.split(/[\\/]/).includes('..')) {
reject(path, 'paths must stay inside the repo');
}
// Canonical spelling, required BEFORE the collision check below.
//
// That check compares strings exactly (`path === sys`), and
// userLayerViolations() later compares against git's changed-path format,
// which is always canonical. A non-canonical spelling therefore matches
// NEITHER: `./merge-tracker.mjs` sails past the collision check, and is
// never recognised as the file it names when the safety check runs. The
// declaration silently protects nothing while the updater overwrites the
// file — the data loss this feature exists to prevent, reachable from a
// plausible typo.
//
// Rejected rather than normalised, deliberately. Normalising would accept
// several spellings for one path and leave this file disagreeing with what
// git reports; refusing keeps one path to one spelling, and says so.
if (path.includes('\\')) {
reject(path, 'paths use forward slashes, matching how git reports them');
}
// A single trailing slash is the documented directory-prefix form, so it is
// dropped before the segment check rather than read as an empty segment.
const segments = (path.endsWith('/') ? path.slice(0, -1) : path).split('/');
if (segments.includes('')) {
reject(path, 'paths must not contain an empty segment (a repeated separator)');
}
if (segments.includes('.')) {
reject(path, 'paths must be written plainly, with no "." segment (use "merge-tracker.mjs", not "./merge-tracker.mjs")');
}
const collision = SYSTEM_PATHS.find((sys) =>
sys.endsWith('/') ? path.startsWith(sys) : path === sys,
);
if (collision) {
reject(
path,
`the system layer ships it (SYSTEM_PATHS entry "${collision}"). `
+ 'Declaring it would stop updates to it with no other signal',
);
}
}
return declared;
}
/**
* USER_PATHS plus whatever the local declaration file adds. This is what the
* safety check compares against — the built-in list alone would report a
* fork's own files as violations.
* @param {string} [root=ROOT] - Repo root to read from.
* @returns {string[]} Every path the updater must never touch.
*/
export function effectiveUserPaths(root = ROOT) {
return [...USER_PATHS, ...localUserPaths(root)];
}
/**
* Which of the files an update touched belong to the user layer.
*
* Pure so the rule can be pinned without driving apply(), which is ROOT-bound
* and full of side effects.
*
* @param {string[]} changedFiles - Paths the update modified.
* @param {string[]} updatePaths - Paths this update was allowed to write.
* An explicit entry here wins over a user-layer prefix match, e.g.
* writing-samples/README.md is a system-owned doc inside a user directory.
* @param {string[]} userPaths - User-layer paths, normally effectiveUserPaths().
* A trailing `/` means directory prefix; anything else matches exactly. Bare
* `startsWith` over-matched neighbours that merely share a prefix —
* `cv.md` claimed `cv.md.bak`, and a declared `run-nightly.ps1` claimed
* `run-nightly.ps1.old` — reporting files the user never declared as
* violations. The declaration syntax has always said trailing `/` is what
* makes an entry a prefix; this makes the matcher agree with it.
* @returns {string[]} Violating files, each listed once.
*/
export function userLayerViolations(changedFiles, updatePaths, userPaths) {
const violations = [];
for (const file of changedFiles) {
if (updatePaths.includes(file)) continue;
if (userPaths.some((userPath) => (userPath.endsWith('/') ? file.startsWith(userPath) : file === userPath))) {
violations.push(file);
}
}
return violations;
}
function parseVersionFile(raw) {
// VERSION may carry a release-please marker, e.g. "1.6.0 # x-release-please-version".
// Take the first whitespace-delimited token so the marker doesn't break semver parsing.
return raw.trim().split(/\s+/)[0] || '';
}
function localVersion() {
const vPath = join(ROOT, 'VERSION');
return existsSync(vPath) ? parseVersionFile(readFileSync(vPath, 'utf-8')) : '0.0.0';
}
function compareVersions(a, b) {
const pa = a.split('.').map(Number);
const pb = b.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if ((pa[i] || 0) < (pb[i] || 0)) return -1;
if ((pa[i] || 0) > (pb[i] || 0)) return 1;
}
return 0;
}
function updateBackupBranchName(version, date = new Date()) {
const stamp = date.toISOString()
.replace(/[-:]/g, '')
.replace(/\.\d{3}Z$/, 'Z');
return `backup-pre-update-${version}-${stamp}`;
}
function backupTimestamp(branchName) {
const match = branchName.match(/-(\d{8}T\d{6}Z)$/);
if (!match) return 0;
const [date, time] = match[1].split('T');
return Date.parse(
`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}T${time.slice(0, 2)}:${time.slice(2, 4)}:${time.slice(4, 6)}Z`,
) || 0;
}
function newestBackupBranch(branches) {
const branchList = branches.split('\n').map(b => b.trim()).filter(Boolean);
if (branchList.length === 0) return null;
// Prefer timestamped backup branches created by current versions. Older
// backups are still accepted below for rollback compatibility.
const timestamped = branchList
.map(branch => ({ branch, timestamp: backupTimestamp(branch) }))
.filter(entry => entry.timestamp > 0)
.sort((a, b) => b.timestamp - a.timestamp);
return timestamped[0]?.branch || branchList[0];
}
export function parsePositiveInt(value, fallback) {
const parsed = Number.parseInt(String(value || ''), 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
export function gitTimeoutMs(args) {
return args[0] === 'fetch' ? DEFAULT_GIT_FETCH_TIMEOUT_MS : DEFAULT_GIT_TIMEOUT_MS;
}
export function reexecTimeoutMs(updatePathCount = SYSTEM_PATHS.length + BOOTSTRAP_PATHS.length) {
return Math.max(
120000,
DEFAULT_GIT_FETCH_TIMEOUT_MS +
DEFAULT_GIT_TIMEOUT_MS * 3 +
UPDATE_PATH_CHECKOUT_BUDGET_MS * Math.max(0, updatePathCount) +
NPM_INSTALL_TIMEOUT_MS +
PLAYWRIGHT_INSTALL_TIMEOUT_MS +
DASHBOARD_REBUILD_TIMEOUT_MS +
REEXEC_BUFFER_TIMEOUT_MS,
);
}
function describeGitCommand(args) {
return `git ${args.join(' ')}`;
}
function isTimeoutLikeError(err) {
return err?.code === 'ETIMEDOUT' || err?.signal === 'SIGTERM';
}
function timeoutSeconds(timeout) {
return Math.round(timeout / 1000);
}
function gitTimeoutEnvVar(args) {
return args[0] === 'fetch' ? 'CAREER_OPS_GIT_FETCH_TIMEOUT_MS' : 'CAREER_OPS_GIT_TIMEOUT_MS';
}
/**
* gitIn without the trailing/leading trim.
*
* Needed for output where whitespace is significant: `--name-only -z` emits
* NUL-delimited paths, and a path may legitimately begin or end with a space.
* Trimming the whole buffer would rewrite such a path into a different one.
* Everything else should keep using gitIn.
*/
export function gitRawIn(root, ...args) {
const timeout = gitTimeoutMs(args);
try {
return execFileSync('git', args, { cwd: root, encoding: 'utf-8', timeout });
} catch (err) {
if (isTimeoutLikeError(err)) {
throw new Error(`${describeGitCommand(args)} timed out after ${timeoutSeconds(timeout)}s. If your network is slow, retry or set ${gitTimeoutEnvVar(args)} to a larger value.`);
}
throw err;
}
}
export function gitIn(root, ...args) {
return gitRawIn(root, ...args).trim();
}
function git(...args) {
return gitIn(ROOT, ...args);
}
/**
* git(), but with the child's stderr piped instead of inherited.
*
* execFileSync inherits stderr by default, so a command whose failure is
* expected and handled still prints git's raw error to the console. Use this
* where a non-zero exit is a normal outcome the caller reports itself.
*
* @param {...string} args - git arguments.
* @returns {string} Trimmed stdout.
*/
function gitQuiet(...args) {
const timeout = gitTimeoutMs(args);
try {
return execFileSync('git', args, {
cwd: ROOT, encoding: 'utf-8', timeout, stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch (err) {
if (isTimeoutLikeError(err)) {
throw new Error(`${describeGitCommand(args)} timed out after ${timeoutSeconds(timeout)}s. If your network is slow, retry or set ${gitTimeoutEnvVar(args)} to a larger value.`);
}
throw err;
}
}
/**
* The enclosing repository's toplevel when ROOT is not a git toplevel itself,
* or null when ROOT is its own toplevel (or not inside any worktree at all).
*
* Every git call in this file runs with `cwd: ROOT` and assumes that resolves
* to the career-ops checkout. An install with no `.git` of its own that sits
* INSIDE another repository — a ZIP unpacked into an existing project — breaks
* that silently: git walks up, finds the outer repo, and every rev-parse,
* fetch, branch and checkout lands there, with pathspecs failing because at
* that root the files are prefixed by the install's subpath (#3334). Callers
* use this to refuse before the first side effect.
*
* A ROOT inside no worktree at all returns null: that layout has no foreign
* repo to damage, and each command already has its own handling for git
* being unavailable.
*
* @param {string} [root=ROOT] - Directory to test.
* @returns {string|null} The foreign toplevel path, or null.
*/
export function gitToplevelMismatch(root = ROOT) {
let toplevel;
try {
toplevel = gitIn(root, 'rev-parse', '--show-toplevel');
} catch {
return null;
}
if (!toplevel) return null;
// Realpath both sides: git resolves symlinks and reports on-disk casing
// (macOS /tmp -> /private/tmp; Windows 8.3 names), while `root` keeps
// whatever spelling the process was launched with. Same policy as the CLI
// guard at the bottom of this file. On a realpath failure fall back to
// resolve(): a false MISMATCH refuses an update, a false match fetches into
// a stranger's repo, so the fallback only ever errs toward refusing.
const canonicalize = realpathSync.native ?? realpathSync;
let same;
try {
same = canonicalize(toplevel) === canonicalize(root);
} catch {
same = resolve(toplevel) === resolve(root);
}
return same ? null : toplevel;
}
/**
* Throw when git operations from ROOT would land in an enclosing repository.
* First statement of apply() and rollback(); check() reports a status instead.
*/
function assertOwnGitToplevel() {
const foreignToplevel = gitToplevelMismatch();
if (foreignToplevel) {
throw new Error(
`career-ops at ${ROOT} is not a git checkout of its own, so git operations would land in the enclosing repository at ${foreignToplevel} — this happens when the install was unpacked from a ZIP or copied without its .git directory. Nothing was changed. To make updates work, clone career-ops fresh (git clone ${CANONICAL_REPO}) and move your user-layer files (cv.md, config/, data/, reports/ — see DATA_CONTRACT.md) into the new clone.`,
);
}
}
/**
* Paths the target manifest ships that did not materialize on disk.
*
* apply() reports success without checking that the checkout loop actually
* produced a coherent install, so a client whose local manifest predates the
* target's silently ends up missing every path added since — and only finds
* out when the next script crashes with ERR_MODULE_NOT_FOUND (#1998).
*
* @param {string[]} targetPaths - SYSTEM_PATHS read from the target updater.
* @returns {string[]} Entries present in FETCH_HEAD but absent locally.
*/
function missingFromTargetManifest(targetPaths) {
const missing = [];
for (const path of targetPaths) {
const spec = path.endsWith('/') ? path.slice(0, -1) : path;
// Directory entries need a RECURSIVE check: a pre-existing directory
// (`.gemini/commands/`, `docs/`) can still be missing files the target
// added under it, and `existsSync` on the directory would wrongly call it
// materialized — masking the very partial update this verification exists
// to catch. Compare the target tree's files beneath the entry against disk.
if (path.endsWith('/')) {
let treeFiles = [];
try {
treeFiles = gitQuiet('ls-tree', '-r', '--name-only', 'FETCH_HEAD', '--', spec)
.split('\n').map(s => s.trim()).filter(Boolean);
} catch {
continue; // FETCH_HEAD unreadable for this spec — treat as stale, not missing
}
// Empty tree ⇒ the target ships nothing here (stale manifest entry).
if (treeFiles.some(f => !existsSync(join(ROOT, f)))) missing.push(path);
continue;
}
if (existsSync(join(ROOT, spec))) continue;
// Only count it as missing when the target actually ships it — a manifest
// entry the target no longer carries is a stale entry, not a failed update.
try {
gitQuiet('cat-file', '-e', `FETCH_HEAD:${spec}`);
missing.push(path);
} catch { /* absent upstream too — nothing to materialize */ }
}
return missing;
}
// Parses the NUL-delimited output of `git status --porcelain -z`. `-z` is the
// only form that round-trips every path byte-for-byte, which is what the
// user-layer safety checks depend on — they compare the parsed `path` against
// real files on disk, and a mangled path is a blind spot (#3048, and the
// follow-up this replaces):
// - never quoted: the newline form C-quotes any path with a space, a quote,
// a control char, or (under git's default core.quotepath) a non-ASCII
// byte, e.g. ` M "data/my notes.md"` / ` M "data/caf\303\251.md"`. `-z`
// emits the raw path, so no dequoting is needed.
// - renames/copies as two fields, not one line: the newline form writes
// `R old -> new` on a single line, so a naive slice yields the blob
// `old -> new` as the "path". `-z` writes the destination and origin as
// two separate NUL-delimited fields; both are surfaced as their own entry
// below so the safety check sees every path the move touched.
// - no CRLF: `-z` suppresses git's line-ending translation, so there is no
// trailing CR to strip on Windows.
//
// gitRawIn (not gitIn) because a `-z` field may legitimately begin or end with
// a space, and trimming the buffer would rewrite it into a different path.
export function parsePorcelainStatus(status) {
if (!status) return [];
const fields = status.split('\0');
const entries = [];
for (let i = 0; i < fields.length; i++) {
const field = fields[i];
if (!field) continue;
const code = field.slice(0, 2);
entries.push({ code, path: field.slice(3) });
// R (rename) and C (copy) always sit in the first status column and are
// followed by one extra field — the origin path. Emit it too.
if (code[0] === 'R' || code[0] === 'C') {
const origin = fields[++i];
if (origin) entries.push({ code, path: origin });
}
}
return entries;
}
export function gitStatusEntries(root = ROOT) {
return parsePorcelainStatus(gitRawIn(root, 'status', '--porcelain', '-z'));
}
export function extractArrayFromSource(source, name) {
source = source.replace(/(['"])(?:\\.|(?!\1)[\s\S])*\1|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, (token) => (
/^['"]/.test(token) ? token : token.replace(/[^\n]/g, ' ')
));
const match = source.match(new RegExp(`const\\s+${name}\\s*=\\s*\\[([\\s\\S]*?)\\];`));
if (!match) return [];
return Array.from(match[1].matchAll(/['"]([^'"]+)['"]/g), (entry) => entry[1]);
}
function mergePathLists(...lists) {
const merged = [];
const seen = new Set();
for (const list of lists) {
for (const path of list) {
if (seen.has(path)) continue;
seen.add(path);
merged.push(path);
}
}
return merged;
}
function normalizeRepoPath(value) {
return String(value || '').replace(/\\/g, '/').replace(/^\.\//, '');
}
function pathMatchesManifest(file, entry) {
const normalizedFile = normalizeRepoPath(file);
const normalizedEntry = normalizeRepoPath(entry).replace(/\/$/, '');
return normalizedFile === normalizedEntry || normalizedFile.startsWith(`${normalizedEntry}/`);
}
export function staleSystemFiles(localFiles, remoteFiles, systemPaths, userPaths = USER_PATHS) {
const remote = new Set([...remoteFiles].map(normalizeRepoPath));
if (remote.size === 0) return [];
return [...localFiles]
.map(normalizeRepoPath)
.filter((file) => !remote.has(file))
.filter((file) => systemPaths.some((entry) => pathMatchesManifest(file, entry)))
.filter((file) => !userPaths.some((entry) => pathMatchesManifest(file, entry)));
}
// A stale-file prune candidate can still be load-bearing for a file this same
// run just decided to KEEP because the user modified it (see
// `locallyModifiedSystemFiles` + the `preservedPaths` handling in `apply()`) —
// e.g. a user's custom CV template referencing a font file upstream no longer
// ships. Deleting the referenced asset out from under a preserved file leaves
// the preserved file silently broken (missing font, broken image) even though
// the file itself survived. Scoped to preserved HTML/CSS files' on-disk
// content, since those are the only preserved file types known to reference
// other system files by relative path.
export function isReferencedByPreservedFile(candidatePath, preservedPaths, readFile = (path) => readFileSync(path, 'utf-8')) {
const basename = normalizeRepoPath(candidatePath).split('/').pop();
if (!basename) return false;
return preservedPaths.some((preservedPath) => {
if (!/\.(html|css)$/i.test(preservedPath)) return false;
try {
return readFile(join(ROOT, ...preservedPath.split('/'))).includes(basename);
} catch {
return false;
}
});
}
// Files the self-reexec stage must check out so the TARGET update-system.mjs
// loads without a missing-module crash. Today this is the entry plus its only
// local import; resolveReexecCheckout derives the real set from the fetched
// source, so this is only a defensive fallback if parsing ever misses one.
const REEXEC_FALLBACK_FILES = ['update-system.mjs', 'scaffolder/bin/skill-entrypoints.mjs'];
// Extracts static relative import/export specifiers ('./x.mjs', '../y.mjs')
// from ESM source. Bare ('node:fs') and package ('js-yaml') specifiers are
// ignored — only on-disk relative modules need to exist before re-exec.
export function relativeImportSpecifiers(source) {
const specs = new Set();
const fromRe = /\b(?:import|export)\b[^;]*?\bfrom\s*['"]([^'"]+)['"]/g;
const bareRe = /\bimport\s*['"]([^'"]+)['"]/g;
let match;
while ((match = fromRe.exec(source))) specs.add(match[1]);
while ((match = bareRe.exec(source))) specs.add(match[1]);
return [...specs].filter((spec) => spec.startsWith('.'));
}
// Resolves the relative-import closure of `entry` within a git ref and returns
// the repo-relative paths (forward-slash, Windows-safe) the re-exec stage must
// check out. Only files actually present in the ref are returned; the known
// fallback files are appended defensively. This generalizes the previously
// hardcoded checkout list so a future new top-level import can't reintroduce
// the self-reexec ERR_MODULE_NOT_FOUND crash (issue #1245).
function resolveReexecCheckout(ref, entry) {
const visited = new Set();
const present = new Set();
const order = [];
const stack = [entry];
while (stack.length) {
const file = stack.pop();
if (visited.has(file)) continue;
visited.add(file);
let source;
try {
source = git('show', `${ref}:${file}`);
} catch {
continue; // absent in this ref — leave it to the normal update stage
}
present.add(file);
order.push(file);
const dir = pathPosix.dirname(file);
for (const spec of relativeImportSpecifiers(source)) {
stack.push(pathPosix.join(dir, spec));
}
}
for (const file of REEXEC_FALLBACK_FILES) {
if (present.has(file)) continue;
try {
git('show', `${ref}:${file}`);
order.push(file);
present.add(file);
} catch {
// Not in the target tree (older version) — nothing to check out.
}
}
return order;
}