Skip to content

Commit bdb9143

Browse files
feat: harden harness and demand-load context
1 parent 9d32ad2 commit bdb9143

31 files changed

Lines changed: 2735 additions & 664 deletions

‎AGENTS.md‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,28 @@
11
# FileMint Agent Guide
22

3-
Use the project in SPEC-first order.
4-
5-
1. Read `specs/SPEC.md`.
6-
2. Read `specs/HARNESS.md`.
7-
3. Run `make verify` before changing behavior when the local Swift toolchain is available.
8-
4. Update SPEC first when product behavior changes.
9-
5. Add or update harness/unit coverage for naming, templates, creation, or preferences behavior.
10-
6. Keep deterministic behavior in `CorePackage`.
11-
7. Keep Finder API usage in `FinderSyncExtension`.
12-
8. Keep SwiftUI settings code in `App/FileMint`.
13-
9. Run `make verify` after implementation.
14-
15-
Do not edit generated `FileMint.xcodeproj` directly. Edit `project.yml`, then run `make project`.
3+
Use SPEC-first development with demand-loaded context.
4+
5+
1. Read [SPEC](specs/SPEC.md), the compact product overview and task router.
6+
2. Match the task's behavior and affected paths to its rows. Read only the selected
7+
domain contracts before editing; add domains when scope crosses a boundary.
8+
Shared files require the rules for the behavior being edited, not every domain.
9+
3. Read [HARNESS](specs/HARNESS.md) when choosing or running verification; load
10+
detailed checklists only for the affected surfaces.
11+
4. Load [AI Playbook](docs/AI_PLAYBOOK.md) only for cross-domain features, handoff,
12+
resuming a task or changing this workflow. Small fixes need no task document.
13+
5. Do not preload domain directories, acceptance history, roadmaps, research,
14+
task archives or tool configuration. Follow a link only when the task needs it.
15+
16+
Keep these invariants across all tasks:
17+
18+
- Update the owning domain SPEC before intentional product behavior changes;
19+
bug fixes restore the existing contract. Add regression coverage for behavior.
20+
- Run `make verify` before behavior changes when Swift is available, and after
21+
implementation. Use HARNESS for additional checks and report any blocked checks.
22+
- Keep deterministic rules in `CorePackage`, Finder APIs in `FinderSyncExtension`,
23+
SwiftUI settings in `App/FileMint`, and native creation UI in `SharedUI`.
24+
- Preserve user files, preferences and authorization boundaries. No folder crawling,
25+
clipboard monitoring, path/content logging or unrequested publication.
26+
- Edit `project.yml`, then `make project`; never edit generated `FileMint.xcodeproj`.
27+
- Do not add package dependencies without a SPEC rationale. Report observed
28+
verification separately from assumptions and old evidence.
Lines changed: 139 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,155 @@
11
import Foundation
22

3-
public struct FileCreationHarnessCase: Codable, Equatable, Sendable {
4-
public var name: String
5-
public var templateID: String
6-
public var requestedFileName: String?
7-
public var existingFileNames: [String]
8-
public var expectedFileName: String
9-
public var expectedContentContains: [String]
3+
/// Constructible only through the shared loader. No unchecked array runner exists.
4+
public struct HarnessSuite: Sendable {
5+
public static let maximumBytes = 1_048_576
6+
public static let maximumDepth = 32
7+
public static let maximumCases = 1_000
8+
let cases: [HarnessCase]
9+
public var caseCount: Int { cases.count }
1010

11-
public init(
12-
name: String,
13-
templateID: String,
14-
requestedFileName: String?,
15-
existingFileNames: [String],
16-
expectedFileName: String,
17-
expectedContentContains: [String]
18-
) {
19-
self.name = name
20-
self.templateID = templateID
21-
self.requestedFileName = requestedFileName
22-
self.existingFileNames = existingFileNames
23-
self.expectedFileName = expectedFileName
24-
self.expectedContentContains = expectedContentContains
11+
private init(cases: [HarnessCase]) { self.cases = cases }
12+
13+
public static func load(data: Data) throws -> HarnessSuite {
14+
guard data.count <= maximumBytes else { throw sizeError }
15+
var json = try HarnessJSON(data)
16+
try json.validate()
17+
let document: HarnessDocument
18+
do {
19+
document = try JSONDecoder().decode(HarnessDocument.self, from: data)
20+
} catch {
21+
throw HarnessDiagnostic.decoding(error)
22+
}
23+
guard !document.cases.isEmpty, document.cases.count <= maximumCases else {
24+
throw HarnessDiagnostic(code: "caseCount", path: "$.cases", message: "Expected 1...1000 cases")
25+
}
26+
var identifiers = Set<String>()
27+
for (index, item) in document.cases.enumerated() {
28+
let path = "$.cases[\(index)]"
29+
guard !item.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
30+
identifiers.insert(item.id).inserted else {
31+
throw HarnessDiagnostic(code: "caseID", path: path + ".id", message: "Case IDs must be nonblank and unique")
32+
}
33+
guard !item.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
34+
throw HarnessDiagnostic(code: "caseName", path: path + ".name", message: "Case name must not be blank")
35+
}
36+
guard TemplateCatalog.template(withID: item.templateID) != nil else {
37+
throw HarnessDiagnostic(code: "template", path: path + ".templateID", message: "Unknown built-in template")
38+
}
39+
try validateFileName(item.expect.fileName, path: path + ".expect.fileName")
40+
var names = Set<String>()
41+
for (fileIndex, file) in item.existingFiles.enumerated() {
42+
let filePath = "\(path).existingFiles[\(fileIndex)].name"
43+
try validateFileName(file.name, path: filePath)
44+
guard names.insert(file.name).inserted else {
45+
throw HarnessDiagnostic(code: "fixtureName", path: filePath, message: "Duplicate fixture filename")
46+
}
47+
}
48+
}
49+
return HarnessSuite(cases: document.cases)
50+
}
51+
52+
public static func load(from url: URL) throws -> HarnessSuite {
53+
let handle: FileHandle
54+
do { handle = try FileHandle(forReadingFrom: url) }
55+
catch { throw HarnessDiagnostic(code: "inputRead", path: "$", message: "Cannot open suite input") }
56+
defer { try? handle.close() }
57+
var data = Data()
58+
do {
59+
while data.count <= maximumBytes {
60+
let chunk = try handle.read(upToCount: min(65_536, maximumBytes + 1 - data.count)) ?? Data()
61+
if chunk.isEmpty { break }
62+
data.append(chunk)
63+
}
64+
} catch {
65+
throw HarnessDiagnostic(code: "inputRead", path: "$", message: "Cannot read suite input")
66+
}
67+
return try load(data: data)
68+
}
69+
70+
private static var sizeError: HarnessDiagnostic {
71+
HarnessDiagnostic(code: "sizeLimit", path: "$", message: "Suite input exceeds 1 MiB")
2572
}
26-
}
2773

28-
public struct HarnessCaseResult: Equatable, Sendable {
29-
public var name: String
30-
public var createdFileName: String
31-
public var passed: Bool
74+
private static func validateFileName(_ name: String, path: String) throws {
75+
let forbidden = CharacterSet(charactersIn: "/\\:").union(.controlCharacters)
76+
guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
77+
name != ".", name != "..", name.unicodeScalars.allSatisfy({ !forbidden.contains($0) }) else {
78+
throw HarnessDiagnostic(code: "fileName", path: path, message: "Expected a single nonblank filename without separators or controls")
79+
}
80+
}
3281
}
3382

34-
public enum HarnessRunner {
35-
public static func run(
36-
cases: [FileCreationHarnessCase],
37-
workspaceRoot: URL,
38-
fileManager: FileManager = .default
39-
) throws -> [HarnessCaseResult] {
40-
let service = FileCreationService(fileManager: fileManager)
41-
let fixedDate = Date(timeIntervalSince1970: 1_704_067_200)
83+
private struct HarnessDocument: Decodable {
84+
let cases: [HarnessCase]
85+
init(from decoder: any Decoder) throws {
86+
let c = try harnessContainer(decoder, allowing: ["schemaVersion", "cases"])
87+
guard try c.decode(Int.self, forKey: HarnessKey("schemaVersion")) == 1 else {
88+
throw HarnessDiagnostic(code: "schemaVersion", path: "$.schemaVersion", message: "Expected schemaVersion 1")
89+
}
90+
cases = try c.decode([HarnessCase].self, forKey: HarnessKey("cases"))
91+
}
92+
}
4293

43-
return try cases.map { testCase in
44-
let caseRoot = workspaceRoot.appendingPathComponent(UUID().uuidString, isDirectory: true)
45-
try fileManager.createDirectory(at: caseRoot, withIntermediateDirectories: true)
94+
struct HarnessCase: Decodable, Sendable {
95+
let id: String
96+
let name: String
97+
let templateID: String
98+
let requestedFileName: String?
99+
let existingFiles: [HarnessFixture]
100+
let expect: HarnessExpectation
46101

47-
for existingFileName in testCase.existingFileNames {
48-
let existingURL = caseRoot.appendingPathComponent(existingFileName, isDirectory: false)
49-
fileManager.createFile(atPath: existingURL.path, contents: Data(), attributes: nil)
50-
}
102+
init(from decoder: any Decoder) throws {
103+
let c = try harnessContainer(decoder, allowing: ["id", "name", "templateID", "requestedFileName", "existingFiles", "expect"])
104+
id = try c.decode(String.self, forKey: HarnessKey("id"))
105+
name = try c.decode(String.self, forKey: HarnessKey("name"))
106+
templateID = try c.decode(String.self, forKey: HarnessKey("templateID"))
107+
requestedFileName = try c.decodeIfPresent(String.self, forKey: HarnessKey("requestedFileName"))
108+
existingFiles = try c.decode([HarnessFixture].self, forKey: HarnessKey("existingFiles"))
109+
expect = try c.decode(HarnessExpectation.self, forKey: HarnessKey("expect"))
110+
}
111+
}
51112

52-
guard let template = TemplateCatalog.template(withID: testCase.templateID) else {
53-
throw FileMintError.templateNotFound(testCase.templateID)
54-
}
113+
struct HarnessFixture: Decodable, Sendable {
114+
let name: String
115+
let content: String
116+
init(from decoder: any Decoder) throws {
117+
let c = try harnessContainer(decoder, allowing: ["name", "content"])
118+
name = try c.decode(String.self, forKey: HarnessKey("name"))
119+
content = try c.decode(String.self, forKey: HarnessKey("content"))
120+
}
121+
}
55122

56-
let result = try service.createFile(
57-
FileCreationRequest(
58-
destinationDirectory: caseRoot,
59-
template: template,
60-
requestedFileName: testCase.requestedFileName,
61-
collisionStrategy: .increment
62-
),
63-
now: fixedDate
64-
)
123+
struct HarnessExpectation: Decodable, Sendable {
124+
let fileName: String
125+
let content: HarnessContent
126+
init(from decoder: any Decoder) throws {
127+
let c = try harnessContainer(decoder, allowing: ["fileName", "content"])
128+
fileName = try c.decode(String.self, forKey: HarnessKey("fileName"))
129+
content = try c.decode(HarnessContent.self, forKey: HarnessKey("content"))
130+
}
131+
}
65132

66-
let content = try String(contentsOf: result.createdURL, encoding: .utf8)
67-
let contentMatches = testCase.expectedContentContains.allSatisfy { content.contains($0) }
68-
let fileNameMatches = result.createdURL.lastPathComponent == testCase.expectedFileName
133+
enum HarnessContent: Decodable, Sendable {
134+
case exact(String)
135+
case contains([String])
69136

70-
return HarnessCaseResult(
71-
name: testCase.name,
72-
createdFileName: result.createdURL.lastPathComponent,
73-
passed: fileNameMatches && contentMatches
74-
)
137+
init(from decoder: any Decoder) throws {
138+
let c = try harnessContainer(decoder, allowing: ["mode", "value", "values"])
139+
let mode = try c.decode(String.self, forKey: HarnessKey("mode"))
140+
switch mode {
141+
case "exact":
142+
try harnessKeys(c, allowing: ["mode", "value"])
143+
self = .exact(try c.decode(String.self, forKey: HarnessKey("value")))
144+
case "contains":
145+
try harnessKeys(c, allowing: ["mode", "values"])
146+
let values = try c.decode([String].self, forKey: HarnessKey("values"))
147+
guard !values.isEmpty, values.allSatisfy({ !$0.isEmpty }) else {
148+
throw HarnessDiagnostic(code: "content", path: harnessPath(c.codingPath) + ".values", message: "Expected nonempty UTF-8 fragments")
149+
}
150+
self = .contains(values)
151+
default:
152+
throw HarnessDiagnostic(code: "contentMode", path: harnessPath(c.codingPath) + ".mode", message: "Expected exact or contains")
75153
}
76154
}
77155
}
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import Foundation
2+
3+
/// The standard decoder discards duplicate object keys. Inspect raw keys first,
4+
/// keeping object scopes and escaped strings intact; Foundation decodes values.
5+
struct HarnessJSON {
6+
private let bytes: [UInt8]
7+
private var offset = 0
8+
9+
init(_ data: Data) throws {
10+
guard String(data: data, encoding: .utf8) != nil else {
11+
throw HarnessDiagnostic(code: "invalidUTF8", path: "$", message: "Input must be UTF-8 JSON")
12+
}
13+
bytes = Array(data)
14+
}
15+
16+
mutating func validate() throws {
17+
try value(depth: 0, path: "$")
18+
whitespace()
19+
guard offset == bytes.count else { throw invalid("Unexpected trailing input") }
20+
}
21+
22+
private mutating func value(depth: Int, path: String) throws {
23+
whitespace()
24+
guard offset < bytes.count else { throw invalid("Expected a JSON value") }
25+
switch bytes[offset] {
26+
case 123, 91: // object or array
27+
guard depth < HarnessSuite.maximumDepth else {
28+
throw HarnessDiagnostic(code: "depthLimit", path: path, message: "JSON nesting exceeds 32 levels")
29+
}
30+
let isObject = bytes[offset] == 123
31+
offset += 1
32+
whitespace()
33+
if consume(isObject ? 125 : 93) { return }
34+
var keys = Set<Data>()
35+
var index = 0
36+
while true {
37+
let childPath: String
38+
if isObject {
39+
whitespace()
40+
let key = try string()
41+
childPath = path + "." + String(key.prefix(80))
42+
guard keys.insert(Data(key.utf8)).inserted else {
43+
throw HarnessDiagnostic(code: "duplicateKey", path: childPath, message: "Duplicate JSON object key")
44+
}
45+
whitespace()
46+
guard consume(58) else { throw invalid("Expected ':' after an object key") }
47+
} else {
48+
childPath = "\(path)[\(index)]"
49+
}
50+
try value(depth: depth + 1, path: childPath)
51+
whitespace()
52+
if consume(isObject ? 125 : 93) { return }
53+
guard consume(44) else { throw invalid("Expected ',' or end of container") }
54+
index += 1
55+
}
56+
case 34:
57+
_ = try string()
58+
case 45, 48...57, 116, 102, 110: // number, true, false, null
59+
// The typed decoder validates scalar spelling/type after this scan.
60+
while offset < bytes.count && ![9, 10, 13, 32, 44, 93, 125].contains(bytes[offset]) {
61+
offset += 1
62+
}
63+
default:
64+
throw invalid("Expected a JSON value")
65+
}
66+
}
67+
68+
private mutating func string() throws -> String {
69+
let start = offset
70+
guard consume(34) else { throw invalid("Expected a JSON string") }
71+
while offset < bytes.count {
72+
let byte = bytes[offset]
73+
guard byte >= 32 else { throw invalid("Unescaped control character in string") }
74+
if byte == 92 {
75+
offset += 2 // Skip an escaped byte; Foundation validates the escape.
76+
} else if byte == 34 {
77+
offset += 1
78+
do {
79+
return try JSONDecoder().decode(String.self, from: Data(bytes[start..<offset]))
80+
} catch {
81+
throw invalid("Invalid string escape or Unicode scalar")
82+
}
83+
} else {
84+
offset += 1
85+
}
86+
}
87+
throw invalid("Unterminated JSON string")
88+
}
89+
90+
private mutating func whitespace() {
91+
while offset < bytes.count && [9, 10, 13, 32].contains(bytes[offset]) { offset += 1 }
92+
}
93+
94+
private mutating func consume(_ byte: UInt8) -> Bool {
95+
guard offset < bytes.count, bytes[offset] == byte else { return false }
96+
offset += 1
97+
return true
98+
}
99+
100+
private func invalid(_ message: String) -> HarnessDiagnostic {
101+
HarnessDiagnostic(code: "invalidJSON", path: "$", message: "\(message) at byte \(offset)")
102+
}
103+
}
104+
105+
struct HarnessKey: CodingKey {
106+
let stringValue: String
107+
var intValue: Int? { nil }
108+
init(_ value: String) { stringValue = value }
109+
init?(stringValue: String) { self.init(stringValue) }
110+
init?(intValue: Int) { return nil }
111+
}
112+
113+
func harnessPath(_ keys: [any CodingKey]) -> String {
114+
keys.reduce("$") { path, key in
115+
if let index = key.intValue { return "\(path)[\(index)]" }
116+
return path + "." + String(key.stringValue.prefix(80))
117+
}
118+
}
119+
120+
func harnessContainer(_ decoder: any Decoder, allowing keys: Set<String>) throws -> KeyedDecodingContainer<HarnessKey> {
121+
let container = try decoder.container(keyedBy: HarnessKey.self)
122+
try harnessKeys(container, allowing: keys)
123+
return container
124+
}
125+
126+
func harnessKeys(_ container: KeyedDecodingContainer<HarnessKey>, allowing keys: Set<String>) throws {
127+
if let unknown = container.allKeys.map(\.stringValue).filter({ !keys.contains($0) }).sorted().first {
128+
throw HarnessDiagnostic(code: "unknownField", path: harnessPath(container.codingPath + [HarnessKey(unknown)]),
129+
message: "Unknown field; allowed fields: \(keys.sorted().joined(separator: ", "))")
130+
}
131+
}

0 commit comments

Comments
 (0)