agentshield 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 +201 -0
- package/README.md +106 -0
- package/dist/index.js +651 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2025] [tomsun28]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# 🛡️ AgentShield
|
|
2
|
+
|
|
3
|
+
English | [简体中文](./README_CN.md)
|
|
4
|
+
|
|
5
|
+
The missing safety layer for AI Agents - Give your AI Agent a "regret pill".
|
|
6
|
+
|
|
7
|
+
**A hardlink-based zero-copy backup system that protects your workspace from unintended AI modifications.**
|
|
8
|
+
|
|
9
|
+
## ✨ Features
|
|
10
|
+
|
|
11
|
+
- **⚡ Zero-Copy Backups** - Uses hardlinks for instant, space-efficient backups (10GB file = 1ms backup)
|
|
12
|
+
- **🕵️ Real-time Protection** - Watches your workspace and automatically backs up files before changes
|
|
13
|
+
- **📦 Smart Exclusions** - Automatically ignores `.git`, `node_modules`, build artifacts, etc.
|
|
14
|
+
- **🔒 Atomic Exec Mode** - Snapshot entire workspace before running agent commands
|
|
15
|
+
- **⏮️ Easy Restore** - One command to roll back any file to its original state
|
|
16
|
+
|
|
17
|
+
## 🚀 Installation
|
|
18
|
+
|
|
19
|
+
### Via npm
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install -g agentshield
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Download Binary
|
|
26
|
+
|
|
27
|
+
Download the binary for your platform from the [Releases](https://github.com/tomsun28/agentshield/releases) page (supports Windows, macOS, Linux).
|
|
28
|
+
|
|
29
|
+
## 📖 Usage
|
|
30
|
+
|
|
31
|
+
### Watch Mode (Real-time Protection)
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
# Watch current directory
|
|
35
|
+
shield watch
|
|
36
|
+
|
|
37
|
+
# Watch specific directory
|
|
38
|
+
shield watch ./my-project
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Exec Mode (Recommended for Agent Tasks)
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
# Snapshot workspace, run command, then allow easy restore
|
|
45
|
+
shield exec -- npm run agent-task
|
|
46
|
+
shield exec -- python ai_script.py
|
|
47
|
+
shield exec --path=./my-project -- cargo run
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
This mode:
|
|
51
|
+
1. Takes a full snapshot before the command runs
|
|
52
|
+
2. Executes your agent command
|
|
53
|
+
3. Allows you to easily restore any modified files
|
|
54
|
+
|
|
55
|
+
### One-time Snapshot
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# Take a snapshot of current directory
|
|
59
|
+
shield snapshot
|
|
60
|
+
|
|
61
|
+
# Take a snapshot of specific directory
|
|
62
|
+
shield snapshot ./my-project
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Restore Files
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
# List all available backups
|
|
69
|
+
shield restore
|
|
70
|
+
|
|
71
|
+
# Restore specific file to latest backup
|
|
72
|
+
shield restore src/index.ts
|
|
73
|
+
|
|
74
|
+
# List all backups with details
|
|
75
|
+
shield list
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Cleanup Old Backups
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Remove backups older than 7 days (default)
|
|
82
|
+
shield clean
|
|
83
|
+
|
|
84
|
+
# Remove backups older than 3 days
|
|
85
|
+
shield clean --days=3
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## 🔍 Default Exclusions
|
|
89
|
+
|
|
90
|
+
These patterns are automatically excluded from backup:
|
|
91
|
+
|
|
92
|
+
- `.git`, `.git/**`
|
|
93
|
+
- `node_modules`, `node_modules/**`
|
|
94
|
+
- `*.log`, `*.tmp`, `*.swp`
|
|
95
|
+
- `dist/`, `build/`, `.next/`, `.nuxt/`
|
|
96
|
+
- `coverage/`, `.cache/`
|
|
97
|
+
- `__pycache__/`, `*.pyc`
|
|
98
|
+
- `.DS_Store`, `Thumbs.db`
|
|
99
|
+
|
|
100
|
+
## 🤝 Contributing
|
|
101
|
+
|
|
102
|
+
Issues and Pull Requests are welcome!
|
|
103
|
+
|
|
104
|
+
## 📄 License
|
|
105
|
+
|
|
106
|
+
[Apache License 2.0](./LICENSE)
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env bun
|
|
3
|
+
// @bun
|
|
4
|
+
|
|
5
|
+
// src/cli.ts
|
|
6
|
+
import { resolve } from "path";
|
|
7
|
+
import { existsSync as existsSync2 } from "fs";
|
|
8
|
+
import { spawn } from "child_process";
|
|
9
|
+
|
|
10
|
+
// src/config.ts
|
|
11
|
+
import { join } from "path";
|
|
12
|
+
var DEFAULT_VAULT_NAME = ".shield";
|
|
13
|
+
var SNAPSHOTS_DIR = "snapshots";
|
|
14
|
+
var INDEX_FILE = "index.json";
|
|
15
|
+
var DEFAULT_EXCLUDE_PATTERNS = [
|
|
16
|
+
".git",
|
|
17
|
+
".git/**",
|
|
18
|
+
"node_modules",
|
|
19
|
+
"node_modules/**",
|
|
20
|
+
".shield",
|
|
21
|
+
".shield/**",
|
|
22
|
+
"**/*.log",
|
|
23
|
+
"**/*.tmp",
|
|
24
|
+
"**/*.swp",
|
|
25
|
+
"**/*.swo",
|
|
26
|
+
"**/~*",
|
|
27
|
+
"**/.DS_Store",
|
|
28
|
+
"**/Thumbs.db",
|
|
29
|
+
"**/__pycache__",
|
|
30
|
+
"**/__pycache__/**",
|
|
31
|
+
"**/*.pyc",
|
|
32
|
+
"**/dist",
|
|
33
|
+
"**/dist/**",
|
|
34
|
+
"**/build",
|
|
35
|
+
"**/build/**",
|
|
36
|
+
"**/.next",
|
|
37
|
+
"**/.next/**",
|
|
38
|
+
"**/.nuxt",
|
|
39
|
+
"**/.nuxt/**",
|
|
40
|
+
"**/coverage",
|
|
41
|
+
"**/coverage/**",
|
|
42
|
+
"**/.cache",
|
|
43
|
+
"**/.cache/**"
|
|
44
|
+
];
|
|
45
|
+
function getDefaultConfig(workspace) {
|
|
46
|
+
return {
|
|
47
|
+
workspace,
|
|
48
|
+
vaultDir: join(workspace, DEFAULT_VAULT_NAME),
|
|
49
|
+
excludePatterns: DEFAULT_EXCLUDE_PATTERNS,
|
|
50
|
+
maxBackupAgeDays: 7
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function getSnapshotsDir(config) {
|
|
54
|
+
return join(config.vaultDir, SNAPSHOTS_DIR);
|
|
55
|
+
}
|
|
56
|
+
function getIndexPath(config) {
|
|
57
|
+
return join(config.vaultDir, INDEX_FILE);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/backup.ts
|
|
61
|
+
import {
|
|
62
|
+
existsSync,
|
|
63
|
+
mkdirSync,
|
|
64
|
+
linkSync,
|
|
65
|
+
copyFileSync,
|
|
66
|
+
statSync as statSync2,
|
|
67
|
+
readFileSync,
|
|
68
|
+
writeFileSync,
|
|
69
|
+
unlinkSync as unlinkSync2
|
|
70
|
+
} from "fs";
|
|
71
|
+
import { join as join3, dirname } from "path";
|
|
72
|
+
|
|
73
|
+
// src/utils.ts
|
|
74
|
+
import { readdirSync, rmdirSync } from "fs";
|
|
75
|
+
import { join as join2, relative } from "path";
|
|
76
|
+
function formatBytes(bytes) {
|
|
77
|
+
if (bytes === 0)
|
|
78
|
+
return "0 B";
|
|
79
|
+
const k = 1024;
|
|
80
|
+
const sizes = ["B", "KB", "MB", "GB", "TB"];
|
|
81
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
82
|
+
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
|
|
83
|
+
}
|
|
84
|
+
function formatTimeAgo(timestamp) {
|
|
85
|
+
const seconds = Math.floor((Date.now() - timestamp) / 1000);
|
|
86
|
+
if (seconds < 60)
|
|
87
|
+
return `${seconds}s ago`;
|
|
88
|
+
if (seconds < 3600)
|
|
89
|
+
return `${Math.floor(seconds / 60)}m ago`;
|
|
90
|
+
if (seconds < 86400)
|
|
91
|
+
return `${Math.floor(seconds / 3600)}h ago`;
|
|
92
|
+
return `${Math.floor(seconds / 86400)}d ago`;
|
|
93
|
+
}
|
|
94
|
+
function matchesPattern(filePath, patterns) {
|
|
95
|
+
const normalizedPath = filePath.replace(/\\/g, "/");
|
|
96
|
+
for (const pattern of patterns) {
|
|
97
|
+
if (pattern.includes("**")) {
|
|
98
|
+
const regex = patternToRegex(pattern);
|
|
99
|
+
if (regex.test(normalizedPath))
|
|
100
|
+
return true;
|
|
101
|
+
} else if (pattern.includes("*")) {
|
|
102
|
+
const regex = patternToRegex(pattern);
|
|
103
|
+
if (regex.test(normalizedPath))
|
|
104
|
+
return true;
|
|
105
|
+
} else {
|
|
106
|
+
if (normalizedPath === pattern || normalizedPath.startsWith(pattern + "/") || normalizedPath.includes("/" + pattern + "/") || normalizedPath.endsWith("/" + pattern)) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
function patternToRegex(pattern) {
|
|
114
|
+
let regex = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*");
|
|
115
|
+
return new RegExp(`(^|/)${regex}($|/)`);
|
|
116
|
+
}
|
|
117
|
+
function getAllFiles(dir, baseDir = dir) {
|
|
118
|
+
const files = [];
|
|
119
|
+
try {
|
|
120
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
121
|
+
for (const entry of entries) {
|
|
122
|
+
const fullPath = join2(dir, entry.name);
|
|
123
|
+
if (entry.isDirectory()) {
|
|
124
|
+
files.push(...getAllFiles(fullPath, baseDir));
|
|
125
|
+
} else if (entry.isFile()) {
|
|
126
|
+
files.push(relative(baseDir, fullPath));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
} catch (err) {}
|
|
130
|
+
return files;
|
|
131
|
+
}
|
|
132
|
+
function removeEmptyDirs(dir) {
|
|
133
|
+
try {
|
|
134
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
135
|
+
for (const entry of entries) {
|
|
136
|
+
if (entry.isDirectory()) {
|
|
137
|
+
removeEmptyDirs(join2(dir, entry.name));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const remaining = readdirSync(dir);
|
|
141
|
+
if (remaining.length === 0) {
|
|
142
|
+
rmdirSync(dir);
|
|
143
|
+
}
|
|
144
|
+
} catch (err) {}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/backup.ts
|
|
148
|
+
class BackupManager {
|
|
149
|
+
config;
|
|
150
|
+
snapshotsDir;
|
|
151
|
+
indexPath;
|
|
152
|
+
index;
|
|
153
|
+
currentSessionId;
|
|
154
|
+
protectedInSession = new Set;
|
|
155
|
+
constructor(config) {
|
|
156
|
+
this.config = config;
|
|
157
|
+
this.snapshotsDir = getSnapshotsDir(config);
|
|
158
|
+
this.indexPath = getIndexPath(config);
|
|
159
|
+
this.currentSessionId = `session_${Date.now()}`;
|
|
160
|
+
this.ensureVaultExists();
|
|
161
|
+
this.index = this.loadIndex();
|
|
162
|
+
}
|
|
163
|
+
ensureVaultExists() {
|
|
164
|
+
if (!existsSync(this.config.vaultDir)) {
|
|
165
|
+
mkdirSync(this.config.vaultDir, { recursive: true });
|
|
166
|
+
}
|
|
167
|
+
if (!existsSync(this.snapshotsDir)) {
|
|
168
|
+
mkdirSync(this.snapshotsDir, { recursive: true });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
loadIndex() {
|
|
172
|
+
if (existsSync(this.indexPath)) {
|
|
173
|
+
try {
|
|
174
|
+
const data = readFileSync(this.indexPath, "utf-8");
|
|
175
|
+
return JSON.parse(data);
|
|
176
|
+
} catch {
|
|
177
|
+
return { entries: [], sessions: {} };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return { entries: [], sessions: {} };
|
|
181
|
+
}
|
|
182
|
+
saveIndex() {
|
|
183
|
+
writeFileSync(this.indexPath, JSON.stringify(this.index, null, 2));
|
|
184
|
+
}
|
|
185
|
+
shouldExclude(filePath) {
|
|
186
|
+
return matchesPattern(filePath, this.config.excludePatterns);
|
|
187
|
+
}
|
|
188
|
+
backupFile(relativePath, forceFullCopy = false) {
|
|
189
|
+
const fullPath = join3(this.config.workspace, relativePath);
|
|
190
|
+
if (this.shouldExclude(relativePath)) {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
if (this.protectedInSession.has(fullPath)) {
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
if (!existsSync(fullPath)) {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const stats = statSync2(fullPath);
|
|
201
|
+
if (!stats.isFile()) {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
const timestamp = Date.now();
|
|
205
|
+
const safeFilename = relativePath.replace(/[/\\]/g, "__");
|
|
206
|
+
const backupFilename = `${timestamp}_${safeFilename}`;
|
|
207
|
+
const backupPath = join3(this.snapshotsDir, backupFilename);
|
|
208
|
+
mkdirSync(dirname(backupPath), { recursive: true });
|
|
209
|
+
let usedHardlink = false;
|
|
210
|
+
if (forceFullCopy) {
|
|
211
|
+
copyFileSync(fullPath, backupPath);
|
|
212
|
+
} else {
|
|
213
|
+
try {
|
|
214
|
+
linkSync(fullPath, backupPath);
|
|
215
|
+
usedHardlink = true;
|
|
216
|
+
} catch (err) {
|
|
217
|
+
copyFileSync(fullPath, backupPath);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const entry = {
|
|
221
|
+
originalPath: relativePath,
|
|
222
|
+
backupPath: backupFilename,
|
|
223
|
+
timestamp,
|
|
224
|
+
size: stats.size,
|
|
225
|
+
sessionId: this.currentSessionId
|
|
226
|
+
};
|
|
227
|
+
this.index.entries.push(entry);
|
|
228
|
+
this.protectedInSession.add(fullPath);
|
|
229
|
+
this.saveIndex();
|
|
230
|
+
return entry;
|
|
231
|
+
} catch (err) {
|
|
232
|
+
console.error(`Failed to backup ${relativePath}:`, err);
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
snapshotWorkspace() {
|
|
237
|
+
const files = getAllFiles(this.config.workspace);
|
|
238
|
+
let backed = 0;
|
|
239
|
+
let skipped = 0;
|
|
240
|
+
for (const file of files) {
|
|
241
|
+
if (this.shouldExclude(file)) {
|
|
242
|
+
skipped++;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
const entry = this.backupFile(file, true);
|
|
246
|
+
if (entry) {
|
|
247
|
+
backed++;
|
|
248
|
+
} else {
|
|
249
|
+
skipped++;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return { total: files.length, backed, skipped };
|
|
253
|
+
}
|
|
254
|
+
resetSession() {
|
|
255
|
+
if (this.index.sessions[this.currentSessionId]) {
|
|
256
|
+
this.index.sessions[this.currentSessionId].endTime = Date.now();
|
|
257
|
+
}
|
|
258
|
+
this.currentSessionId = `session_${Date.now()}`;
|
|
259
|
+
this.index.sessions[this.currentSessionId] = { startTime: Date.now() };
|
|
260
|
+
this.protectedInSession.clear();
|
|
261
|
+
this.saveIndex();
|
|
262
|
+
}
|
|
263
|
+
getBackupsForFile(relativePath) {
|
|
264
|
+
return this.index.entries.filter((e) => e.originalPath === relativePath).sort((a, b) => b.timestamp - a.timestamp);
|
|
265
|
+
}
|
|
266
|
+
getAllBackups() {
|
|
267
|
+
return [...this.index.entries].sort((a, b) => b.timestamp - a.timestamp);
|
|
268
|
+
}
|
|
269
|
+
restoreFile(entry) {
|
|
270
|
+
const backupFullPath = join3(this.snapshotsDir, entry.backupPath);
|
|
271
|
+
const targetPath = join3(this.config.workspace, entry.originalPath);
|
|
272
|
+
if (!existsSync(backupFullPath)) {
|
|
273
|
+
console.error(`Backup file not found: ${entry.backupPath}`);
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
mkdirSync(dirname(targetPath), { recursive: true });
|
|
278
|
+
copyFileSync(backupFullPath, targetPath);
|
|
279
|
+
return true;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
console.error(`Failed to restore ${entry.originalPath}:`, err);
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
restoreLatest(relativePath) {
|
|
286
|
+
const backups = this.getBackupsForFile(relativePath);
|
|
287
|
+
if (backups.length === 0) {
|
|
288
|
+
console.error(`No backups found for: ${relativePath}`);
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
return this.restoreFile(backups[0]);
|
|
292
|
+
}
|
|
293
|
+
restoreSession(sessionId) {
|
|
294
|
+
const sessionEntries = this.index.entries.filter((e) => e.sessionId === sessionId);
|
|
295
|
+
let restored = 0;
|
|
296
|
+
let failed = 0;
|
|
297
|
+
const latestByFile = new Map;
|
|
298
|
+
for (const entry of sessionEntries) {
|
|
299
|
+
const existing = latestByFile.get(entry.originalPath);
|
|
300
|
+
if (!existing || entry.timestamp < existing.timestamp) {
|
|
301
|
+
latestByFile.set(entry.originalPath, entry);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
for (const entry of latestByFile.values()) {
|
|
305
|
+
if (this.restoreFile(entry)) {
|
|
306
|
+
restored++;
|
|
307
|
+
} else {
|
|
308
|
+
failed++;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return { restored, failed };
|
|
312
|
+
}
|
|
313
|
+
cleanOldBackups(maxAgeDays) {
|
|
314
|
+
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
|
315
|
+
let removed = 0;
|
|
316
|
+
let freedBytes = 0;
|
|
317
|
+
const toRemove = [];
|
|
318
|
+
const toKeep = [];
|
|
319
|
+
for (const entry of this.index.entries) {
|
|
320
|
+
if (entry.timestamp < cutoff) {
|
|
321
|
+
toRemove.push(entry);
|
|
322
|
+
} else {
|
|
323
|
+
toKeep.push(entry);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
for (const entry of toRemove) {
|
|
327
|
+
const backupPath = join3(this.snapshotsDir, entry.backupPath);
|
|
328
|
+
try {
|
|
329
|
+
if (existsSync(backupPath)) {
|
|
330
|
+
const stats = statSync2(backupPath);
|
|
331
|
+
unlinkSync2(backupPath);
|
|
332
|
+
freedBytes += stats.size;
|
|
333
|
+
removed++;
|
|
334
|
+
}
|
|
335
|
+
} catch (err) {}
|
|
336
|
+
}
|
|
337
|
+
this.index.entries = toKeep;
|
|
338
|
+
this.saveIndex();
|
|
339
|
+
removeEmptyDirs(this.snapshotsDir);
|
|
340
|
+
return { removed, freedBytes };
|
|
341
|
+
}
|
|
342
|
+
getStats() {
|
|
343
|
+
const uniqueFiles = new Set(this.index.entries.map((e) => e.originalPath));
|
|
344
|
+
const totalSize = this.index.entries.reduce((sum, e) => sum + e.size, 0);
|
|
345
|
+
return {
|
|
346
|
+
totalBackups: this.index.entries.length,
|
|
347
|
+
totalSize,
|
|
348
|
+
uniqueFiles: uniqueFiles.size,
|
|
349
|
+
sessions: Object.keys(this.index.sessions).length
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// src/watcher.ts
|
|
355
|
+
import { watch } from "fs";
|
|
356
|
+
|
|
357
|
+
class ShieldWatcher {
|
|
358
|
+
config;
|
|
359
|
+
backupManager;
|
|
360
|
+
watcher = null;
|
|
361
|
+
debounceMap = new Map;
|
|
362
|
+
debounceMs = 50;
|
|
363
|
+
constructor(config, backupManager) {
|
|
364
|
+
this.config = config;
|
|
365
|
+
this.backupManager = backupManager;
|
|
366
|
+
}
|
|
367
|
+
start() {
|
|
368
|
+
if (this.watcher) {
|
|
369
|
+
console.log("Watcher already running");
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
console.log(`\uD83D\uDE80 Shield started, protecting: ${this.config.workspace}`);
|
|
373
|
+
console.log(`\uD83D\uDCC1 Vault location: ${this.config.vaultDir}`);
|
|
374
|
+
console.log("─".repeat(50));
|
|
375
|
+
this.watcher = watch(this.config.workspace, { recursive: true }, (event, filename) => {
|
|
376
|
+
if (!filename)
|
|
377
|
+
return;
|
|
378
|
+
const normalizedFilename = filename.replace(/\\/g, "/");
|
|
379
|
+
if (normalizedFilename.startsWith(".shield") || this.backupManager.shouldExclude(normalizedFilename)) {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const existingTimeout = this.debounceMap.get(normalizedFilename);
|
|
383
|
+
if (existingTimeout) {
|
|
384
|
+
clearTimeout(existingTimeout);
|
|
385
|
+
}
|
|
386
|
+
const timeout = setTimeout(() => {
|
|
387
|
+
this.debounceMap.delete(normalizedFilename);
|
|
388
|
+
this.handleFileChange(normalizedFilename);
|
|
389
|
+
}, this.debounceMs);
|
|
390
|
+
this.debounceMap.set(normalizedFilename, timeout);
|
|
391
|
+
});
|
|
392
|
+
this.watcher.on("error", (err) => {
|
|
393
|
+
console.error("Watcher error:", err);
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
handleFileChange(relativePath) {
|
|
397
|
+
const entry = this.backupManager.backupFile(relativePath);
|
|
398
|
+
if (entry) {
|
|
399
|
+
console.log(`[\uD83D\uDEE1️ Shield] Original version locked: ${relativePath}`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
stop() {
|
|
403
|
+
if (this.watcher) {
|
|
404
|
+
this.watcher.close();
|
|
405
|
+
this.watcher = null;
|
|
406
|
+
for (const timeout of this.debounceMap.values()) {
|
|
407
|
+
clearTimeout(timeout);
|
|
408
|
+
}
|
|
409
|
+
this.debounceMap.clear();
|
|
410
|
+
console.log("Shield stopped");
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
resetSession() {
|
|
414
|
+
this.backupManager.resetSession();
|
|
415
|
+
console.log("─".repeat(50));
|
|
416
|
+
console.log("\uD83D\uDD04 New session started, protection state reset");
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// src/cli.ts
|
|
421
|
+
function parseArgs(args) {
|
|
422
|
+
const result = {
|
|
423
|
+
command: args[0] || "help",
|
|
424
|
+
args: [],
|
|
425
|
+
flags: {}
|
|
426
|
+
};
|
|
427
|
+
for (let i = 1;i < args.length; i++) {
|
|
428
|
+
const arg = args[i];
|
|
429
|
+
if (arg.startsWith("--")) {
|
|
430
|
+
const [key, value] = arg.slice(2).split("=");
|
|
431
|
+
result.flags[key] = value ?? true;
|
|
432
|
+
} else if (arg.startsWith("-")) {
|
|
433
|
+
result.flags[arg.slice(1)] = true;
|
|
434
|
+
} else {
|
|
435
|
+
result.args.push(arg);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return result;
|
|
439
|
+
}
|
|
440
|
+
function printHelp() {
|
|
441
|
+
console.log(`
|
|
442
|
+
\uD83D\uDEE1️ Shield - File Protection for AI Agents
|
|
443
|
+
|
|
444
|
+
Usage:
|
|
445
|
+
shield <command> [options]
|
|
446
|
+
|
|
447
|
+
Commands:
|
|
448
|
+
watch [path] Start watching a directory (default: current dir)
|
|
449
|
+
exec <command> Snapshot workspace, run command, then allow restore
|
|
450
|
+
snapshot [path] Take a one-time snapshot of all files
|
|
451
|
+
restore [file] Restore a file to its backed-up version
|
|
452
|
+
list List all backups
|
|
453
|
+
clean [--days=N] Remove backups older than N days (default: 7)
|
|
454
|
+
status Show backup statistics
|
|
455
|
+
help Show this help message
|
|
456
|
+
|
|
457
|
+
Options:
|
|
458
|
+
--path=<dir> Specify workspace directory
|
|
459
|
+
--days=<N> For clean command: max age in days
|
|
460
|
+
|
|
461
|
+
Examples:
|
|
462
|
+
shield watch ./my-project
|
|
463
|
+
shield exec -- npm run agent-task
|
|
464
|
+
shield restore src/index.ts
|
|
465
|
+
shield clean --days=3
|
|
466
|
+
shield status
|
|
467
|
+
`);
|
|
468
|
+
}
|
|
469
|
+
async function runCli(argv) {
|
|
470
|
+
const options = parseArgs(argv.slice(2));
|
|
471
|
+
switch (options.command) {
|
|
472
|
+
case "watch":
|
|
473
|
+
await cmdWatch(options);
|
|
474
|
+
break;
|
|
475
|
+
case "exec":
|
|
476
|
+
await cmdExec(options, argv);
|
|
477
|
+
break;
|
|
478
|
+
case "snapshot":
|
|
479
|
+
await cmdSnapshot(options);
|
|
480
|
+
break;
|
|
481
|
+
case "restore":
|
|
482
|
+
await cmdRestore(options);
|
|
483
|
+
break;
|
|
484
|
+
case "list":
|
|
485
|
+
await cmdList(options);
|
|
486
|
+
break;
|
|
487
|
+
case "clean":
|
|
488
|
+
await cmdClean(options);
|
|
489
|
+
break;
|
|
490
|
+
case "status":
|
|
491
|
+
await cmdStatus(options);
|
|
492
|
+
break;
|
|
493
|
+
case "help":
|
|
494
|
+
default:
|
|
495
|
+
printHelp();
|
|
496
|
+
break;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
async function getConfig(options) {
|
|
500
|
+
const pathArg = options.flags["path"] || options.args[0] || ".";
|
|
501
|
+
const workspace = resolve(pathArg);
|
|
502
|
+
if (!existsSync2(workspace)) {
|
|
503
|
+
console.error(`Error: Directory not found: ${workspace}`);
|
|
504
|
+
process.exit(1);
|
|
505
|
+
}
|
|
506
|
+
return getDefaultConfig(workspace);
|
|
507
|
+
}
|
|
508
|
+
async function cmdWatch(options) {
|
|
509
|
+
const config = await getConfig(options);
|
|
510
|
+
const backupManager = new BackupManager(config);
|
|
511
|
+
const watcher = new ShieldWatcher(config, backupManager);
|
|
512
|
+
watcher.start();
|
|
513
|
+
process.on("SIGINT", () => {
|
|
514
|
+
console.log(`
|
|
515
|
+
`);
|
|
516
|
+
watcher.stop();
|
|
517
|
+
const stats = backupManager.getStats();
|
|
518
|
+
console.log(`
|
|
519
|
+
\uD83D\uDCCA Session summary: ${stats.totalBackups} backups, ${stats.uniqueFiles} unique files`);
|
|
520
|
+
process.exit(0);
|
|
521
|
+
});
|
|
522
|
+
await new Promise(() => {});
|
|
523
|
+
}
|
|
524
|
+
async function cmdExec(options, rawArgv) {
|
|
525
|
+
const dashDashIndex = rawArgv.indexOf("--");
|
|
526
|
+
if (dashDashIndex === -1 || dashDashIndex === rawArgv.length - 1) {
|
|
527
|
+
console.error("Usage: shield exec -- <command>");
|
|
528
|
+
console.error("Example: shield exec -- npm run agent-task");
|
|
529
|
+
process.exit(1);
|
|
530
|
+
}
|
|
531
|
+
const commandArgs = rawArgv.slice(dashDashIndex + 1);
|
|
532
|
+
const pathArg = options.flags["path"] || ".";
|
|
533
|
+
const workspace = resolve(pathArg);
|
|
534
|
+
const config = getDefaultConfig(workspace);
|
|
535
|
+
const backupManager = new BackupManager(config);
|
|
536
|
+
console.log("\uD83D\uDEE1️ Shield Exec Mode");
|
|
537
|
+
console.log("─".repeat(50));
|
|
538
|
+
console.log("\uD83D\uDCF8 Taking pre-execution snapshot...");
|
|
539
|
+
const snapshot = backupManager.snapshotWorkspace();
|
|
540
|
+
console.log(`✓ Snapshot complete: ${snapshot.backed} files backed up, ${snapshot.skipped} skipped`);
|
|
541
|
+
console.log("─".repeat(50));
|
|
542
|
+
console.log(`\uD83D\uDE80 Running: ${commandArgs.join(" ")}`);
|
|
543
|
+
console.log("─".repeat(50));
|
|
544
|
+
const child = spawn(commandArgs[0], commandArgs.slice(1), {
|
|
545
|
+
stdio: "inherit",
|
|
546
|
+
shell: true,
|
|
547
|
+
cwd: workspace
|
|
548
|
+
});
|
|
549
|
+
await new Promise((resolve2, reject) => {
|
|
550
|
+
child.on("close", (code) => {
|
|
551
|
+
console.log("─".repeat(50));
|
|
552
|
+
if (code === 0) {
|
|
553
|
+
console.log("✓ Command completed successfully");
|
|
554
|
+
} else {
|
|
555
|
+
console.log(`⚠ Command exited with code ${code}`);
|
|
556
|
+
}
|
|
557
|
+
console.log(`
|
|
558
|
+
\uD83D\uDCA1 To restore files, run: shield restore <file>`);
|
|
559
|
+
console.log(" To list all backups: shield list");
|
|
560
|
+
resolve2();
|
|
561
|
+
});
|
|
562
|
+
child.on("error", reject);
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
async function cmdSnapshot(options) {
|
|
566
|
+
const config = await getConfig(options);
|
|
567
|
+
const backupManager = new BackupManager(config);
|
|
568
|
+
console.log("\uD83D\uDCF8 Taking snapshot...");
|
|
569
|
+
const result = backupManager.snapshotWorkspace();
|
|
570
|
+
console.log(`✓ Complete: ${result.backed} files backed up, ${result.skipped} skipped`);
|
|
571
|
+
}
|
|
572
|
+
async function cmdRestore(options) {
|
|
573
|
+
const config = await getConfig(options);
|
|
574
|
+
const backupManager = new BackupManager(config);
|
|
575
|
+
const fileArg = options.args[0];
|
|
576
|
+
if (!fileArg) {
|
|
577
|
+
const backups = backupManager.getAllBackups();
|
|
578
|
+
if (backups.length === 0) {
|
|
579
|
+
console.log("No backups available");
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
console.log(`Available backups (use 'shield restore <file>' to restore):
|
|
583
|
+
`);
|
|
584
|
+
const uniqueFiles = new Map;
|
|
585
|
+
for (const backup of backups) {
|
|
586
|
+
if (!uniqueFiles.has(backup.originalPath)) {
|
|
587
|
+
uniqueFiles.set(backup.originalPath, backup);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
for (const [path, backup] of uniqueFiles) {
|
|
591
|
+
console.log(` ${path} (${formatTimeAgo(backup.timestamp)})`);
|
|
592
|
+
}
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
console.log(`\uD83D\uDD04 Restoring: ${fileArg}`);
|
|
596
|
+
const success = backupManager.restoreLatest(fileArg);
|
|
597
|
+
if (success) {
|
|
598
|
+
console.log(`✓ Restored: ${fileArg}`);
|
|
599
|
+
} else {
|
|
600
|
+
console.log(`✗ Failed to restore: ${fileArg}`);
|
|
601
|
+
process.exit(1);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async function cmdList(options) {
|
|
605
|
+
const config = await getConfig(options);
|
|
606
|
+
const backupManager = new BackupManager(config);
|
|
607
|
+
const backups = backupManager.getAllBackups();
|
|
608
|
+
if (backups.length === 0) {
|
|
609
|
+
console.log("No backups found");
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
console.log(`\uD83D\uDCCB All Backups (${backups.length} total)
|
|
613
|
+
`);
|
|
614
|
+
for (const backup of backups.slice(0, 50)) {
|
|
615
|
+
const timeStr = formatTimeAgo(backup.timestamp);
|
|
616
|
+
const sizeStr = formatBytes(backup.size);
|
|
617
|
+
console.log(` ${backup.originalPath}`);
|
|
618
|
+
console.log(` └─ ${timeStr} | ${sizeStr}`);
|
|
619
|
+
}
|
|
620
|
+
if (backups.length > 50) {
|
|
621
|
+
console.log(`
|
|
622
|
+
... and ${backups.length - 50} more`);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
async function cmdClean(options) {
|
|
626
|
+
const config = await getConfig(options);
|
|
627
|
+
const backupManager = new BackupManager(config);
|
|
628
|
+
const days = parseInt(options.flags["days"]) || 7;
|
|
629
|
+
console.log(`\uD83E\uDDF9 Cleaning backups older than ${days} days...`);
|
|
630
|
+
const result = backupManager.cleanOldBackups(days);
|
|
631
|
+
console.log(`✓ Removed ${result.removed} backups, freed ${formatBytes(result.freedBytes)}`);
|
|
632
|
+
}
|
|
633
|
+
async function cmdStatus(options) {
|
|
634
|
+
const config = await getConfig(options);
|
|
635
|
+
const backupManager = new BackupManager(config);
|
|
636
|
+
const stats = backupManager.getStats();
|
|
637
|
+
console.log(`\uD83D\uDCCA Shield Status
|
|
638
|
+
`);
|
|
639
|
+
console.log(` Workspace: ${config.workspace}`);
|
|
640
|
+
console.log(` Vault: ${config.vaultDir}`);
|
|
641
|
+
console.log(` Total Backups: ${stats.totalBackups}`);
|
|
642
|
+
console.log(` Unique Files: ${stats.uniqueFiles}`);
|
|
643
|
+
console.log(` Total Size: ${formatBytes(stats.totalSize)}`);
|
|
644
|
+
console.log(` Sessions: ${stats.sessions}`);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// src/index.ts
|
|
648
|
+
runCli(process.argv).catch((err) => {
|
|
649
|
+
console.error("Error:", err.message);
|
|
650
|
+
process.exit(1);
|
|
651
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "agentshield",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Instant file protection for AI agent operations - hardlink-based zero-copy backup system",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"shield": "dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"dev": "bun run src/index.ts",
|
|
18
|
+
"build:npm": "bun build ./src/index.ts --outdir dist --target node && echo '#!/usr/bin/env node' | cat - dist/index.js > dist/temp && mv dist/temp dist/index.js && chmod +x dist/index.js",
|
|
19
|
+
"build:bin": "bun build --compile ./src/index.ts --outfile shield",
|
|
20
|
+
"build:bin:windows": "bun build --compile --target=bun-windows-x64 ./src/index.ts --outfile shield.exe",
|
|
21
|
+
"build:bin:linux": "bun build --compile --target=bun-linux-x64 ./src/index.ts --outfile shield-linux",
|
|
22
|
+
"build:bin:all": "bun run build:bin && bun run build:bin:windows && bun run build:bin:linux",
|
|
23
|
+
"prepublishOnly": "bun run build:npm"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"agent",
|
|
27
|
+
"backup",
|
|
28
|
+
"protection",
|
|
29
|
+
"hardlink",
|
|
30
|
+
"rollback",
|
|
31
|
+
"ai-safety"
|
|
32
|
+
],
|
|
33
|
+
"author": "tomsun28",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/tomsun28/agentshield.git"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://github.com/tomsun28/agentshield#readme",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/tomsun28/agentshield/issues"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=18.0.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/bun": "latest",
|
|
51
|
+
"typescript": "^5.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|